Metadata-Version: 2.4
Name: vs-graph
Version: 0.1.12
Summary: JSON-driven graph library for building agentic applications
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and derivative works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of discussing and
              improving the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and incorporated
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any
              Contribution embodied within the Work constitutes direct or
              contributory patent infringement, then any patent licenses granted to
              You under this License for that Work shall terminate as of the date
              such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" file as part of its distribution,
                  You must include a readable copy of the attribution notices
                  contained within such NOTICE file, in at least one of the
                  following places: within a NOTICE text file distributed as part
                  of the Derivative Works; within the Source form or documentation,
                  if provided along with the Derivative Works; or, within a display
                  generated by the Derivative Works, if and wherever such
                  third-party notices normally appear. The contents of the NOTICE
                  file are for informational purposes only and do not modify the
                  License. You may add Your own attribution notices within
                  Derivative Works that You distribute, alongside or as an addendum
                  to the NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, modify, and distribute
              Your modifications.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any conditions of TITLE,
              NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
              PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 VivekaSutra. All rights reserved.
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied. See the License for the specific language governing
           permissions and limitations under the License.
        
Keywords: graph,agent,langgraph,agentic,viveka,vs
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: langgraph>=0.2
Requires-Dist: pydantic<3,>=2.0
Requires-Dist: vs-common
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == "redis"
Requires-Dist: hiredis>=2.0; extra == "redis"
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Dynamic: license-file

# vs-graph

JSON-driven LangGraph wrapper for building agentic workflows — define graph topology in JSON, implement nodes and edges in Python, and get a fully wired, observable, checkpointed execution graph.

---

## Overview

`vs-graph` wraps [LangGraph](https://github.com/langchain-ai/langgraph) and eliminates the boilerplate of building agentic graphs: wiring nodes, routing edges, setting up checkpointers, and propagating trace events. You declare the graph structure in a JSON file, implement node logic by extending `VsBaseNode`, and wire routing logic by extending `VsBaseConditionalEdge` or `VsDynamicFanOutEdge`. The library handles everything else.

The `@node` and `@edge` decorators self-register implementations at import time. The `@graph` decorator on a graph class specifies which packages to auto-import so no manual import list is required.

---

## The Problem It Solves

### Without vs-graph

```python
# Manual LangGraph wiring — every graph requires this boilerplate
from langgraph.graph import StateGraph, START, END

sg = StateGraph(MyState)
sg.add_node("classifier", classifier_node.invoke)
sg.add_node("executor", executor_node.invoke)
sg.add_node("responder", responder_node.invoke)
sg.add_edge(START, "classifier")
sg.add_conditional_edges("classifier", routing_fn, {"execute": "executor", "default": "responder"})
sg.add_edge("executor", "responder")
sg.add_edge("responder", END)
checkpointer = MemorySaver()
graph = sg.compile(checkpointer=checkpointer)
```

Every graph has this same boilerplate. Adding a node requires updating both code and wiring.

### With vs-graph

```python
# graph topology is in JSON
# Python only contains business logic

@graph(nodes=["myapp.graph.nodes"], edges=["myapp.graph.edges"])
class MyGraph(VsBaseGraph[MyState]):
    def __init__(self):
        with open("my_graph.json") as f:
            graph_json = json.load(f)
        super().__init__(graph_json=graph_json, state_class=MyState)
        self.build()

graph = MyGraph()
result = await graph.invoke({"trace_id": "", "error": None, "user_input": "hello"})
```

---

## How It All Fits Together

```
@graph(nodes=[...], edges=[...])
class MyGraph(VsBaseGraph[MyState])
    └── __init__: load JSON, call build()

build()
    ├── _auto_import_packages()     # walks node/edge packages, triggers @node/@edge registration
    ├── _instantiate_nodes()        # VsNodeRegistry.create() for each JSON node definition
    ├── _instantiate_edges()        # VsEdgeRegistry.create() for conditional/dynamic_fan_out
    ├── _validate_graph()           # checks all node ids, edge targets, and exit nodes
    ├── _load_checkpointer()        # reads config.ini [graph] section
    └── _build_langgraph()          # compiles StateGraph with checkpointer

invoke(state)
    ├── auto-generates trace_id if not set
    └── StateGraph.ainvoke(state)
            └── per node: VsBaseNode.invoke()
                    ├── trace: "node started"
                    ├── execute(state)          ← your business logic
                    └── trace: "node completed" / "node failed"
            └── per conditional / dynamic_fan_out edge: async VsBaseEdge.route()
                    ├── _evaluate(state) / get_sends(state)   ← your routing logic
                    └── trace: "routing to next_node" / "fanning out to N branch(es)"
            (direct and fan_out edges are plain LangGraph edges — no wrapper, no trace)
```

---

## Graph JSON

The JSON file declares the graph topology. Python classes are referenced by the `name` field in each node/edge definition — matching the name passed to `@node(name="...")` or `@edge(name="...")`.

```json
{
  "version": "1.0",
  "name": "my_graph",
  "description": "Routes a user message to a tool run or a plain chat reply.",
  "entry_node": "classifier",
  "exit_nodes": ["responder"],
  "nodes": [
    { "id": "classifier", "name": "classifier_node", "config": {},
      "description": "Decides whether the message needs a tool or just an answer." },
    { "id": "executor",   "name": "executor_node",   "config": {},
      "description": "Runs the tool the classifier picked." },
    { "id": "responder",  "name": "responder_node",  "config": {},
      "description": "Turns whatever happened into a reply the user can read." }
  ],
  "edges": [
    {
      "type": "conditional",
      "source": "classifier",
      "edge_class": "classifier_routing_edge",
      "description": "Tool-worthy intents go to the executor, everything else answers directly.",
      "route": {
        "execute": "executor",
        "default": "responder"
      }
    },
    { "type": "direct", "source": "executor", "target": "responder" }
  ]
}
```

### JSON Fields

| Field | Required | Description |
|---|---|---|
| `name` | Yes | Graph name — used in logs and error messages |
| `version` | No | Version string (default `"1.0"`) |
| `description` | No | What this graph is for. Documentation only — read it and you know the workflow without opening Python. |
| `entry_node` | Yes | `id` of the node that receives the initial state |
| `exit_nodes` | Yes | List of node `id`s that connect to `END` |
| `nodes` | Yes | Array of node definitions |
| `nodes[].id` | Yes | Unique node id within this graph — used in edge source/target fields |
| `nodes[].name` | Yes | Registry name — must match the `@node(name="...")` decorator value |
| `nodes[].config` | No | Arbitrary dict passed to the node constructor as `self.config` |
| `nodes[].description` | No | Why this node exists. Available as `self.description` and attached to every trace event the node publishes. |
| `edges` | No | Array of edge definitions |
| `edges[].type` | Yes | `direct`, `fan_out`, `conditional`, or `dynamic_fan_out` |
| `edges[].source` | Yes | Node `id` this edge originates from |
| `edges[].target` | For `direct` | Target node `id` |
| `edges[].targets` | For `fan_out` | Array of target node `id`s (minimum 2) |
| `edges[].edge_class` | For `conditional`, `dynamic_fan_out` | Registry name matching `@edge(name="...")` |
| `edges[].route` | For `conditional` | Map of route keys to target node `id`s — must include `"default"` |
| `edges[].config` | No | Arbitrary dict passed to the edge constructor as `self.config` |
| `edges[].description` | No | Why this edge exists. Available as `self.description` and attached to every trace event the edge publishes. |

### Edge Types

| Type | Python class needed | Description |
|---|---|---|
| `direct` | No | Fixed single target — fully declared in JSON |
| `fan_out` | No | Fixed parallel targets — fully declared in JSON |
| `conditional` | Yes — extends `VsBaseConditionalEdge` | `_evaluate(state)` returns a route key; key is looked up in `route` map |
| `dynamic_fan_out` | Yes — extends `VsDynamicFanOutEdge` | `get_sends(state)` returns a list of `Send` objects for runtime branching |

---

## State

All graph state must extend `VsBaseGraphState`:

```python
from typing import Optional
from vs_graph.schema.vs_base_graph_state import VsBaseGraphState

class MyState(VsBaseGraphState):
    user_input: str
    intent: Optional[str]
    response: Optional[str]
```

`VsBaseGraphState` is a `TypedDict` providing:

| Field | Type | Description |
|---|---|---|
| `trace_id` | `str` | Auto-generated per `invoke()` call if not set. Links all trace events for this execution. |
| `error` | `Optional[VsGraphError]` | Populated by the framework when a node raises `VsUserException`. Contains `message`, `cause`, `stack_trace`. |
| `current_message` | `Optional[str]` | Convenience field for the current user-facing message. Not set by the framework. |

---

## Nodes

Extend `VsBaseNode` and implement `execute`. Decorate with `@node(name="...")` to self-register in `VsNodeRegistry`.

```python
from vs_graph.node.vs_base_node import VsBaseNode
from vs_graph.decorator.vs_node_decorator import node
from vs_graph.exception.vs_graph_exceptions import VsUserException, VsNodeExecutionException

@node(name="classifier_node")
class ClassifierNode(VsBaseNode[MyState]):

    async def execute(self, state: MyState) -> dict:
        if not state.get("user_input"):
            raise VsUserException("Input is required.")
        state["intent"] = "execute"
        await self.trace(state["trace_id"], "intent classified", data={"intent": state["intent"]})
        return state
```

### `@node` decorator

```python
@node(name="classifier_node")   # registers under key "classifier_node"
@node                           # registers under the class name
```

The `name` value must match the `"name"` field in the JSON node definition.

### What `invoke()` does (called by the graph, not you)

`VsBaseNode.invoke()` wraps your `execute()`:

1. Logs and publishes trace: `"node '{id}' started"`
2. Calls `await self.execute(state)`
3. On success: logs and publishes trace: `"node '{id}' completed"` with `duration_seconds`
4. On `VsUserException`: stores error in `state["error"]` and returns state (graph continues)
5. On `VsNodeExecutionException`: logs error and re-raises (graph stops)
6. On any other exception: logs error and re-raises (graph stops)

### Publishing trace events

```python
async def execute(self, state: MyState) -> dict:
    await self.trace(
        state["trace_id"],
        "retrieved context",
        data={"num_chunks": 8},
    )
    return state
```

`self.trace()` is a no-op if no `trace_publisher` was passed to the graph.

### Telling the user what is happening

A node that takes four seconds looks exactly like one that has hung. Set `thinking_message` and the framework publishes it the moment the node starts, so something human appears while the work happens:

```python
@node(name="planning_node")
class PlannerNode(VsBaseNode[MyState]):

    thinking_message = "Working out how to answer this…"

    async def execute(self, state: MyState) -> dict:
        ...
```

Or per-deployment, without touching the code:

```json
{
  "id": "planning",
  "name": "planning_node",
  "config": { "thinking_message": "Working out how to answer this…" }
}
```

The config value wins over the class attribute. It is published with `data["event"] = "node_thinking"`, ahead of the node's `started` event, so a consumer can show it to the user and route the rest to a log.

Override `resolve_thinking_message(state)` when the message depends on the state — or to say nothing at all. `VsHydrationNode` does exactly that: it stays quiet when the checkpoint is already warm, because there is nothing to wait for.

```python
def resolve_thinking_message(self, state: MyState) -> Optional[str]:
    if not state.get("documents"):
        return None                       # nothing to search, so do not claim to be searching
    return f"Searching {len(state['documents'])} documents…"
```

### Quietening a chatty node

Every node publishes five lifecycle events. Set `trace_lifecycle = False` on the class, or `"trace_lifecycle": false` in the node's JSON config, to silence those while keeping anything the node publishes itself.

### Node constructor args

`VsBaseNode.__init__` receives:

| Parameter | Source |
|---|---|
| `node_id` | The `id` field from the JSON node definition |
| `config` | The `config` dict from the JSON node definition |
| `description` | The `description` field from the JSON node definition |
| `trace_publisher` | The publisher passed to `VsBaseGraph.__init__` |

Access them as `self.node_id`, `self.config`, `self.description`, `self.trace_publisher`.

---

## Prebuilt Nodes

Some nodes are the same in every agentic graph. `vs-graph` ships them so you don't rewrite them each time:

- **Shipped defaults** — fully implemented and self-registered. `VsHeuristicInputGuardNode` (as `vs_guard_node`) and `VsInputValidationNode` (as `vs_input_validation_node`, with JSON state rules): drop the registry name into your JSON and configure it. No node subclass needed.
- **Half-built** — orchestration, tracing, and skip logic done; you implement one method (`VsHydrationNode.load`, `VsModerationInputGuardNode.moderate`). Subclass, `@node(name="...")`, reference it in JSON.

### Input Validation and Preprocessing

`VsInputValidationNode` is a concrete, optional node for checking input before retrieval, model calls, or tool execution. It supports two mutually exclusive modes:

| Mode | Configuration | Application node subclass? | Outputs |
|---|---|---|---|
| JSON state validation | `config.state_validation` rules | No; use `vs_input_validation_node` | `input_valid`, `validation_errors` |
| Pydantic object validation | `input_schema` on a registered subclass; optional `config.input_key` | Yes | Above, plus `normalized_input` |

Importing `vs_graph` automatically imports and registers the concrete node through `vs_graph/__init__.py`. Your graph already imports this package, so no additional node-package import is needed for JSON state validation. Custom schema subclasses still need the application's usual `@graph(nodes=[...])` import configuration.

Use it when different callers feed your graph, invalid requests need a correction branch, or you want consistent validation errors across agents. Skip it when the application boundary already performs the same checks. A `TypedDict` state schema describes channels and types but does not enforce request values at runtime.

This is separate from an input guard: validation checks whether data is usable (required fields, types, ranges, formats); guards check whether content is allowed. Neither replaces authorization or checks against current external data, such as room availability at booking time.

#### Validate state fields directly from JSON

Add this node definition to your graph's `nodes` list. `id` is local to your graph; `name` is the built-in registry name:

```json
{
  "id": "chat_request_validation",
  "name": "vs_input_validation_node",
  "config": {
    "state_validation": [
      {
        "key": "conversation_id",
        "rules": [
          {"type": "required_string", "error_message": "Conversation ID is required and must be a non-blank string."}
        ]
      },
      {
        "key": "retries",
        "rules": [
          {"type": "required"},
          {"type": "not_null"},
          {"type": "integer", "error_message": "Retry count must be a whole number."},
          {"type": "gt", "value": 30, "error_message": "Retry count must be greater than 30."}
        ]
      }
    ]
  }
}
```

`gt: 30` literally requires a value greater than 30; use `lte` if you mean an upper limit. Keys refer to top-level state channels, not nested paths. Declare those channels and the validation outputs in your graph state:

```python
from vs_graph.schema.vs_input_validation_state import VsInputValidationState


class ChatState(VsInputValidationState):
    conversation_id: str
    retries: int
```

For `{"conversation_id": null, "retries": 20}`, the node returns:

```json
{
  "input_valid": false,
  "validation_errors": [
    {"field": "conversation_id", "code": "required_string", "message": "Conversation ID is required and must be a non-blank string."},
    {"field": "retries", "code": "gt", "message": "Retry count must be greater than 30."}
  ]
}
```

On success it returns `{"input_valid": true, "validation_errors": []}`. Both outputs are replaced on every run, clearing stale results after correction. Original state values are never changed or coerced, and `normalized_input` is not written in this mode. The node does not write `state["error"]` or automatically stop execution.

Each rule accepts an optional non-empty `error_message`. Omit it for a generated default message. The machine-readable `code` remains the rule type regardless of wording.

| Rule `type` | `value` | Behavior |
|---|---|---|
| `required` | None | Key must exist; explicit null still counts as present. |
| `required_string` | None | Combined presence, non-null, and non-blank string check. Rejects missing keys, null, empty/whitespace-only strings, and non-string values. Does not trim the value. |
| `not_null` | None | A present value must not be null. Add `required` to also reject missing keys. |
| `not_blank` | None | Value must be a string containing non-whitespace characters; does not trim it. |
| `string` | None | Strict string check. |
| `integer` | None | Strict integer check; rejects strings, floats, and booleans. |
| `boolean` | None | Strict boolean check. |
| `gt`, `gte`, `lt`, `lte` | Finite number | Numeric comparison; state value must also be a finite integer/float, excluding booleans. |
| `min_length`, `max_length` | Non-negative integer | Inclusive length constraint on a string or collection. |
| `one_of` | Non-empty list | Type-sensitive membership; `true`, `1`, and `1.0` are distinct. |

Use `required_string` for a mandatory string such as a conversation ID. It replaces `required` + `not_null` + `not_blank` with one rule and one optional custom message. Keep the separate rules when you need different messages or optional fields.

Missing keys are skipped unless `required` or `required_string` is configured. Null values are skipped unless `not_null` or `required_string` is configured. For present non-null values, remaining rules run in configured order and stop at the first failure for that field; other fields are still checked. This yields one actionable error per field and avoids comparing invalid types. Put type checks before range checks for clearer errors.

Unknown rules, missing/invalid rule parameters, blank custom messages, duplicate field entries, and malformed configuration fail during node construction (and therefore graph build). Validation output channels cannot themselves be configured as input fields. Do not combine `state_validation` with `input_schema`, `input_key`, or `input_keys`.

#### Route after JSON state validation

Make `chat_request_validation` your `entry_node` or connect an earlier node to it. Register an application conditional edge:

```python
from vs_graph.decorator.vs_edge_decorator import edge
from vs_graph.edge.vs_base_conditional_edge import VsBaseConditionalEdge


@edge(name="chat_validation_route")
class ChatValidationRoute(VsBaseConditionalEdge[ChatState]):
    def _evaluate(self, state: ChatState) -> str:
        return "valid" if state.get("input_valid", False) else "invalid"
```

Add this edge definition to the graph JSON, declaring your application's `process_chat` and `request_correction` nodes separately:

```json
{
  "type": "conditional",
  "source": "chat_request_validation",
  "edge_class": "chat_validation_route",
  "route": {
    "valid": "process_chat",
    "invalid": "request_correction",
    "default": "request_correction"
  }
}
```

Import the application's edge package with `@graph(edges=[...])` as usual. Do not also add an unconditional edge to processing, since it would execute for invalid input too.

#### UI processing traces

Both validation modes publish progress and outcome messages through the graph's injected `trace_publisher`. Connect that publisher to your UI stream; with no publisher, nothing is sent. Default messages are:

| Stage | Message | `data.event` |
|---|---|---|
| Before validation | `Validating the request…` | `node_thinking` |
| Valid input | `Request looks good.` | `validation_passed` |
| Invalid input | `Please check the request details.` | `validation_failed` |

Customize them in the node's JSON `config`, alongside `state_validation`:

```json
{
  "trace_processing": true,
  "trace_lifecycle": false,
  "thinking_message": "Validating the Request",
  "passed_message": "Request looks good",
  "failed_message": "Some request details need attention"
}
```

`trace_processing` defaults to `true`; set it to `false` to silence both the validation progress and outcome messages. `trace_lifecycle` independently controls the technical start/completed/error events inherited from `VsBaseNode`. Set both flags to `false` to silence all automatic traces for this node. Set an individual message to `null` or `""` to suppress only that message.

The UI consumer should display `node_thinking`, `validation_passed`, and `validation_failed` events. Outcomes include `node_id`, `input_valid`, and `error_count`; they do not include request values or detailed validation errors. Failed validation uses the WARN level and remains a normal state result. Unexpected implementation exceptions use the base node's failure tracing instead of a validation outcome. Publisher failures do not change validation results.

#### Pydantic mode: validate an object stored in state

Use the existing schema mode when you need parsing, defaults, normalization, nested structures, or custom Python business rules. The following sections describe this mode; existing subclasses remain compatible.

#### Define the state and application schema

Extend `VsInputValidationState` to declare the three output channels. Existing state classes can instead declare the same fields directly. Do not add append reducers to these channels: each validation run replaces its previous result.

```python
from typing import Any
from pydantic import BaseModel, ConfigDict, Field

from vs_graph.decorator.vs_node_decorator import node
from vs_graph.node.vs_input_validation_node import VsInputValidationNode
from vs_graph.schema.vs_input_validation_state import VsInputValidationState


class BookingState(VsInputValidationState):
    request: dict[str, Any]


class BookingRequest(BaseModel):
    model_config = ConfigDict(strict=True, extra="forbid", str_strip_whitespace=True)

    room_id: str = Field(min_length=1)
    attendees: int = Field(gt=0)
    duration_minutes: int = Field(gt=0, le=480)


@node(name="booking_input_validation")
class BookingInputValidationNode(VsInputValidationNode[BookingState]):
    input_schema = BookingRequest
```

The schema controls coercion, defaults, extra fields, and field-specific normalization. This example rejects `"3"` as an attendee count; use the schema's normal Pydantic settings if coercion is desired. Only `request` is validated, not the entire graph state.

#### Add it to the graph and route on the result

Reference the application subclass by its registered name:

```json
{
  "id": "validate_input",
  "name": "booking_input_validation",
  "config": {"input_key": "request"},
  "description": "Checks booking details before attempting a reservation."
}
```

Make `validate_input` the graph's `entry_node` (or connect an earlier node to it). Import the application's node and edge packages through `@graph(nodes=[...], edges=[...])` as usual. Define a conditional edge:

```python
from vs_graph.decorator.vs_edge_decorator import edge
from vs_graph.edge.vs_base_conditional_edge import VsBaseConditionalEdge


@edge(name="booking_validation_route")
class BookingValidationRoute(VsBaseConditionalEdge[BookingState]):
    def _evaluate(self, state: BookingState) -> str:
        return "valid" if state.get("input_valid", False) else "invalid"
```

Add the following to the JSON `edges` list. `book_room` and `request_correction` must be node IDs declared by your application:

```json
{
  "type": "conditional",
  "source": "validate_input",
  "edge_class": "booking_validation_route",
  "route": {
    "valid": "book_room",
    "invalid": "request_correction",
    "default": "request_correction"
  }
}
```

The node does not route automatically. Avoid an unconditional edge from validation to the booking node, since that would also execute for invalid input.

#### Output contract

For `{"request": {"room_id": " ROOM-12 ", "attendees": 3, "duration_minutes": 30}}`, the returned delta is:

```python
{
    "normalized_input": {"room_id": "ROOM-12", "attendees": 3, "duration_minutes": 30},
    "input_valid": True,
    "validation_errors": [],
}
```

For `attendees=-3`, it returns:

```python
{
    "normalized_input": None,
    "input_valid": False,
    "validation_errors": [
        {"field": "attendees", "code": "greater_than", "message": "Input should be greater than 0"}
    ],
}
```

Downstream processing uses `state["normalized_input"]` after the valid branch. The raw request is preserved. All three output channels are overwritten on each run, clearing stale errors after correction and stale normalized data after failure. Missing input is validated as `None`, producing a schema error. Nested error locations use dotted paths such as `participants.0.email`; root errors use `$`.

Expected schema and business-rule failures are ordinary state results, not `VsUserException`, and do not write `state["error"]`. Unexpected hook exceptions propagate and stop execution. Pydantic error inputs/context are omitted from the returned errors; application-written validation messages should still avoid embedding sensitive values.

#### Extension points

| Member | Default / behavior |
|---|---|
| `input_schema` | Required application class attribute: Pydantic v2 `BaseModel` subclass that dumps to a dictionary. Scalar/list `RootModel` schemas are unsupported. |
| `input_key` | Class attribute defaulting to `"request"`; overridable through JSON `config.input_key`. Names one top-level state channel, not a dotted path. |
| `normalize_input(raw_input)` | Optional synchronous hook before schema validation. Receives a deep copy; returns the input to validate. Default passes it through. |
| `validate_input(state, normalized_input)` | Optional synchronous hook after schema validation. Returns/yields `VsInputValidationError` dictionaries. Treat its arguments as read-only. Default returns no errors. |
| `execute(state)` | Provided template; normally do not override. Normalization → schema validation → application rules → state delta. |

For example, an application can extend the booking node with a rule based on other state:

```python
from vs_graph.schema.vs_input_validation_state import VsInputValidationError


class CapacityBookingState(BookingState):
    max_attendees: int


@node(name="capacity_booking_input_validation")
class CapacityBookingInputValidationNode(BookingInputValidationNode):
    def validate_input(self, state: CapacityBookingState, normalized_input: dict):
        if normalized_input["attendees"] > state["max_attendees"]:
            yield VsInputValidationError(
                field="attendees",
                code="capacity_exceeded",
                message="The attendee count exceeds the allowed capacity.",
            )
```

Use `CapacityBookingState` as the graph's state class for this variant. Keep database/API checks in a separate node when they require asynchronous I/O.

### VsHydrationNode

The typical first node in a conversational graph. LangGraph loads the checkpoint for the current `thread_id` into `state` before the graph runs — but a checkpoint only exists while it's warm. New conversation, or Redis TTL expired after 30 days of silence, means an empty `state`. `VsHydrationNode` rebuilds it from your durable store (ctx-resolver, DB, …) so the agent keeps its memory across gaps the checkpointer can't cover.

`execute()` is already written:

1. `is_hydrated(state)` → if true, the checkpoint was warm, return `{}` and move on
2. otherwise `await load(state)` and return the delta — LangGraph checkpoints it from there

You implement `load`:

```python
from vs_graph.node.vs_hydration_node import VsHydrationNode
from vs_graph.decorator.vs_node_decorator import node

@node(name="hydration_node")
class ConversationHydrationNode(VsHydrationNode[MyState]):

    hydration_keys = ["history", "resolved_context"]

    async def load(self, state: MyState) -> dict:
        cid = state["conversation_id"]
        return {
            "history": await conversation_store.get_history(cid),
            "resolved_context": await ctx_resolver.resolve(cid),
        }
```

| Member | Kind | Description |
|---|---|---|
| `load(state)` | Abstract — you implement | Fetch prior context from the durable store (key off `conversation_id` / `user_id` in `state`) and return it as a state delta. |
| `hydration_keys` | Class attr | State keys that, once all non-`None`, mean hydration already happened. Set this and you never touch `is_hydrated`. |
| `is_hydrated(state)` | Override (optional) | Default: all `hydration_keys` are non-`None`. Override for custom "is the state warm?" logic. |
| `execute(state)` | Provided — don't override | The skip-or-load template above. |

Emits `node '{id}' hydrated` or `node '{id}' already hydrated` trace events.

### Input Guards

Run before the graph does anything expensive. A blocked message raises `VsUserException`, which the graph stores in `state["error"]` and carries to your responder — so the user gets a clean "that's not allowed" instead of a crash or a wasted LLM bill.

Two flavours, both extending `VsInputGuardNode`:

| Node | I/O | Implement | Use for |
|---|---|---|---|
| `VsHeuristicInputGuardNode` | none | nothing — self-registered as `vs_guard_node`, configure `patterns` in JSON; subclass only for `rules()` | Cheap fast-fail — obvious junk, banned strings, prompt-injection tells |
| `VsModerationInputGuardNode` | one call | `moderate(text)` | A real moderation model — hate, self-harm, sexual, violence, … |

Common shape:

| Member | Kind | Description |
|---|---|---|
| `check(state, text)` | Abstract on `VsInputGuardNode`; each flavour implements it | Returns a `VsGuardDecision`. |
| `guard_text(state)` | Override (optional) | What text to inspect. Default: `state["current_message"]`. |
| `execute(state)` | Provided — don't override | Runs `check`, traces `guard passed` / `guard blocked`, raises `VsUserException` on block. |

`VsGuardDecision(allowed, reason=None, category=None, scores={})` — `reason` is what the user sees.

#### Heuristic — `VsHeuristicInputGuardNode` (shipped default)

This one is a **default node**: `vs-graph` imports it, it self-registers under `vs_guard_node`, and it's ready the moment you `import vs_graph`. Nothing to subclass, nothing to write.

**Why use it:** it's the cheapest guard you can put in front of a graph — pure regex, zero I/O, runs in microseconds. Catch the obvious stuff (banned strings, prompt-injection tells like "ignore previous instructions", oversized payloads) here and you never pay for the LLM call, the retrieval, or the moderation round-trip on garbage input. Put it first, chain a `VsModerationInputGuardNode` after it for the cases regex can't judge.

**How to use it:** add it to the graph JSON as your `entry_node` (or right after hydration) and pass patterns in `config` — no Python:

```json
{
  "id": "guard",
  "name": "vs_guard_node",
  "config": {
    "patterns": ["ignore (all )?previous instructions", "\\bBEGIN\\s+SYSTEM\\s+PROMPT\\b"],
    "block_reason": "That request can't be processed."
  }
}
```

Subclass only when you need dynamic `rules()`:

```python
from vs_graph.node.vs_heuristic_input_guard_node import VsHeuristicInputGuardNode
from vs_graph.decorator.vs_node_decorator import node

@node(name="length_guard")
class LengthGuard(VsHeuristicInputGuardNode[MyState]):

    def rules(self, state, text):
        if len(text) > 8000:
            yield "Message is too long."
```

#### Moderation

Subclass and implement `moderate()` — return a `VsModerationResult`. `check()` does the thresholding (`threshold`, `blocked_categories`).

`VsModerationResult(scores={category: float}, flagged=None, raw=None)`.

OpenAI (`omni-moderation-latest` — scores come back ready-made):

```python
from openai import AsyncOpenAI
from vs_graph.node.vs_moderation_input_guard_node import VsModerationInputGuardNode
from vs_graph.schema.vs_moderation_result import VsModerationResult
from vs_graph.decorator.vs_node_decorator import node

_openai = AsyncOpenAI()

@node(name="moderation_input_guard")
class OpenAiModerationGuard(VsModerationInputGuardNode[MyState]):

    threshold = 0.5

    async def moderate(self, text: str) -> VsModerationResult:
        resp = await _openai.moderations.create(
            model="omni-moderation-latest", input=text,
        )
        result = resp.results[0]
        return VsModerationResult(
            scores=dict(result.category_scores),
            flagged=result.flagged,
            raw=result.model_dump(),
        )
```

Claude (no moderation endpoint — ask Claude to score it, parse the JSON):

```python
import json
import anthropic
from vs_graph.node.vs_moderation_input_guard_node import VsModerationInputGuardNode
from vs_graph.schema.vs_moderation_result import VsModerationResult
from vs_graph.decorator.vs_node_decorator import node

_claude = anthropic.AsyncAnthropic()

_CATS = ["hate", "harassment", "self_harm", "sexual", "violence"]
_SYS = (
    "You are a content-moderation classifier. Score the user message from 0.0 to 1.0 "
    "for each of these categories: " + ", ".join(_CATS) + ". "
    'Reply with ONLY a JSON object mapping each category to its float score.'
)

@node(name="moderation_input_guard")
class ClaudeModerationGuard(VsModerationInputGuardNode[MyState]):

    threshold = 0.6

    async def moderate(self, text: str) -> VsModerationResult:
        msg = await _claude.messages.create(
            model="claude-opus-5",          # claude-haiku-4-5 is plenty for this, your call
            max_tokens=256,
            system=_SYS,
            messages=[{"role": "user", "content": text}],
        )
        raw = next(b.text for b in msg.content if b.type == "text")
        scores = {k: float(v) for k, v in json.loads(raw).items()}
        return VsModerationResult(scores=scores, raw=raw)
```

Chain them in the JSON — heuristic first (free), moderation next — by pointing the heuristic guard's edge at the moderation guard.

---

## Edges

### Direct edge

No Python class. Declared fully in JSON:

```json
{ "type": "direct", "source": "executor", "target": "responder" }
```

### Fan-out edge

No Python class. Declares fixed parallel targets in JSON (minimum 2):

```json
{
  "type": "fan_out",
  "source": "splitter",
  "targets": ["worker_a", "worker_b", "worker_c"]
}
```

All targets receive the same state and execute in parallel via LangGraph's native fan-out.

### Conditional edge

Extend `VsBaseConditionalEdge` and implement `_evaluate`. Decorate with `@edge(name="...")`:

```python
from vs_graph.edge.vs_base_conditional_edge import VsBaseConditionalEdge
from vs_graph.decorator.vs_edge_decorator import edge

@edge(name="classifier_routing_edge")
class ClassifierRoutingEdge(VsBaseConditionalEdge[MyState]):

    def _evaluate(self, state: MyState) -> str:
        if state.get("intent") == "execute":
            return "execute"
        return "default"
```

`_evaluate` returns a route key. The base class's async `route()` wrapper looks it up in the `route` map from JSON, publishes the routing trace, and returns the target node id. If the key is not in the map, it falls back to `"default"`. A `"default"` entry in the JSON `route` map is required.

JSON:

```json
{
  "type": "conditional",
  "source": "classifier",
  "edge_class": "classifier_routing_edge",
  "route": {
    "execute": "executor",
    "default": "responder"
  }
}
```

### Dynamic fan-out edge

Extend `VsDynamicFanOutEdge` and implement `get_sends`. Returns a list of LangGraph `Send` objects — each specifies a target node and a custom state for that branch:

```python
from vs_graph.edge.vs_dynamic_fan_out_edge import VsDynamicFanOutEdge
from vs_graph.decorator.vs_edge_decorator import edge
from langgraph.types import Send

@edge(name="document_fan_out_edge")
class DocumentFanOutEdge(VsDynamicFanOutEdge[MyState]):

    def get_sends(self, state: MyState) -> list:
        return [
            Send("process_document", {**state, "document": doc})
            for doc in state["documents"]
        ]
```

JSON:

```json
{
  "type": "dynamic_fan_out",
  "source": "splitter",
  "edge_class": "document_fan_out_edge"
}
```

### `@edge` decorator

```python
@edge(name="classifier_routing_edge")   # registers under key "classifier_routing_edge"
@edge                                   # registers under the class name
```

The `name` value must match the `"edge_class"` field in the JSON edge definition.

---

## @graph Decorator — Auto-Import Packages

Instead of manually importing every node and edge module, use `@graph` on your graph class to declare which packages contain your implementations. The library scans and imports them automatically at `build()` time, triggering `@node` and `@edge` registration.

```python
from vs_graph.decorator.vs_graph_decorator import graph
from vs_graph.vs_base_graph import VsBaseGraph

@graph(
    nodes=["myapp.graph.nodes"],
    edges=["myapp.graph.edges"],
)
class MyGraph(VsBaseGraph[MyState]):

    def __init__(self):
        with open("my_graph.json") as f:
            graph_json = json.load(f)
        super().__init__(graph_json=graph_json, state_class=MyState)
        self.build()
```

Both `nodes` and `edges` accept a list of package paths. Each package is walked recursively — all modules within it are imported. You can specify multiple packages:

```python
@graph(
    nodes=["myapp.graph.nodes", "shared.common_nodes"],
    edges=["myapp.graph.edges"],
)
class MyGraph(VsBaseGraph[MyState]):
    ...
```

Without `@graph`, node and edge modules must be imported manually before `build()` is called:

```python
import myapp.graph.nodes.classifier_node  # noqa
import myapp.graph.nodes.executor_node    # noqa
```

`@graph` with no packages, or subclasses without the decorator, are both valid — auto-import is skipped.

---

## Registries

### VsNodeRegistry

`VsNodeRegistry` is a static registry. `@node` populates it at import time.

| Method | Description |
|---|---|
| `register(name, node_class)` | Called by `@node` — raises `ValueError` if name already registered |
| `get(name)` | Returns the class — raises `ValueError` if not found |
| `create(name, node_id, config, **kwargs)` | Instantiates the node class |
| `is_registered(name)` | Returns `True` if name is registered |
| `list_nodes()` | Returns sorted list of registered names |
| `clear()` | Removes all registered nodes — for testing only |

### VsEdgeRegistry

Same pattern as `VsNodeRegistry` for edge classes.

| Method | Description |
|---|---|
| `register(name, edge_class)` | Called by `@edge` — raises `ValueError` if name already registered |
| `get(name)` | Returns the class — raises `ValueError` if not found |
| `create(name, source, **kwargs)` | Instantiates the edge class |
| `is_registered(name)` | Returns `True` if name is registered |
| `list_edges()` | Returns sorted list of registered names |
| `clear()` | Removes all registered edges — for testing only |

---

## Checkpointer

Configured via `config.ini`. Provides LangGraph thread-level state persistence across `invoke()` calls. The thread key defaults to `state["trace_id"]`; override it with `config={"configurable": {"thread_id": ...}}` on `invoke()`.

```ini
[graph]
checkpointer = memory
```

```ini
[graph]
checkpointer             = redis
redis_url                = redis://localhost:6379
checkpoint_key_prefix    = vs:checkpoint:
checkpoint_ttl_seconds   = 3600
```

| Key | Default | Description |
|---|---|---|
| `graph.checkpointer` | `memory` | Checkpointer type: `memory` or `redis` |
| `graph.redis_url` | `redis://localhost:6379` | Redis connection URL (redis only) |
| `graph.checkpoint_key_prefix` | `vs:checkpoint:` | Key prefix for stored checkpoints (redis only) |
| `graph.checkpoint_ttl_seconds` | None | TTL for checkpoint keys in seconds (redis only) |

Custom checkpointers can be registered via `VsCheckpointerFactory`:

```python
from vs_graph.checkpointer.vs_checkpointer_factory import VsCheckpointerFactory

VsCheckpointerFactory.register(
    "postgres",
    lambda cfg: MyPostgresCheckpointer(config=cfg)
)
```

The factory lambda receives the same `cfg` dict that `_load_checkpointer` builds from `config.ini`.

---

## Trace Publisher

Pass a `VsBaseTracePublisher` to the graph constructor to stream execution events to any external sink (queue, websocket, database):

```python
from vs_common.publisher.vs_base_trace_publisher import VsBaseTracePublisher
from vs_common.schema.vs_trace_level import VsTraceLevel
from typing import Any, Dict, Optional

class MyTracePublisher(VsBaseTracePublisher):

    async def publish(
        self,
        trace_id: str,
        message: str,
        level: VsTraceLevel = VsTraceLevel.INFO,
        data: Optional[Dict[str, Any]] = None,
    ) -> None:
        await my_queue.push({
            "trace_id": trace_id,
            "message": message,
            "level": level.value,
            "data": data or {},
        })
```

```python
graph = MyGraph(graph_json, state_class=MyState, trace_publisher=MyTracePublisher())
```

The publisher is automatically propagated to every node and edge instance. You do not pass it to nodes or edges directly.

### VsTraceEvent — telling framework noise from what a node meant to say

Every trace the framework raises carries a machine-readable tag under `data["event"]`. Filter and style on that rather than pattern-matching the message text, which is English and will change.

**A trace a node publishes itself has no `event` key at all.** That is how you tell deliberate analysis from framework bookkeeping:

```python
from vs_graph.schema.vs_trace_event import VsTraceEvent

class MyTracePublisher(VsBaseTracePublisher):

    async def publish(self, trace_id, message, level=VsTraceLevel.INFO, data=None):
        event = (data or {}).get("event")

        if event is None:
            return await show_as_analysis(trace_id, message)    # a node said this on purpose
        if event == VsTraceEvent.NODE_THINKING:
            return await show_as_status(trace_id, message)      # user-facing progress
        if event in VsTraceEvent.LIFECYCLE:
            return await log_only(trace_id, message)            # bookkeeping
```

| Constant | Value | Raised by |
|---|---|---|
| `NODE_THINKING` | `node_thinking` | `VsBaseNode.invoke()`, before the node runs |
| `NODE_STARTED` | `node_started` | `VsBaseNode.invoke()` |
| `NODE_COMPLETED` | `node_completed` | `VsBaseNode.invoke()`, with `duration_seconds` |
| `NODE_USER_ERROR` | `node_user_error` | on `VsUserException` — the graph continues |
| `NODE_FAILED` | `node_failed` | on `VsNodeExecutionException` — the graph stops |
| `NODE_CRASHED` | `node_crashed` | on anything else — the graph stops |
| `NODE_HYDRATED` | `node_hydrated` | `VsHydrationNode` after loading |
| `NODE_ALREADY_HYDRATED` | `node_already_hydrated` | `VsHydrationNode` on a warm checkpoint |
| `GUARD_PASSED` | `guard_passed` | the input guard nodes |
| `GUARD_BLOCKED` | `guard_blocked` | the input guard nodes |
| `VALIDATION_PASSED` | `validation_passed` | `VsInputValidationNode`, when input is valid |
| `VALIDATION_FAILED` | `validation_failed` | `VsInputValidationNode`, when input is invalid |
| `EDGE_ROUTED` | `edge_routed` | `VsBaseConditionalEdge.route()`, with `route_key`, `next_node` |
| `EDGE_FANNED_OUT` | `edge_fanned_out` | `VsDynamicFanOutEdge.route()`, with `branch_count`, `targets` |

`VsTraceEvent.LIFECYCLE` is the set of five that `trace_lifecycle = False` silences — the ones `VsBaseNode` raises around every node.

**Events published automatically by the framework:**

| Event | Source |
|---|---|
| `"node '{id}' started"` | `VsBaseNode.invoke()` |
| `"node '{id}' completed"` with `duration_seconds` | `VsBaseNode.invoke()` |
| `"node '{id}' user error"` | `VsBaseNode.invoke()` on `VsUserException` |
| `"node '{id}' failed"` | `VsBaseNode.invoke()` on exception |
| `"edge '{source}' routing to '{next_node}'"` with `route_key`, `next_node`, `duration_seconds` | `VsBaseConditionalEdge.route()` |
| `"edge '{source}' fanning out to {n} branch(es)"` with `branch_count`, `targets`, `duration_seconds` | `VsDynamicFanOutEdge.route()` |

If a node or edge has a `description` in the JSON, it is merged into the `data` payload of **every** trace event that node or edge publishes — the framework's own `started`/`completed` events and anything you publish from `execute()`. Whoever is watching the stream sees what ran *and* why, without opening the code:

```json
{
  "trace_id": "…",
  "message": "node 'guard' started",
  "data": { "description": "Blocks junk input before we pay for the LLM call." }
}
```

An explicit `"description"` key in your own `data` dict wins over the JSON one.

Direct and static `fan_out` edges are pure topology — they compile to plain LangGraph edges and emit no trace events. The routing wrappers are `async` and `await` the trace publish before returning the next node, so the routing event is always ordered ahead of the next node's `"started"` event.

---

## Exceptions

| Exception | When to raise | Effect |
|---|---|---|
| `VsUserException` | Error is safe to surface to the user | Stored in `state["error"]` — graph continues to next node |
| `VsNodeExecutionException` | Internal node failure | Logged and re-raised — graph stops |
| `VsGraphBuildException` | Invalid build state | Raised during `build()` |
| `VsEdgeEvaluationException` | Edge routing failure | Raised from edge `evaluate()` |

```python
from vs_graph.exception.vs_graph_exceptions import VsUserException, VsNodeExecutionException

async def execute(self, state: MyState) -> dict:
    if not state.get("user_input"):
        raise VsUserException("Please provide an input.")

    try:
        result = await call_external_service()
    except Exception as e:
        raise VsNodeExecutionException(f"External service failed: {e}") from e

    state["result"] = result
    return state
```

`state["error"]` shape when `VsUserException` is raised:

```json
{
  "message": "Please provide an input.",
  "cause": null,
  "stack_trace": null
}
```

---

## Full Example

```python
import json
from typing import Optional

from vs_graph.vs_base_graph import VsBaseGraph
from vs_graph.schema.vs_base_graph_state import VsBaseGraphState
from vs_graph.node.vs_base_node import VsBaseNode
from vs_graph.edge.vs_base_conditional_edge import VsBaseConditionalEdge
from vs_graph.decorator.vs_node_decorator import node
from vs_graph.decorator.vs_edge_decorator import edge
from vs_graph.decorator.vs_graph_decorator import graph
from vs_graph.exception.vs_graph_exceptions import VsUserException


# --- State ---

class MyState(VsBaseGraphState):
    user_input: str
    intent: Optional[str]
    response: Optional[str]


# --- Nodes ---

@node(name="classifier_node")
class ClassifierNode(VsBaseNode[MyState]):

    async def execute(self, state: MyState) -> dict:
        if not state.get("user_input"):
            raise VsUserException("Input is required.")
        state["intent"] = "search" if "find" in state["user_input"] else "chat"
        await self.trace(state["trace_id"], "classified", data={"intent": state["intent"]})
        return state


@node(name="responder_node")
class ResponderNode(VsBaseNode[MyState]):

    async def execute(self, state: MyState) -> dict:
        state["response"] = f"Handling intent: {state['intent']}"
        return state


# --- Edges ---

@edge(name="classifier_routing_edge")
class ClassifierRoutingEdge(VsBaseConditionalEdge[MyState]):

    def _evaluate(self, state: MyState) -> str:
        return state.get("intent", "default")


# --- Graph ---

@graph(nodes=["myapp.graph.nodes"], edges=["myapp.graph.edges"])
class MyGraph(VsBaseGraph[MyState]):

    def __init__(self):
        graph_json = {
            "version": "1.0",
            "name": "my_graph",
            "entry_node": "classifier",
            "exit_nodes": ["responder"],
            "nodes": [
                {"id": "classifier", "name": "classifier_node", "config": {}},
                {"id": "responder",  "name": "responder_node",  "config": {}},
            ],
            "edges": [
                {
                    "type": "conditional",
                    "source": "classifier",
                    "edge_class": "classifier_routing_edge",
                    "route": {"search": "responder", "chat": "responder", "default": "responder"}
                }
            ]
        }
        super().__init__(graph_json=graph_json, state_class=MyState)
        self.build()


# --- Run ---

import asyncio

async def main():
    g = MyGraph()
    result = await g.invoke({
        "trace_id": "",
        "error": None,
        "current_message": None,
        "user_input": "find me a product",
        "intent": None,
        "response": None,
    })
    print(result["response"])  # Handling intent: search

asyncio.run(main())
```

---

## Class Reference

---

### VsBaseGraph

Abstract base class for all graphs. Extend it and call `build()` in `__init__`.

**Constructor:**

| Parameter | Type | Description |
|---|---|---|
| `graph_json` | `Dict[str, Any]` | Parsed graph JSON — validated on construction. Its optional `description` is exposed as `self.description`. |
| `state_class` | `Type[S]` | TypedDict subclass used as LangGraph state type |
| `trace_publisher` | `Optional[VsBaseTracePublisher]` | Publisher injected into all nodes and edges |

**Methods:**

| Method | Description |
|---|---|
| `build()` | Auto-imports packages, instantiates nodes/edges, validates, loads checkpointer, compiles LangGraph. Call once at startup. |
| `async invoke(state, config=None)` | Runs the compiled graph. Auto-generates `trace_id` if not set. Sets the checkpointer `thread_id` to `state["trace_id"]` unless you pass `config={"configurable": {"thread_id": ...}}` — an explicit `thread_id` wins, but a `configurable` dict without one still gets `trace_id` merged in. |

---

### VsHydrationNode

Prebuilt first node. Rebuilds `state` from a durable store when the checkpoint is cold (new thread or expired TTL). See [Prebuilt Nodes](#prebuilt-nodes).

| Member | Kind | Description |
|---|---|---|
| `load(state)` | Abstract | Fetch prior context from your store, return a state delta. |
| `hydration_keys` | Class attr (`List[str]`) | Keys that mean "already hydrated" when all non-`None`. |
| `is_hydrated(state)` | Optional override | Default checks `hydration_keys`. |
| `execute(state)` | Provided | Skip-or-load template — do not override. |

---

### VsInputValidationNode

Concrete node registered as `vs_input_validation_node` when `vs_graph` is imported. See [Input Validation and Preprocessing](#input-validation-and-preprocessing) for JSON rules, output examples, and routing.

| Member | Description |
|---|---|
| `config.state_validation` | Non-empty list of `{key, rules}` entries for direct state validation; no subclass required. |
| Rule `error_message` | Optional custom failure message; defaults are generated when omitted. |
| `input_schema` / `config.input_key` | Alternative Pydantic object mode for registered application subclasses. Cannot be combined with `state_validation`. |
| `execute(state)` | Returns `input_valid` and `validation_errors`; schema mode also returns `normalized_input`. |

---

### VsInputGuardNode / VsHeuristicInputGuardNode / VsModerationInputGuardNode

Prebuilt guard nodes. Block bad input before the graph spends anything. See [Input Guards](#input-guards).

| Member | Where | Description |
|---|---|---|
| `check(state, text)` | Abstract on base; implemented by each flavour | Returns `VsGuardDecision`. |
| `guard_text(state)` | Base, overridable | Text to inspect. Default `state["current_message"]`. |
| `execute(state)` | Base, provided | Runs `check`, traces, raises `VsUserException` on block. |
| `patterns` / `rules(state, text)` | `VsHeuristicInputGuardNode` | Regex list (from `config.patterns` or a subclass attr) / generator of block reasons. No I/O. Self-registers as `vs_guard_node`. |
| `moderate(text)` | `VsModerationInputGuardNode`, abstract | Call a moderation model, return `VsModerationResult`. |
| `threshold` / `blocked_categories` | `VsModerationInputGuardNode` | Score cutoff / category allowlist for blocking. |

`VsGuardDecision(allowed, reason, category, scores)` and `VsModerationResult(scores, flagged, raw)` live in `vs_graph.schema`.

---

### VsBaseNode

Abstract base class for all nodes.

**Constructor parameters** (injected by `VsNodeRegistry.create()`):

| Parameter | Type | Description |
|---|---|---|
| `node_id` | `str` | Node id from JSON |
| `config` | `Optional[Dict[str, Any]]` | Node config dict from JSON |
| `description` | `Optional[str]` | Node description from JSON |
| `trace_publisher` | `Optional[VsBaseTracePublisher]` | Propagated from the graph |

**Instance attributes:**

| Attribute | Description |
|---|---|
| `self.node_id` | The node id from JSON |
| `self.config` | The config dict from JSON |
| `self.description` | The node description from JSON — auto-attached to every trace event |
| `self.trace_publisher` | The graph-level trace publisher |
| `self.logger` | Logger instance keyed to the class name |

**Abstract method:**

| Method | Signature | Description |
|---|---|---|
| `execute` | `async execute(state: S) -> dict` | Implement your node logic here. Return the updated state dict. |

**Helper method:**

| Method | Signature | Description |
|---|---|---|
| `trace` | `async trace(trace_id, message, data=None, level=INFO)` | Publishes a trace event, merging `self.description` into `data`. No-op if no publisher. |

---

### VsBaseConditionalEdge

Abstract base class for conditional routing edges.

**Constructor parameters:**

| Parameter | Type | Description |
|---|---|---|
| `source` | `str` | Source node id |
| `route` | `Dict[str, str]` | Map of route keys to target node ids — must include `"default"`. Stored as `self.route_map`. |
| `config` | `Optional[Dict[str, Any]]` | Edge config dict from JSON |
| `description` | `Optional[str]` | Edge description from JSON — auto-attached to every trace event |
| `trace_publisher` | `Optional[VsBaseTracePublisher]` | Propagated from the graph |

**Abstract method:**

| Method | Signature | Description |
|---|---|---|
| `_evaluate` | `_evaluate(state: S) -> str` | Return a route key. `route()` looks it up in `route_map`; falls back to `"default"`. |

**Routing function** (registered with LangGraph — you do not call it):

| Method | Signature | Description |
|---|---|---|
| `route` | `async route(state: S) -> str` | Calls `_evaluate`, resolves the key against `route_map` (falling back to `"default"`), publishes the routing trace, returns the target node id. Raises if there is no default. |

---

### VsDynamicFanOutEdge

Abstract base class for runtime fan-out edges.

**Abstract method:**

| Method | Signature | Description |
|---|---|---|
| `get_sends` | `get_sends(state: S) -> List` | Return a list of `langgraph.types.Send` objects. Each `Send` specifies a target node and a custom state dict for that branch. |

**Routing function** (registered with LangGraph — you do not call it):

| Method | Signature | Description |
|---|---|---|
| `route` | `async route(state: S) -> List` | Calls `get_sends`, publishes a fan-out trace with `branch_count` and `targets`, returns the `Send` list. |

---

### VsCheckpointerFactory

Static factory for checkpointer registration and creation.

| Method | Description |
|---|---|
| `register(name, factory_fn)` | Register a custom checkpointer. `factory_fn` receives a config dict. |
| `create(checkpointer_type, config)` | Instantiate and return the checkpointer. |

Built-in types: `"memory"`, `"redis"`.

---

## Running Tests

Run both JSON state-validation and Pydantic validation tests, including graph routing and automatic registration, from the `vs-graph` directory after installing the package and its dependencies:

```bash
python -m unittest discover -s tests -p 'test_*validation*.py' -v
```
