@lzn1998/dsh-langgraph 1.0.1 → 1.6.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.
Files changed (44) hide show
  1. package/README.md +172 -51
  2. package/bench/README.md +54 -0
  3. package/bench/demo-video.mjs +208 -0
  4. package/bench/results-harness.json +125 -0
  5. package/bench/run.mjs +139 -0
  6. package/compose/analysis.js +359 -0
  7. package/compose/build.js +274 -0
  8. package/compose/constants.js +83 -0
  9. package/compose/guard.js +72 -0
  10. package/compose/nodes.js +214 -0
  11. package/compose/resolve.js +97 -0
  12. package/compose/schema.js +975 -0
  13. package/compose/specs.js +218 -0
  14. package/compose/template.js +260 -0
  15. package/compose/tool.js +713 -0
  16. package/docs/BENCHMARK.md +116 -0
  17. package/docs/COMPOSE.md +376 -0
  18. package/docs/CONTEXT.md +34 -18
  19. package/docs/DETAIL.md +48 -1
  20. package/docs/ECOSYSTEM.md +30 -5
  21. package/gallery/README.md +69 -0
  22. package/gallery/assets/gallery.png +0 -0
  23. package/gallery/assets/session.png +0 -0
  24. package/gallery/index.html +516 -0
  25. package/gallery/specs/approval-plan.lg.json +51 -0
  26. package/gallery/specs/data-extract.lg.json +75 -0
  27. package/gallery/specs/incident-triage.lg.json +64 -0
  28. package/gallery/specs/pr-review.lg.json +49 -0
  29. package/gallery/specs/repo-scan.lg.json +54 -0
  30. package/gallery/specs/research-brief.lg.json +94 -0
  31. package/index.d.ts +136 -0
  32. package/index.js +423 -46
  33. package/media/dsh-langgraph-demo.webm +0 -0
  34. package/media/raw/page@0d0adc4d6eb7b946d722093988db7e67.webm +0 -0
  35. package/media/raw/page@0fceaacbda6d8f2da8485736c565ed87.webm +0 -0
  36. package/media/raw/page@49c6bb9135c0c35ed8cf9054a8e05711.webm +0 -0
  37. package/media/raw/page@86f5e37e1c1218697f8724a6bafda8d2.webm +0 -0
  38. package/media/raw/page@9b5b70b442c0ace7d4b135fc80edba73.webm +0 -0
  39. package/media/raw/page@beb9164240f13ad017c3fa7e8f20a772.webm +0 -0
  40. package/media/raw/page@db4ee1834adcc9e8d5b4708eabe4eb5c.webm +0 -0
  41. package/media/raw/page@e9c63a0029d3181e41506fc4bf8da05a.webm +0 -0
  42. package/media/raw/page@eaf729b06925fe86e9e9e4bf48e2cdcc.webm +0 -0
  43. package/media/raw/page@f0d6fd1a2534e69bc2f228b30ae19a9c.webm +0 -0
  44. package/package.json +7 -3
@@ -0,0 +1,116 @@
1
+ # A small DSH benchmark: ordinary loop vs dsh-langgraph graphs
2
+
3
+ **Date:** 2026-11-27 · **Plugin:** dsh-langgraph 1.5.0 (runtime unchanged in 1.6.0) ·
4
+ **DSH:** local `deepseek-harness` checkout · **Model:** DeepSeek-V4.1-Flash · **Host:** one
5
+ macOS machine.
6
+
7
+ This is a directional comparison, not a leaderboard. The question: when does an explicit
8
+ graph buy enough at a seam to justify its cost over the stock DSH ordinary loop?
9
+
10
+ ## Setup
11
+
12
+ The stock **official** arm uses the `headless` profile with no plugin. The **plugin**
13
+ arms use the `lgh` profile with this package linked. Both use the same model, workspace
14
+ policy, and task text. The headless tasks have no human gate, so they can run unattended.
15
+
16
+ Two deterministic tasks:
17
+
18
+ | Task | Input | Output check |
19
+ |---|---|---|
20
+ | `fanout` | 8 files, each `Score: N` | exactly `36` |
21
+ | `report` | 3 project files with a service count | exactly `Beta: Chen` |
22
+
23
+ The task text for `plain` explicitly asks for ordinary DSH tools and forbids the graph
24
+ tools. `default` leaves the choice to the plugin's prompt. `coarse` and `fine` force a
25
+ graph in the task text. One run per cell. The harness is in
26
+ [`bench/run.mjs`](../bench/run.mjs); the commands are in [`bench/README.md`](../bench/README.md).
27
+
28
+ `tokens` is the sum of DSH `step_end` usage (input + output + cache reads). It is
29
+ comparable between cells but is not a bill. Graph-internal model calls may not all appear
30
+ as `step_end`; treat the graph arms as a lower bound.
31
+
32
+ ## Headless results
33
+
34
+ `time / reported tokens / steps`; every cell produced the expected file.
35
+
36
+ | Task | Official DSH (headless) | Plugin `plain` | Plugin `default` | Forced coarse | Forced fine |
37
+ |---|---:|---:|---:|---:|---:|
38
+ | `fanout` (8 files, sum) | 16s / 72.5K / 5 | 9s / 65.2K / 4 | 9s / 64.0K / 4 | 45s / 264.9K / 12 | 60s / 393.4K / 15 |
39
+ | `report` (3 files, pick) | 7s / 41.1K / 3 | 9s / 63.3K / 4 | 10s / 79.7K / 5 | 30s / 124.2K / 6 | 39s / 229.0K / 10 |
40
+
41
+ The six ordinary-loop cells come from one `bench/run.mjs` run
42
+ ([results](../bench/results-harness.json)); the forced-graph columns are the earlier
43
+ 1.5.0 matrix, because that run deliberately forced coarse/fine graphs. A second official
44
+ run measured 12s / 73.9K / 5 and 7s / 41.2K / 3; a second plain run measured 7s / 81.1K
45
+ and 9s / 46.9K. The variance at this size is large.
46
+
47
+ At n=1 there is **no consistent winner** between the official loop and the plugin's
48
+ ordinary loop: they sit in the same roughly 40–80K reported-token band, and the faster
49
+ arm changes between tasks. The plugin's system prompt and three tools do not impose a
50
+ reliable tax; the extra tokens are within run-to-run noise. The default plugin prompt did
51
+ **not** compose on either small task — it stayed with the ordinary loop. That is the
52
+ intended conservative behavior.
53
+
54
+ The forced graphs cost roughly **3–5×** the ordinary loop in tokens. The coarse graph is
55
+ agent-heavy; the fine graph has more tool/model rows. Both forced arms are the earlier
56
+ 1.5.0 runs; they first hit a strict `bool` / `No files found` failure and recovered
57
+ through fork or re-compose, so their time/token totals include that recovery. The current
58
+ guide/law, `file_path` correction and compose-time tool-argument validation remove two of
59
+ those first-failure classes; the numbers are still a useful upper bound on the cost of
60
+ forcing a graph at a small seam.
61
+
62
+ ## The 12-topic Web case
63
+
64
+ The larger case is Web-only because it has a human gate; a headless profile has no
65
+ answerer. It is the same 12-topic brief used by the gallery and the demo video:
66
+
67
+ | Approach | Wall | Steps | Tokens | Result |
68
+ |---|---:|---:|---:|---|
69
+ | Ordinary loop + native question | 53s | 7 | 124K | correct 12-row brief |
70
+ | Coarse agent graph + gate | 1m38s | 17 | 462K | correct after a manual heading fix |
71
+ | Fine map graph + gate | 55s | 9 | 226K | correct 12 rows; gate/resume |
72
+
73
+ The fine graph is two 12-item maps (read + extract), an outline model, a human gate, a
74
+ compose model and a write. It is slower than the ordinary loop by ~2s, uses ~1.8× the
75
+ reported tokens, and is about **half** the coarse agent graph. The coarse graph's write
76
+ node dropped headings and needed a manual fix; the fine graph wrote the approved outline
77
+ faithfully.
78
+
79
+ ## What this says
80
+
81
+ - **Do not reach for a graph on a one- or two-step task.** The ordinary loop — official
82
+ or plugin — is the baseline; at these sizes the two are within noise.
83
+ - **A graph is a seam tax.** At 8 files and 3 files the tax does not pay. The 12-topic
84
+ map/extract case is the first shape where the explicit fan-out, the human signature and
85
+ the durable thread start to earn their overhead; even there, the loop is cheaper in
86
+ tokens.
87
+ - **Fine is not automatically worse than coarse.** For a genuine per-item fan-out, a
88
+ map of the same role (fine) was about half the cost of four open-ended agent phases
89
+ (coarse), and produced a more faithful file. The earlier "fine is harmful" result was
90
+ the manual and validation, not the shape.
91
+ - **The only robust signal is the graph tax.** Small ordinary-loop differences move with
92
+ the run; the 3–5× graph cost and the 12-topic fine/coarse gap do not.
93
+ - **The honest default is the product.** The plugin's system prompt says "compose only
94
+ at seams"; the benchmark shows why.
95
+
96
+ ## Threats to validity
97
+
98
+ One run per cell, one model, one host, two small headless tasks plus one Web case. The
99
+ official and plugin profiles differ in system prompt/tool surface by construction; that is
100
+ the intervention. Small-task variance is large: a repeated ordinary-loop cell moved by
101
+ 15–50K tokens and several seconds. The forced graph arms include recovery from the earlier
102
+ 1.5.0 manual. Token accounting includes cache reads and may undercount graph-internal
103
+ model calls. The 12-topic case is a single Web session. Treat the table as a decision aid,
104
+ not a statistical claim.
105
+
106
+ ## Reproduce
107
+
108
+ ```sh
109
+ DSH_ROOT=/Users/zhinan/deepseek-harness node bench/run.mjs
110
+ DSH_ROOT=/Users/zhinan/deepseek-harness node bench/run.mjs fanout official
111
+ DSH_ROOT=/Users/zhinan/deepseek-harness node bench/run.mjs fanout coarse
112
+ ```
113
+
114
+ The 12-topic case is the `research-brief` gallery graph, run in the `lgtest` Web profile;
115
+ [the demo video](../media/dsh-langgraph-demo.webm) is a recording of that completed
116
+ session. The gallery page is [`gallery/index.html`](../gallery/index.html).
@@ -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,6 +62,12 @@ 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.
@@ -72,22 +80,26 @@ boundaries and the available moves:
72
80
  - a graph that is already registered and whose output matches → `langgraph_run`;
73
81
  - a one-off task, or a task whose shape is still unclear → ordinary DSH tools;
74
82
  - an ad-hoc fan-out whose shape is generated for this run → `workflow`;
75
- - a shape worth reusing → a profile graph module (authored outside this tool).
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).
76
85
 
77
- `langgraph_run` cannot define a graph; the model is told not to invent an id. The only
78
- concrete list in the prompt is the registry itself — data the model must select from, not
79
- an example to copy. This is deliberate: the model should choose or compose the shape,
80
- not imitate a canned one.
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.
81
93
 
82
94
  ## Boundaries with DSH's own context
83
95
 
84
96
  | DSH facility | Boundary |
85
97
  |---|---|
86
- | `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. |
87
- | `subagent` | One-off delegation stays `subagent`; a graph may delegate internally, and `helpers.subagent` creates a normal DSH child. |
88
- | `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. |
89
101
  | `job_output` / `job_kill` | A background graph run is a DSH job; use the stock job tools. |
90
- | 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. |
91
103
  | Trajectory | Graph activity appears as nested log-only sub-calls; it is not injected into model context. |
92
104
  | Goals, schedules | Out of scope; the plugin does not create either. |
93
105
 
@@ -98,20 +110,24 @@ not imitate a canned one.
98
110
  workflow tool's "ONLY when..." guidance and made the two "workflow" instructions read
99
111
  as one.
100
112
  - The section is global to the profile while the plugin is active, including agents whose
101
- 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.
102
114
  - Registry entries are sorted by id; broken modules are skipped from the list.
103
115
 
104
116
  ## Maintenance checklist
105
117
 
106
118
  When changing this layer:
107
119
 
108
- 1. Keep the words **graph**, **thread**, **checkpoint**, and **DSH job** consistent in the
109
- 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.
110
122
  2. Do not use "workflow" as a synonym for a graph; it belongs only in the explicit
111
123
  distinction from the `workflow` tool.
112
124
  3. Add a trigger only if it is a property the plugin actually provides; do not advertise
113
125
  long-term memory unless a graph uses the store.
114
- 4. Keep the section about selection and the tool descriptions about mechanics.
115
- 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
116
132
  demo overlap.
117
- 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.