@lzn1998/dsh-langgraph 1.0.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,376 @@
1
+ # Composing graphs at runtime
2
+
3
+ `langgraph_run` runs graphs that were registered with the profile. `langgraph_compose`
4
+ adds a second source: a model can describe a graph as strict JSON in the middle of a
5
+ task, store it as an immutable **session-owned spec**, and run it with the same runtime,
6
+ checkpointer, thread, trace, and background-job path.
7
+
8
+ The division of labour is deliberate:
9
+
10
+ - **The graph owns the seams** — phases, dependencies, branches, parallel fan-out, the
11
+ human gate, state, and durability.
12
+ - **A node owns its inside** — an `agent` node gets a prose brief and tools; a `model`
13
+ node gets one judgment; a `tool` node gets one known atomic action.
14
+ - **The compiler owns translation** — JSON to `StateGraph`, with no model, no randomness,
15
+ and no I/O. The same spec always produces the same graph.
16
+
17
+ ## How to think about a composed graph
18
+
19
+ The model-facing `describe` reply separates a prose **guide** (why and how to think) from
20
+ a normative **law** (numbered MUST/MUST NOT rules), then gives the vocabulary reference
21
+ and archetype examples. The guide is written to be read as a mentor; the law is written
22
+ to be obeyed as a contract. In one paragraph: a graph is a contract about seams; the state is the ledger
23
+ that survives a seam, a node is a role that files one result, an edge is a handoff, a map
24
+ is one role repeated over a list, a gate is a signature, and a transform is the form a
25
+ result takes when filed. Start from the ledger and the seams, not the boxes; keep the
26
+ graph coarse, and split only where a step itself is the contract. The ledger's types and
27
+ reducers are its rules — a json field with default `[]` and `append` collects one object
28
+ per item, while `merge` shallow-merges one object and does not concatenate arrays. Tool
29
+ args pass through unchanged, a gate resumes with the raw answer, and a compiler rejection
30
+ is a disagreement between the ledger and the contract, not a reason to read the compiler.
31
+ The reference below is the exact vocabulary; the examples are archetypes, not templates.
32
+
33
+ ## When to compose, and when not to
34
+
35
+ Compose when the task has:
36
+
37
+ - at least three dependent steps;
38
+ - a branch, retry, or repair loop;
39
+ - work that must survive across turns or a Host restart;
40
+ - a fan-out over a list plus an aggregation;
41
+ - a human gate between phases.
42
+
43
+ Do not compose for one or two linear steps, to wrap a single tool call, or when a
44
+ registered graph already matches. The ordinary agent loop remains the default; a graph
45
+ should earn its ceremony.
46
+
47
+ The system prompt only states the principle; the numbers live here and in the advisory
48
+ lint. Aim for **4–8 phase nodes**. `validate` and `compose` return advisory warnings for a
49
+ graph with more than 12 nodes, a chain longer than 8 phases, a literal-only single tool
50
+ node, a model that feeds one tool, or a one- or two-step linear graph. Warnings do not
51
+ block; use them to merge steps into an `agent` node.
52
+
53
+ ## Lifecycle
54
+
55
+ ```
56
+ langgraph_compose({ action: "describe" }) # guide + law + reference + examples
57
+ langgraph_compose({ action: "validate", spec }) # no store, no run
58
+ langgraph_compose({ action: "compose", spec }) # store, return the id + topology
59
+ langgraph_run({ graph: "lg_adhoc_..." }) # compile and execute
60
+ langgraph_threads({ action: "history" | "state" | "edit" | "topology" | "delete" })
61
+ langgraph_run({ graph, thread, resume }) # answer an interrupt
62
+ langgraph_compose({ action: "fork", graph, from }) # rewrite the downstream
63
+ ```
64
+
65
+ A spec's id is `lg_adhoc_` plus 24 hex characters of the sha256 of its normalized JSON.
66
+ `name` and `description` are part of the content: changing either produces a new id.
67
+ Specs are immutable; a changed graph is a new spec and a new thread.
68
+
69
+ Composed graphs do not appear in the registered-graph list in the system prompt. They are
70
+ listed by `langgraph_compose({ action: "list" })` and by `langgraph_run` with no `graph`.
71
+
72
+ ## The IR
73
+
74
+ ```json
75
+ {
76
+ "ir": 1,
77
+ "name": "scan-and-decide",
78
+ "description": "Scan once, make one judgment, ask before continuing.",
79
+ "state": {
80
+ "pattern": { "type": "string", "default": "**/*.js" },
81
+ "files": { "type": "string[]", "default": [] },
82
+ "large": { "type": "boolean", "default": false }
83
+ },
84
+ "nodes": [
85
+ { "id": "scan", "do": "tool", "tool": "glob",
86
+ "args": { "pattern": { "$state": "pattern" } },
87
+ "out": { "files": "lines" } },
88
+ { "id": "judge", "do": "model",
89
+ "prompt": ["There are ", { "$state": "files" }, ". Is this large? Reply true or false."],
90
+ "out": { "large": "bool" } }
91
+ ],
92
+ "edges": [
93
+ { "from": "START", "to": "scan" },
94
+ { "from": "scan", "to": "judge" },
95
+ { "from": "judge", "to": "END", "when": true }
96
+ ],
97
+ "output": ["files", "large"],
98
+ "maxSteps": 25
99
+ }
100
+ ```
101
+
102
+ `START` and `END` are the IR's sentinels (LangGraph's own sentinels are internal). `ir`
103
+ is required and must be `1`. No node id may equal a state field name; `__start__`,
104
+ `__end__`, and `__interrupt__` are reserved.
105
+
106
+ ### State
107
+
108
+ | Type | Default must be |
109
+ |---|---|
110
+ | `string` | a string |
111
+ | `number` | a finite number |
112
+ | `boolean` | a boolean |
113
+ | `json` | any JSON value, including null, arrays, and objects |
114
+ | `string[]` | an array of strings |
115
+ | `number[]` | an array of finite numbers |
116
+
117
+ The reducer is one of `replace` (default), `append`, `add`, `max`, `min`, `merge`.
118
+ `append` is for arrays; a json field with default `[]` and `append` collects one value per
119
+ item (objects included). `add`/`max`/`min` are for numbers. `merge` shallow-merges json
120
+ objects with default `{}` (`{...left, ...right}`) and does **not** concatenate arrays; use
121
+ `append` with default `[]` to collect a list. A field written by parallel branches or a
122
+ `map` body must be mergeable.
123
+
124
+ A `$state` reference names a top-level field. A dotted path (`data.answer`) reads into a
125
+ `json` field only. A literal object may not use the `$state` key.
126
+
127
+ ### Nodes
128
+
129
+ | `do` | Fields | What it does |
130
+ |---|---|---|
131
+ | `tool` | `tool`, `args`, `out` | One DSH tool in the calling session's scope. |
132
+ | `model` | `prompt`, `system?`, `schema?`, `out` | One model judgment; `schema` asks for JSON and validates it. |
133
+ | `agent` | `prompt`, `tools`, `out` | LangGraph's prebuilt ReAct agent over selected DSH tools; the brief is prose and the compiler never inspects it. |
134
+ | `subagent` | `prompt`, `schema?`, `out` | A child DSH session with its own tool scope; optional structured output. |
135
+ | `gate` | `question`, `options?`, `out` | LangGraph `interrupt()`; the resume value is written through `out`. |
136
+ | `set` | `values` | Literal or `$state` assignments, no arithmetic. |
137
+ | `map` | `over`, `body`, `maxItems?`, `maxConcurrency?` | Dynamic fan-out over a `string[]` or `number[]` field. |
138
+
139
+ `prompt` is an array of strings and `$state` references, concatenated exactly as written.
140
+ `args` and `set.values` may contain nested literals and references. A tool node's `args`
141
+ are passed unchanged to the DSH tool; use the tool's own argument names (`glob {pattern}`,
142
+ `read {file_path}`, `write {file_path, content}`). A map body can put `{ $state: "item" }` anywhere
143
+ an arg expects the item.
144
+
145
+ A `gate` pauses the run with `{ question, options, node }`; `langgraph_run` returns
146
+ `status: "interrupted"` with the thread and interrupts. Ask the user, then resume the
147
+ same thread with `resume: <raw answer>`. `options` are labels only; the resume value
148
+ goes through `out`. For label answers use `out: { decision: "text" }` and an `eq` guard;
149
+ `bool` accepts only `true`/`false`.
150
+
151
+ ### Transforms
152
+
153
+ The `out` map names state fields and how a node result becomes the value:
154
+
155
+ | Transform | Produces | Typical field |
156
+ |---|---|---|
157
+ | `text` | string | `string` |
158
+ | `lines` | string[] | `string[]` |
159
+ | `json` | parsed JSON | `json` |
160
+ | `bool` | boolean (accepts `"true"`/`"false"`) | `boolean` |
161
+ | `number` | finite number | `number` |
162
+ | `first` | the first line or item | `string` |
163
+ | `count` | lines or items | `number` |
164
+
165
+ A transform must fit the field type. A `model` with a string `schema` may write `json`
166
+ into a string field. A map body may additionally write a scalar into an array field with
167
+ `append` (one element per item).
168
+
169
+ `bool` is strict: it accepts a JSON boolean or the text `true`/`false` only. A verify node
170
+ that returns a sentence should use `text` plus a guard, or a `model` with a boolean
171
+ schema.
172
+
173
+ A `model` or `subagent` `schema` is checked with a JSON Schema subset: `type`, `enum`,
174
+ `const`, `required`, `properties`, `additionalProperties`, `items`, and min/max length,
175
+ items, and numeric bounds. Other keywords (such as `pattern` or `$ref`) are ignored.
176
+
177
+ ### Guards
178
+
179
+ `when` is `true`, `false`, or `{ "op": "...", "args": [...] }` with one of `eq`, `ne`,
180
+ `in`, `gt`, `gte`, `lt`, `lte`, `exists`, `and`, `or`, `not`. There is no expression
181
+ string and no `eval`. A missing value or a type mismatch makes a comparison false rather
182
+ than throwing. `gt`/`gte`/`lt`/`lte` need numbers; `in` needs an array on the right;
183
+ `and`/`or`/`not` nest guards.
184
+
185
+ ### Edges
186
+
187
+ Each node's outgoing edges are exactly one of:
188
+
189
+ 1. **sequence** — one unconditional edge;
190
+ 2. **choice** — one or more conditional edges, evaluated in array order; add a
191
+ `when: true` fallback, or a run with no match fails;
192
+ 3. **parallel** — two or more unconditional edges = static fan-out.
193
+
194
+ Do not mix conditional and unconditional edges from one node. `START` has no incoming
195
+ edges; `END` has no outgoing edges; `START` edges are unconditional. A node with multiple
196
+ incoming edges waits for all of them (LangGraph's implicit join). Cycles are allowed and
197
+ analyzed as strongly connected components; `maxSteps` bounds them.
198
+
199
+ ## Map
200
+
201
+ `map` fans out over an array. The body reads the hidden `item` and `index` references; a
202
+ parent field named `item` or `index` is shadowed inside the body.
203
+
204
+ ```json
205
+ {
206
+ "id": "read",
207
+ "do": "map",
208
+ "over": "files",
209
+ "maxItems": 50,
210
+ "maxConcurrency": 8,
211
+ "body": {
212
+ "do": "tool",
213
+ "tool": "read",
214
+ "args": { "file_path": { "$state": "item" } },
215
+ "out": { "reports": "text" }
216
+ }
217
+ }
218
+ ```
219
+
220
+ - `over` must be a list you control. A tool result such as `No files found` is one
221
+ string, not an empty list; check or guard it before mapping.
222
+ - To map over files: a `glob` tool node with `out: { files: "lines" }` produces the
223
+ `string[]`; the body's `read` args use `{ file_path: { $state: "item" } }`, and
224
+ `out: { contents: "text" }` into a `string[]` with `append` adds one string per item.
225
+ `langgraph_compose({ action: "describe" })` returns this full pattern as the
226
+ `map-gate-write` example.
227
+ - The body may be `tool`, `model`, `agent`, or `subagent`; no `gate`, no nested `map`.
228
+ - Every body `out` field must use a mergeable reducer. `text`/`first` into
229
+ `string[]` + `append` appends one string per item; `lines` appends an array; `number`
230
+ and `count` into `number[]` + `append`.
231
+ - For one structured object per item, declare the field as
232
+ `{ "type": "json", "default": [], "reducer": "append" }` and have the body write
233
+ `{ "extracts": "json" }`; each item appends one value. `json` into `json` + `merge`
234
+ (default `{}`) is for merging objects into one object, not for a list. The `describe`
235
+ reply returns this pattern as the `map-extract` example.
236
+ - `maxItems` defaults to 50 and is capped at 100. A longer array fails the map; it is
237
+ never truncated.
238
+ - `maxConcurrency` defaults to 8 and is capped at 16. In this version the strictest map
239
+ limit is applied as the whole run's LangGraph concurrency cap.
240
+ - **Order:** `append` follows LangGraph's `Send` order, which is the input order, not
241
+ completion order. This is deterministic and was verified against LangGraph 1.7.5.
242
+ - An empty array sends one sentinel item so the join still runs; the downstream graph
243
+ continues with the aggregate defaults instead of silently ending.
244
+ - The compiler builds three nodes: `<id>__fanout` (dispatch), `<id>` (one item), and
245
+ `<id>__join` (runs once after all items). The join follows the spec's out-edges, so a
246
+ guard after a map sees the aggregated state.
247
+
248
+ ## The compose tool
249
+
250
+ | Action | Behaviour |
251
+ |---|---|
252
+ | `describe` | The prose guide, the normative law, the vocabulary reference and archetype examples. On demand, so it costs no prompt tokens. |
253
+ | `validate` | Parse and check; returns `{ ok, errors, warnings, topology }`; stores nothing. |
254
+ | `compose` | Validate, build once to prove the spec compiles, store, and return `{ graph, name, input, topology, warnings, created }`. The topology is IR-level; `langgraph_threads({ action: "topology" })` returns the compiled nodes, including the hidden map fanout/join. |
255
+ | `list` | This session's specs with thread counts. |
256
+ | `get` | The stored spec and input schema. |
257
+ | `delete` | Delete the spec; refuses while threads exist unless `delete_threads: true`. |
258
+ | `fork` | Return an editable downstream spec plus the current state. |
259
+
260
+ Errors carry an exact IR path (`nodes[2].do`, `edges[3].to`), the expected shape and,
261
+ where useful, a hint, so a model can repair a spec from the reply. Tool references are
262
+ checked against the tools visible to the calling agent; when the caller passes full tool
263
+ definitions, a tool node's args are also checked against the tool's own parameters
264
+ (required keys, unknown keys when `additionalProperties` is false, literal types, and
265
+ top-level `$state` reference types) at compose time and enforced again at run time.
266
+
267
+ ### Specs from a file
268
+
269
+ `compose` and `validate` accept `path` instead of `spec`: a `.json` file inside the
270
+ session's cwd. Absolute paths, `..` escapes, and symlinks that leave the cwd are
271
+ rejected. A profile without a session cwd must pass the parsed object. The file is only
272
+ a source; resuming a thread never re-reads it. Editing the file produces a new spec.
273
+
274
+ ### Storage and ownership
275
+
276
+ Specs live in the `langgraph_specs` storage domain, one record per content id, capped at
277
+ 64 per session. A record is `{ spec, source, sessionId, createdAt, compilerVersion }`.
278
+ Without a storage domain the store is process-local, like the in-memory checkpoint
279
+ fallback. A spec is owned by the session that composed it; another session cannot run,
280
+ read, or delete it. The Web panel's owner-only topology route may inspect any spec.
281
+
282
+ ## Running, failure, and recovery
283
+
284
+ `langgraph_run` accepts a registered id or a composed id. A composed run carries the
285
+ spec's `maxSteps` (default 25) and map concurrency cap. Threads, interrupts, background
286
+ jobs, time travel, topology, and traces work exactly as for registered graphs.
287
+
288
+ ### Failure result
289
+
290
+ A failed run returns `status: "failed"` instead of throwing:
291
+
292
+ ```json
293
+ {
294
+ "status": "failed",
295
+ "graph": "lg_adhoc_7f3a...",
296
+ "thread": "lg_lg_adhoc_7f3a..._...",
297
+ "checkpoint": "1ef...",
298
+ "failedNode": "read",
299
+ "failedScc": ["read"],
300
+ "pending": ["read"],
301
+ "downstream": ["END", "judge", "read"],
302
+ "upstream": ["START", "scan"],
303
+ "lastSupersteps": [
304
+ { "step": 2, "source": "loop", "next": ["read"], "tasks": [{ "id": "judge", "error": null }],
305
+ "values": { "verdict": "large" } }
306
+ ],
307
+ "error": { "name": "ToolError", "message": "read: ENOENT", "node": "read", "itemIndex": 1 },
308
+ "state": { "reports": [] },
309
+ "hint": "transient -> resume with the same thread; state -> edit/replay; graph -> fork the downstream and compose"
310
+ }
311
+ ```
312
+
313
+ - `failedNode` comes from the node wrapper; a map item also carries `itemIndex`.
314
+ - `failedScc` is the cycle the failure belongs to (a singleton for a non-cyclic node).
315
+ - `upstream` is the completed dependency side; `downstream` includes the failed region
316
+ and everything after it.
317
+ - `pending` is the boundary checkpoint's next work, with hidden map nodes reported as
318
+ the spec's map id.
319
+ - `lastSupersteps` holds the failure boundary and at most two prior checkpoints, with
320
+ `state`/`values` bounded by `output` and a 4000-character cap.
321
+ - A registered graph gets the error and thread history, but no SCC/dependency fields
322
+ because it has no IR.
323
+
324
+ Background jobs report the same structured result in `job_output`.
325
+
326
+ ### Recovery
327
+
328
+ 1. **Transient** — `langgraph_run({ graph, thread })` resumes the pending work on the
329
+ same thread. Completed map items are checkpointed; the failed superstep is retried.
330
+ 2. **State error** — `langgraph_threads edit` at the failure `checkpoint`, then
331
+ `langgraph_run({ graph, thread, checkpoint })` replays from the edit.
332
+ 3. **Graph bug** — `langgraph_compose({ action: "fork", graph, from: failedNode, thread })`
333
+ returns the downstream nodes/edges as a new spec skeleton, with `START` pointing at
334
+ the failed region's external entries, plus the thread's current state. Edit the spec,
335
+ `compose` it, and run the new graph with that state as input. The old spec and thread
336
+ remain.
337
+ 4. **Loop bug** — fork the whole SCC; the loop is one recovery unit.
338
+ 5. The runtime never mutates a spec. Every rewrite is a new immutable spec.
339
+
340
+ At-least-once applies: a failed node may already have produced side effects. Destructive
341
+ actions should be idempotent or guarded by a `gate`.
342
+
343
+ ## Limits
344
+
345
+ | Item | Limit |
346
+ |---|---|
347
+ | nodes | 64 |
348
+ | edges | 128 |
349
+ | state fields | 64 |
350
+ | spec JSON | 256 KiB |
351
+ | `maxSteps` | 1–200 (default 25) |
352
+ | map `maxItems` | 1–100 (default 50) |
353
+ | map `maxConcurrency` | 1–16 (default 8) |
354
+ | specs per session | 64 |
355
+
356
+ ## Not supported
357
+
358
+ - No arbitrary JavaScript: only the IR's node kinds. The compiler never runs model-written
359
+ code, and a spec is never written to `graphs/*.js`.
360
+ - No subgraphs, LangGraph Platform/Studio, token streaming inside a tool result, or vector
361
+ search in the store.
362
+ - No per-map concurrency in v1; the strictest map cap is global.
363
+ - No automatic spec promotion to a profile module. Reuse across sessions means writing a
364
+ graph module and installing it, which requires the profile's normal restart.
365
+
366
+ ## Examples
367
+
368
+ `test/fixtures/specs/` holds the conformance specs:
369
+
370
+ - `scan-report` — tool, model, choice.
371
+ - `approval-gate` / `ask-user` — gate and resume.
372
+ - `ask-tools` — agent over session tools.
373
+ - `ask-workspace` — tool then model.
374
+ - `ask-subagent` — child session.
375
+ - `map-report` — map, append, join.
376
+ - `parallel` — static fan-out and a join.
package/docs/CONTEXT.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Context and prompt design
2
2
 
3
- This plugin adds one vocabulary and two tools to a DSH profile. This page records
3
+ This plugin adds one vocabulary and three tools to a DSH profile. This page records
4
4
  exactly what it injects, what it deliberately does not inject, and how that layer stays
5
5
  distinct from DSH's own prompt and tools.
6
6
 
@@ -8,7 +8,7 @@ distinct from DSH's own prompt and tools.
8
8
 
9
9
  | Layer | Contribution | Lifetime |
10
10
  |---|---|---|
11
- | Tool schemas | `langgraph_run`, `langgraph_threads` | While the plugin is loaded; `config.prompt: false` does not remove them. |
11
+ | Tool schemas | `langgraph_run`, `langgraph_threads`, `langgraph_compose` | While the plugin is loaded; `config.prompt: false` does not remove them. |
12
12
  | System-prompt section | `tool:langgraph`, order `TOOL_SUBAGENT - 10` | Effect-owned by the plugin; `config.prompt: false` disables it. |
13
13
  | Runtime context | **none** | — |
14
14
  | Session events | none from the model's point of view | Traces are log-only DSH PTC events for Trajectory. |
@@ -35,7 +35,9 @@ use it because:
35
35
 
36
36
  | Term | Meaning in this plugin | Not |
37
37
  |---|---|---|
38
- | **graph** | A module registered with the profile (`id`, `description`, `input`, `build`). | The `workflow` tool's ad-hoc JavaScript script. |
38
+ | **graph** | A module registered with the profile (`id`, `description`, `input`, `build`), or a session-owned composed spec; both run with `langgraph_run`. | The `workflow` tool's ad-hoc JavaScript script. |
39
+ | **composed graph** | An immutable `GraphSpec` stored in `langgraph_specs`, compiled by the plugin, with an id `lg_adhoc_<hash>`. | A `graphs/*.js` module, a file, or a DSH Session. |
40
+ | **spec** | One stored IR record; editing means composing a new spec. | A mutable document or a running graph. |
39
41
  | **graph run** | One execution with an input, returning a state. | A DSH turn or Session. |
40
42
  | **thread** | A durable LangGraph checkpoint chain for one graph run, owned by the session and graph that created it. | A DSH Session. |
41
43
  | **checkpoint** | One snapshot in a thread; `history`, `edit`, and replay address it by id. | A DSH session checkpoint. |
@@ -60,19 +62,44 @@ graph with `bash`, `subagent`, or ad-hoc steps. This keeps graph
60
62
  use from becoming ceremony while still letting a matching graph win over a hand-rolled
61
63
  sequence.
62
64
 
65
+ `langgraph_compose` is for work with seams that should not be re-decided every turn:
66
+ cross-turn persistence, parallel fan-out with aggregation, a human decision, or a retry
67
+ boundary. The section states that principle and the hard boundaries; the numeric
68
+ coarse-first thresholds and node-kind heuristics live in the advisory lint and the
69
+ on-demand `describe`, not in the always-on prompt.
70
+
63
71
  The tool description covers mechanics (arguments, thread/resume/checkpoint, background
64
72
  job), not selection; the section covers selection, not mechanics. This split is the main
65
73
  rule for future edits.
66
74
 
75
+ ## Leaving the shape open
76
+
77
+ The prompt does not prescribe a decision tree or concrete examples. It states the
78
+ boundaries and the available moves:
79
+
80
+ - a graph that is already registered and whose output matches → `langgraph_run`;
81
+ - a one-off task, or a task whose shape is still unclear → ordinary DSH tools;
82
+ - an ad-hoc fan-out whose shape is generated for this run → `workflow`;
83
+ - a shape worth a durable, inspectable graph → `langgraph_compose` with a JSON spec;
84
+ - a shape worth reusing across sessions → a profile graph module (authored outside this tool).
85
+
86
+ `langgraph_run` cannot define a graph; the model is told not to invent an id. A composed
87
+ spec is not a file and not a DSH Session, and it is immutable: changing it means composing
88
+ a new one. The prompt does not prescribe a node count or a node-kind checklist: it gives
89
+ the seam principle and the escape valve (`agent` for open work), and `describe` is the
90
+ manual. The only concrete list in the prompt is the registry itself — data the model must
91
+ select from, not an example to copy. This is deliberate: the model should choose or
92
+ compose the shape, not imitate a canned one.
93
+
67
94
  ## Boundaries with DSH's own context
68
95
 
69
96
  | DSH facility | Boundary |
70
97
  |---|---|
71
- | `workflow` tool | `workflow` writes an ad-hoc JavaScript fan-out script; `langgraph_run` runs a profile-registered, named graph with a durable thread. The section sits **after** the workflow tool's "only when the user asks" rule and **before** subagent guidance (`TOOL_SUBAGENT - 10`), so that rule cannot read as part of this section. |
72
- | `subagent` | One-off delegation stays `subagent`; a graph may delegate internally, and `helpers.subagent` creates a normal DSH child. |
73
- | `ask_user_question` | The native question tool is the default for one question; the `ask-user` graph only adds value when a graph or thread is wanted. |
98
+ | `workflow` tool | `workflow` writes an ad-hoc JavaScript fan-out script; `langgraph_run` runs a named graph (registered or composed) with a durable thread. The section sits **after** the workflow tool's "only when the user asks" rule and **before** subagent guidance (`TOOL_SUBAGENT - 10`), so that rule cannot read as part of this section. |
99
+ | `subagent` | One-off delegation stays `subagent`; a graph may use an `agent` node for open work in this session or a `subagent` node for a child Session. |
100
+ | `ask_user_question` | The native question tool is the default for one question; a `gate` node is for a decision inside a durable graph. |
74
101
  | `job_output` / `job_kill` | A background graph run is a DSH job; use the stock job tools. |
75
- | DSH Session | A LangGraph thread is not a Session; the prompt and tool schema say so explicitly. |
102
+ | DSH Session | A LangGraph thread is not a Session; a composed spec is not a Session either. The prompt and tool schemas say so explicitly. |
76
103
  | Trajectory | Graph activity appears as nested log-only sub-calls; it is not injected into model context. |
77
104
  | Goals, schedules | Out of scope; the plugin does not create either. |
78
105
 
@@ -83,20 +110,24 @@ rule for future edits.
83
110
  workflow tool's "ONLY when..." guidance and made the two "workflow" instructions read
84
111
  as one.
85
112
  - The section is global to the profile while the plugin is active, including agents whose
86
- tool policy hides `langgraph_run`; `config.prompt: false` is the escape hatch.
113
+ tool policy hides the graph tools; `config.prompt: false` is the escape hatch.
87
114
  - Registry entries are sorted by id; broken modules are skipped from the list.
88
115
 
89
116
  ## Maintenance checklist
90
117
 
91
118
  When changing this layer:
92
119
 
93
- 1. Keep the words **graph**, **thread**, **checkpoint**, and **DSH job** consistent in the
94
- prompt, tool descriptions, error messages, UI, and docs.
120
+ 1. Keep the words **graph**, **composed graph**, **spec**, **thread**, **checkpoint**, and
121
+ **DSH job** consistent in the prompt, tool descriptions, error messages, UI, and docs.
95
122
  2. Do not use "workflow" as a synonym for a graph; it belongs only in the explicit
96
123
  distinction from the `workflow` tool.
97
124
  3. Add a trigger only if it is a property the plugin actually provides; do not advertise
98
125
  long-term memory unless a graph uses the store.
99
- 4. Keep the section about selection and the tool descriptions about mechanics.
100
- 5. Keep graph descriptions one line, unique, and specific about the graph's value; avoid
126
+ 4. Keep the section about selection and the tool descriptions about mechanics. Compose
127
+ mechanics live in `langgraph_compose` and its on-demand `describe`, not in the prompt.
128
+ 5. Keep the prompt principle-based: seams, coarse graph, open work in `agent`. Keep
129
+ numeric thresholds and node-kind heuristics in the advisory lint and `describe`, not
130
+ in the always-on section.
131
+ 6. Keep graph descriptions one line, unique, and specific about the graph's value; avoid
101
132
  demo overlap.
102
- 6. Re-check section order when a DSH release adds or renames prompt sections.
133
+ 7. Re-check section order when a DSH release adds or renames prompt sections.
package/docs/DETAIL.md CHANGED
@@ -9,6 +9,10 @@ Run a LangGraph graph from inside a DSH agent session, and continue it later.
9
9
  - `langgraph_threads` — `list`, `state`, `history`, `edit`, `topology`, and `delete`.
10
10
  A checkpoint can be inspected, forked with new values, and replayed; a graph's nodes
11
11
  and edges are available as JSON for a client view.
12
+ - `langgraph_compose` — compose a session-owned graph from a strict JSON `GraphSpec`,
13
+ validate/list/get/delete it, and `fork` an editable downstream spec after a failure.
14
+ A composed graph uses the same compile, run, checkpoint, trace, background, and
15
+ time-travel path; see [COMPOSE.md](COMPOSE.md) for the IR reference.
12
16
  - **Durable threads.** Every superstep is checkpointed in a DSH storage domain
13
17
  (`langgraph_checkpoints`), so a thread survives the turn and the Host process. Pass
14
18
  `thread` back to continue it; a profile without `storageDomain` falls back to an
@@ -44,6 +48,46 @@ Run a LangGraph graph from inside a DSH agent session, and continue it later.
44
48
  and `helpers.createReactAgent({...})` is LangGraph's prebuilt ReAct agent wired to both.
45
49
  `helpers.messages` re-exports the LangChain message classes.
46
50
 
51
+ ## Composed graphs (GraphSpec)
52
+
53
+ The runtime has one execution path. A composed graph is another **entry**: a stored spec
54
+ resolves to `{ id, description, input, build }`, where `build(api)` calls the plugin's
55
+ deterministic JSON-to-`StateGraph` compiler. It then uses the same `compile`, `executeRun`,
56
+ checkpointer, store, helpers, trace, background job, and thread ownership as a registered
57
+ module.
58
+
59
+ - **IR.** `ir: 1`, state fields with types and reducers, and nodes `tool`, `model`,
60
+ `agent`, `gate`, `map`, `set`, `subagent`. `out` transforms convert a result into a
61
+ typed state value; guards are structured (`eq`, `in`, `gt`, …) and never `eval`.
62
+ Edges are sequence (one unconditional), choice (conditional in order), or static
63
+ fan-out (two or more unconditional). A node with multiple incoming edges joins.
64
+ - **Compiler.** `compose/schema.js` validates with exact IR paths and budgets,
65
+ `compose/analysis.js` computes Tarjan SCCs, reachability, and the writer/reducer
66
+ contract, `compose/build.js` emits the `StateGraph`, and `compose/nodes.js` executes
67
+ one node. The compiler calls no model and performs no I/O.
68
+ - **Specs.** `langgraph_specs` stores one immutable record per content id
69
+ (`lg_adhoc_<24 hex>`), capped at 64 per session and owned by the composing session.
70
+ Without a storage domain the store is process-local. `compose/resolve.js` turns a spec
71
+ id into a runtime entry and caches it per owner.
72
+ - **Map.** A map compiles to a hidden fanout dispatcher, a body node (the spec's id), and
73
+ a hidden join. `Send` runs the body once per item; the join runs once with the
74
+ aggregated state and then follows the spec's out-edges. `append` follows the Send/input
75
+ order, not completion order. An empty array uses a sentinel item so the join still
76
+ runs. The body may be `tool`, `model`, `agent`, or `subagent`; its `out` fields need
77
+ mergeable reducers.
78
+ - **Failure.** A failed run returns `status: "failed"` with `failedNode` (and
79
+ `itemIndex` for a map item), `failedScc`, `upstream`, `downstream`, `pending`, the last
80
+ three checkpoint snapshots with bounded values, the error, and a state copy bounded by
81
+ `output`. A registered graph gets the error and history without the IR dependency sets.
82
+ Background jobs carry the same structure.
83
+ - **Recovery.** Resume the same thread for a transient error; `edit` the failure
84
+ checkpoint and replay for a bad state; `fork` the downstream (or the whole SCC) into a
85
+ new editable spec for a graph bug. The runtime never mutates a spec.
86
+ - **Compose tool.** `describe` is the on-demand guide/law/reference/examples; `validate` stores nothing;
87
+ `compose` previews and stores; `list`, `get`, and `delete` are owner-scoped; `fork`
88
+ returns the downstream skeleton and the thread's current state. A workspace `.json`
89
+ path is read only inside the session cwd.
90
+
47
91
  ## Model-facing guidance
48
92
 
49
93
  While the plugin is active it registers a system-prompt section through DSH's public
@@ -53,11 +97,19 @@ a description match, or a graph-specific need such as a durable thread, backgrou
53
97
  interrupt/resume, checkpoint replay, or Trajectory sub-calls), and the registry (up to 24
54
98
  ids and descriptions; input schemas stay out of the prompt). The model therefore knows
55
99
  what exists without spending a discovery call; `langgraph_run` with no `graph` still
56
- returns the full list and input schemas.
100
+ returns the full list and input schemas. The section also states the compose principle
101
+ (seams, coarse graph, open work in `agent`), that a composed graph is immutable and
102
+ session-owned, and how to read a failed run and fork its downstream. The numeric
103
+ thresholds and node-kind heuristics live in the advisory lint and `describe`.
57
104
 
58
105
  - The section sits just before the subagent guidance, after the `workflow` tool's
59
106
  "only when the user asks" rule. An earlier placement at `TOOL_WORKFLOW` made the two
60
107
  "workflow" instructions read as one.
108
+ - The section also says that `langgraph_run` only runs registered graphs and cannot
109
+ define one: one-off or still-unclear work stays on ordinary DSH tools (or `workflow`
110
+ for an ad-hoc fan-out), and a reusable shape belongs in a profile graph module. It
111
+ gives no concrete examples for that choice, so the model composes the shape instead
112
+ of copying one.
61
113
  - Apart from the section and the two tool schemas, the plugin injects no runtime context;
62
114
  per-session thread facts are read on demand with `langgraph_threads`. See
63
115
  [CONTEXT.md](CONTEXT.md) for the mapping and the maintenance rules.
package/docs/ECOSYSTEM.md CHANGED
@@ -12,7 +12,7 @@ wired and how to add an integration that is not bundled.
12
12
  | Expose DSH tools to LangGraph | `helpers.tools([...names])` | Real LangChain `tool()` instances; visible names only. |
13
13
  | One text completion | `helpers.callModel(prompt, options)` | Deployment model route; text only. |
14
14
  | A LangChain chat model | `helpers.chatModel(options)` | Supports `bindTools`; reports usage. |
15
- | Prebuilt ReAct agent | `helpers.createReactAgent(options)` | Wraps the DSH model and tools; returns an uncompiled graph. |
15
+ | Prebuilt ReAct agent | `helpers.createReactAgent(options)` | Wraps the DSH model and tools; returns a compiled graph (LangGraph 1.7.5). |
16
16
  | Message classes | `helpers.messages` | `AIMessage`, `HumanMessage`, `SystemMessage`, `ToolMessage`. |
17
17
  | Durable checkpoints | `api.checkpointer` | The plugin compiles your graph with it by default. |
18
18
  | Long-term memory | `getStore(config)`, `api.store`, `helpers.store()` | `DshStore` over `langgraph_store`; filters/pagination, no vector search. |
@@ -107,12 +107,37 @@ const agent = await helpers.createReactAgent({
107
107
  llm: helpers.chatModel(),
108
108
  tools: helpers.tools(['read', 'glob', 'bash']),
109
109
  })
110
- return agent // a StateGraph; the plugin compiles it with its checkpointer and store
111
110
  ```
112
111
 
113
- Pass the uncompiled graph back. LangGraph only accepts LangChain Runnables as tools, so
114
- use `helpers.tools` rather than raw DSH tool names; the original DSH JSON schema is what
115
- the model sees.
112
+ In LangGraph 1.7.5 this already returns a **compiled** graph. `compile(entry, ...)`
113
+ detects that and does not inject the plugin's checkpointer or store, so returning it
114
+ directly as the whole graph loses the durable thread. Use it inside a node (as the
115
+ `ask-tools` example and the IR `agent` node do):
116
+
117
+ ```js
118
+ return new StateGraph(State)
119
+ .addNode('react', async state => {
120
+ const result = await agent.invoke({ messages: [['human', state.question]] })
121
+ const last = result.messages.at(-1)
122
+ return { answer: typeof last.content === 'string' ? last.content : '' }
123
+ })
124
+ .addEdge(START, 'react')
125
+ .addEdge('react', END)
126
+ ```
127
+
128
+ If you do use it as the graph itself, pass `checkpointer` and `store` explicitly to
129
+ `createReactAgent`. LangGraph only accepts LangChain Runnables as tools, so use
130
+ `helpers.tools` rather than raw DSH tool names; the original DSH JSON schema is what the
131
+ model sees.
132
+
133
+ ## Composed graphs
134
+
135
+ `langgraph_compose` is a declarative front end over the same runtime, not a second
136
+ ecosystem. A composed node may be `tool`, `model`, `agent` (this same prebuilt ReAct
137
+ agent), `gate`, `map`, `set`, or `subagent`; it cannot import a package or construct a
138
+ custom retriever. When a shape needs an arbitrary LangChain package, a vector store, or
139
+ custom streaming, write a graph module, or keep that work inside an `agent` node. A
140
+ composed spec is never written into `graphs/*.js` and never loads code.
116
141
 
117
142
  ## Streaming
118
143