@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
package/bench/run.mjs ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * A small, reproducible DSH benchmark.
3
+ *
4
+ * DSH_ROOT=/path/to/deepseek-harness node bench/run.mjs
5
+ * DSH_ROOT=... node bench/run.mjs fanout official
6
+ *
7
+ * `official` uses the stock `headless` profile (no plugin). `plain` uses the
8
+ * `lgh` profile with the plugin linked but asks for ordinary tools. `default`
9
+ * leaves the tool choice to the plugin prompt. `coarse`/`fine` force the graph
10
+ * conditions from the matrix. One run per cell; see docs/BENCHMARK.md.
11
+ */
12
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
13
+ import { spawn } from 'node:child_process'
14
+ import { resolve, join } from 'node:path'
15
+
16
+ const DSH = process.env.DSH_ROOT ?? '/Users/zhinan/deepseek-harness'
17
+ const WORK = process.env.BENCH_WORK ?? resolve(DSH, '.lg-bench/work')
18
+ const CLI = ['--import', 'tsx/esm', 'apps/cli/src/bin.ts']
19
+
20
+ const TASKS = {
21
+ fanout: {
22
+ files: Object.fromEntries(Array.from({ length: 8 }, (_, i) => [
23
+ `item-0${i + 1}.txt`,
24
+ `Score: ${[3, 5, 2, 7, 1, 8, 4, 6][i]}\n`,
25
+ ])),
26
+ expected: '36',
27
+ output: 'result.txt',
28
+ prompt: (dir, out, suffix) => `In ${dir} there are files named item-01.txt through item-08.txt. Read every file, sum the numeric values after \`Score:\`, and write only the sum to:\n${out}\n\n${suffix}`,
29
+ },
30
+ report: {
31
+ files: {
32
+ 'alpha.txt': 'Project: Alpha\nOwner: Alice\nServices: 3\n',
33
+ 'beta.txt': 'Project: Beta\nOwner: Chen\nServices: 5\n',
34
+ 'gamma.txt': 'Project: Gamma\nOwner: Dana\nServices: 4\n',
35
+ },
36
+ expected: 'Beta: Chen',
37
+ output: 'result.md',
38
+ prompt: (dir, out, suffix) => `Read these three project files:\n- ${join(dir, 'alpha.txt')}\n- ${join(dir, 'beta.txt')}\n- ${join(dir, 'gamma.txt')}\n\nWhich project has the most services? Write exactly \`ProjectName: OwnerName\` (omit the word "Project" from the project name) to:\n${out}\n\n${suffix}`,
39
+ },
40
+ }
41
+
42
+ const CONDITIONS = {
43
+ official: {
44
+ profile: 'headless',
45
+ suffix: 'Use ordinary DSH tools.',
46
+ },
47
+ plain: {
48
+ profile: 'lgh',
49
+ suffix: 'Use ordinary DSH tools. Do not use `langgraph_compose` or `langgraph_run` for this task.',
50
+ },
51
+ default: {
52
+ profile: 'lgh',
53
+ suffix: '',
54
+ },
55
+ coarse: {
56
+ profile: 'lgh',
57
+ suffix: 'Use `langgraph_compose` to define a coarse LangGraph graph, then run it with `langgraph_run`. Keep the graph at the seams: put the open-ended work inside `agent` nodes; do not create one node per file or per tool call.',
58
+ },
59
+ fine: {
60
+ profile: 'lgh',
61
+ suffix: 'Use `langgraph_compose` to define a fine-grained LangGraph graph, then run it with `langgraph_run`. Model each concrete step as explicit `tool` or `model` nodes with explicit edges. Use `map` for the per-file work if it fits.',
62
+ },
63
+ }
64
+
65
+ function parseJsonl(text) {
66
+ const events = []
67
+ for (const line of text.split('\n')) {
68
+ if (!line.trim()) continue
69
+ try { events.push(JSON.parse(line)) } catch { /* ignore non-JSON */ }
70
+ }
71
+ return events
72
+ }
73
+
74
+ function summarize(text) {
75
+ const events = parseJsonl(text)
76
+ let steps = 0
77
+ let total = 0
78
+ let input = 0
79
+ let output = 0
80
+ const tools = {}
81
+ let final
82
+ for (const event of events) {
83
+ if (event.type === 'status' && event.phase === 'step_end' && event.usage) {
84
+ steps += 1
85
+ input += event.usage.inputTokens ?? 0
86
+ output += event.usage.outputTokens ?? 0
87
+ total += event.usage.totalTokens ?? 0
88
+ }
89
+ if (event.type === 'tool_call' && typeof event.tool === 'string') {
90
+ tools[event.tool] = (tools[event.tool] ?? 0) + 1
91
+ }
92
+ if (event.type === 'final') final = event
93
+ }
94
+ return { steps, tokens: { input, output, total }, tools, final: final?.reason ?? null }
95
+ }
96
+
97
+ async function runCell(taskName, conditionName) {
98
+ const task = TASKS[taskName]
99
+ const condition = CONDITIONS[conditionName]
100
+ if (!task || !condition) throw new Error(`unknown task/condition ${taskName}/${conditionName}`)
101
+ const root = resolve(WORK, `${taskName}-${conditionName}`)
102
+ const output = join(root, task.output)
103
+ await rm(root, { recursive: true, force: true })
104
+ await mkdir(root, { recursive: true })
105
+ for (const [name, content] of Object.entries(task.files)) {
106
+ await writeFile(join(root, name), content, 'utf8')
107
+ }
108
+ const suffix = condition.suffix
109
+ const prompt = task.prompt(root, output, suffix).trim()
110
+ const started = Date.now()
111
+ const child = spawn(process.execPath, [...CLI, '--profile', condition.profile, 'headless', '--json', '--permission-mode', 'workspace-write', '--approval-policy', 'never', prompt], {
112
+ cwd: DSH,
113
+ env: { ...process.env },
114
+ })
115
+ let stdout = ''
116
+ let stderr = ''
117
+ child.stdout.on('data', chunk => { stdout += chunk })
118
+ child.stderr.on('data', chunk => { stderr += chunk })
119
+ const code = await new Promise(resolve => child.on('close', resolve))
120
+ const seconds = Math.round((Date.now() - started) / 1000)
121
+ const summary = summarize(stdout)
122
+ let result
123
+ try { result = (await readFile(output, 'utf8')).trim() } catch { result = undefined }
124
+ const success = result !== undefined && result.includes(task.expected)
125
+ return { task: taskName, condition: conditionName, profile: condition.profile, success, seconds, steps: summary.steps, tokens: summary.tokens, tools: summary.tools, result: result?.slice(0, 120) ?? null, exit: code, stderr: stderr.slice(-300) }
126
+ }
127
+
128
+ const [taskArg, conditionArg] = process.argv.slice(2)
129
+ const pairs = taskArg && conditionArg
130
+ ? [[taskArg, conditionArg]]
131
+ : Object.keys(TASKS).flatMap(task => ['official', 'plain', 'default'].map(condition => [task, condition]))
132
+ const results = []
133
+ for (const [task, condition] of pairs) {
134
+ process.stderr.write(`\n== ${task} / ${condition} ==\n`)
135
+ const result = await runCell(task, condition)
136
+ results.push(result)
137
+ process.stderr.write(JSON.stringify(result) + '\n')
138
+ }
139
+ console.log(JSON.stringify(results, null, 2))
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Graph analysis for the GraphSpec IR: adjacency, Tarjan SCCs, reachability,
3
+ * writer/reducer checks for static fan-out, and advisory lint.
4
+ *
5
+ * Analysis never mutates a spec and never builds a graph. The compiler uses it
6
+ * for validation; the failure report and the future `fork` action use it to name
7
+ * a failed node's cycle and downstream.
8
+ */
9
+
10
+ import { END, START } from './constants.js'
11
+ import { hasStateKey, isPlainObject } from './template.js'
12
+
13
+ /** Group edges by source, keeping the spec's edge order. */
14
+ function groupBySource(spec) {
15
+ const outgoing = new Map()
16
+ for (const edge of spec.edges ?? []) {
17
+ if (!outgoing.has(edge.from)) outgoing.set(edge.from, [])
18
+ outgoing.get(edge.from).push(edge)
19
+ }
20
+ return outgoing
21
+ }
22
+
23
+ /** Group edges by target. */
24
+ function groupByTarget(spec) {
25
+ const incoming = new Map()
26
+ for (const edge of spec.edges ?? []) {
27
+ if (!incoming.has(edge.to)) incoming.set(edge.to, [])
28
+ incoming.get(edge.to).push(edge)
29
+ }
30
+ return incoming
31
+ }
32
+
33
+ /** Breadth-first reachability over `outgoing` edges. */
34
+ function reachable(outgoing, starts) {
35
+ const seen = new Set(starts)
36
+ const queue = [...starts]
37
+ while (queue.length > 0) {
38
+ const id = queue.shift()
39
+ for (const edge of outgoing.get(id) ?? []) {
40
+ if (!seen.has(edge.to)) {
41
+ seen.add(edge.to)
42
+ queue.push(edge.to)
43
+ }
44
+ }
45
+ }
46
+ return seen
47
+ }
48
+
49
+ /** Breadth-first reachability over `incoming` edges. */
50
+ function reverseReachable(incoming, starts) {
51
+ const seen = new Set(starts)
52
+ const queue = [...starts]
53
+ while (queue.length > 0) {
54
+ const id = queue.shift()
55
+ for (const edge of incoming.get(id) ?? []) {
56
+ if (!seen.has(edge.from)) {
57
+ seen.add(edge.from)
58
+ queue.push(edge.from)
59
+ }
60
+ }
61
+ }
62
+ return seen
63
+ }
64
+
65
+ /**
66
+ * Tarjan's strongly connected components over the spec's real nodes. START and
67
+ * END are excluded; a self-loop counts as a cycle.
68
+ * @param {Set<string>} nodeIds - real node ids.
69
+ * @param {(id: string) => string[]} successors - sorted successor node ids.
70
+ * @returns {string[][]} SCCs, each sorted, and the list sorted by first member.
71
+ */
72
+ function tarjan(nodeIds, successors) {
73
+ let nextIndex = 0
74
+ const index = new Map()
75
+ const low = new Map()
76
+ const stack = []
77
+ const onStack = new Set()
78
+ const components = []
79
+
80
+ function connect(id) {
81
+ index.set(id, nextIndex)
82
+ low.set(id, nextIndex)
83
+ nextIndex += 1
84
+ stack.push(id)
85
+ onStack.add(id)
86
+ for (const next of successors(id)) {
87
+ if (!index.has(next)) {
88
+ connect(next)
89
+ low.set(id, Math.min(low.get(id), low.get(next)))
90
+ } else if (onStack.has(next)) {
91
+ low.set(id, Math.min(low.get(id), index.get(next)))
92
+ }
93
+ }
94
+ if (low.get(id) === index.get(id)) {
95
+ const component = []
96
+ let member
97
+ do {
98
+ member = stack.pop()
99
+ onStack.delete(member)
100
+ component.push(member)
101
+ } while (member !== id)
102
+ components.push(component.sort())
103
+ }
104
+ }
105
+
106
+ for (const id of [...nodeIds].sort()) {
107
+ if (!index.has(id)) connect(id)
108
+ }
109
+ components.sort((left, right) => left[0].localeCompare(right[0]))
110
+ return components
111
+ }
112
+
113
+ /**
114
+ * Analyze one spec.
115
+ * @param {object} spec - a structurally valid GraphSpec.
116
+ * @returns {object} nodes, adjacency, SCCs, reachability, and the SCC of each node.
117
+ */
118
+ export function analyze(spec) {
119
+ const nodes = new Map((spec.nodes ?? []).map(node => [node.id, node]))
120
+ const outgoing = new Map()
121
+ const incoming = new Map()
122
+ for (const id of [START, ...nodes.keys(), END]) {
123
+ outgoing.set(id, [])
124
+ incoming.set(id, [])
125
+ }
126
+ for (const edge of spec.edges ?? []) {
127
+ const sourceExists = outgoing.has(edge.from)
128
+ const targetExists = incoming.has(edge.to)
129
+ if (!sourceExists || !targetExists) continue
130
+ outgoing.get(edge.from).push(edge)
131
+ incoming.get(edge.to).push(edge)
132
+ }
133
+
134
+ const nodeSuccessors = id => [...new Set(
135
+ (outgoing.get(id) ?? [])
136
+ .map(edge => edge.to)
137
+ .filter(target => nodes.has(target)),
138
+ )].sort()
139
+ const sccs = tarjan(new Set(nodes.keys()), nodeSuccessors)
140
+ const sccOf = new Map()
141
+ sccs.forEach((component, componentIndex) => {
142
+ for (const id of component) sccOf.set(id, componentIndex)
143
+ })
144
+
145
+ return {
146
+ nodes,
147
+ outgoing,
148
+ incoming,
149
+ sccs,
150
+ sccOf,
151
+ reachableFromStart: reachable(outgoing, [START]),
152
+ canReachEnd: reverseReachable(incoming, [END]),
153
+ }
154
+ }
155
+
156
+ /** Whether a node writes a state field through `out`, `set`, or a map body. */
157
+ export function writesField(node, field) {
158
+ if (node === undefined || node === null) return false
159
+ if (node.out !== undefined && Object.prototype.hasOwnProperty.call(node.out, field)) return true
160
+ if (node.do === 'set' && isPlainObject(node.values) && Object.prototype.hasOwnProperty.call(node.values, field)) return true
161
+ if (node.do === 'map' && writesField(node.body, field)) return true
162
+ return false
163
+ }
164
+
165
+ /** All node ids reachable from the given node ids, including them and END. */
166
+ export function downstreamOf(analysis, ids) {
167
+ const starts = Array.isArray(ids) ? ids : [ids]
168
+ return [...reachable(analysis.outgoing, starts)].sort()
169
+ }
170
+
171
+ /** All node ids that can reach the given node ids, including them and START. */
172
+ export function upstreamOf(analysis, ids) {
173
+ const starts = Array.isArray(ids) ? ids : [ids]
174
+ return [...reverseReachable(analysis.incoming, starts)].sort()
175
+ }
176
+
177
+ /**
178
+ * Validate the writer/reducer contract for static fan-out: when one node has
179
+ * two or more unconditional out-edges, every state field written by more than
180
+ * one of those branches must use a mergeable reducer.
181
+ * @param {object} spec - a structurally valid GraphSpec.
182
+ * @param {object} analysis - the result of `analyze(spec)`.
183
+ * @returns {Array<{ path: string, message: string, expected?: string }>} problems.
184
+ */
185
+ export function fanOutProblems(spec, analysis) {
186
+ const problems = []
187
+ const state = isPlainObject(spec.state) ? spec.state : {}
188
+ for (const source of [START, ...analysis.nodes.keys()]) {
189
+ const unconditional = (analysis.outgoing.get(source) ?? [])
190
+ .filter(edge => edge.when === undefined)
191
+ .map(edge => edge.to)
192
+ const branches = [...new Set(unconditional)]
193
+ .filter(target => analysis.nodes.has(target))
194
+ .sort()
195
+ if (branches.length < 2) continue
196
+ for (const field of Object.keys(state).sort()) {
197
+ const writers = branches.filter(branch => writesField(analysis.nodes.get(branch), field))
198
+ if (writers.length < 2) continue
199
+ const reducer = state[field]?.reducer ?? 'replace'
200
+ if (reducer !== 'replace') continue
201
+ problems.push({
202
+ path: `state.${field}`,
203
+ message: `field "${field}" is written by parallel branches ${writers.join(', ')} from "${source}" but has no mergeable reducer`,
204
+ expected: 'append | add | max | min | merge',
205
+ })
206
+ }
207
+ }
208
+ return problems
209
+ }
210
+
211
+ /**
212
+ * Advisory lint. None of these block a spec; they name shapes that usually mean
213
+ * the graph is too fine, cannot finish, or has unreachable work.
214
+ * @param {object} spec - a structurally valid GraphSpec.
215
+ * @param {object} analysis - the result of `analyze(spec)`.
216
+ * @returns {Array<{ path: string, message: string, code: string }>} warnings.
217
+ */
218
+ export function lintWarnings(spec, analysis) {
219
+ const warnings = []
220
+ const warn = (path, message, code) => warnings.push({ path, message, code })
221
+ const state = isPlainObject(spec.state) ? spec.state : {}
222
+
223
+ for (const node of spec.nodes ?? []) {
224
+ if ((analysis.outgoing.get(node.id) ?? []).length === 0) {
225
+ warn(`nodes.${node.id}`, 'node has no outgoing edge; the run ends here — connect it to END for clarity', 'terminal')
226
+ }
227
+ }
228
+
229
+ for (const id of [...analysis.nodes.keys()].sort()) {
230
+ if (!analysis.reachableFromStart.has(id)) {
231
+ warn(`nodes.${id}`, 'node is not reachable from START', 'unreachable')
232
+ } else if (!analysis.canReachEnd.has(id)) {
233
+ warn(`nodes.${id}`, 'node cannot reach END', 'dead-end')
234
+ }
235
+ }
236
+
237
+ if ((analysis.outgoing.get(START) ?? []).some(edge => edge.to === END)) {
238
+ warn('edges', 'START goes directly to END', 'empty-graph')
239
+ }
240
+
241
+ for (const [source, edges] of analysis.outgoing) {
242
+ if (source === END || edges.length === 0) continue
243
+ if (edges.every(edge => edge.when !== undefined) && !edges.some(edge => edge.when === true)) {
244
+ warn(`nodes.${source}`, 'choice has no `when: true` fallback; the run fails if no guard matches', 'no-fallback')
245
+ }
246
+ }
247
+
248
+ for (const node of spec.nodes ?? []) {
249
+ if (node.do !== 'gate' || !Array.isArray(node.options) || node.options.length === 0) continue
250
+ for (const [field, kind] of Object.entries(node.out ?? {})) {
251
+ if (kind !== 'bool') continue
252
+ warn(`nodes.${node.id}.out.${field}`, 'gate options are labels; bool accepts only true/false. Use out { decision: "text" } with an eq guard, or resume true/false.', 'gate-bool-options')
253
+ }
254
+ }
255
+
256
+ const numericWriter = node => {
257
+ const fields = []
258
+ if (node?.out !== undefined) fields.push(...Object.keys(node.out))
259
+ if (node?.do === 'set' && isPlainObject(node.values)) fields.push(...Object.keys(node.values))
260
+ if (node?.do === 'map' && node.body?.out !== undefined) fields.push(...Object.keys(node.body.out))
261
+ return fields.some(field => state[field]?.type === 'number')
262
+ }
263
+
264
+ for (const component of analysis.sccs) {
265
+ const members = [...component].sort()
266
+ const cyclic = members.length > 1
267
+ || (analysis.outgoing.get(members[0]) ?? []).some(edge => edge.to === members[0])
268
+ if (!cyclic) continue
269
+ warn(`nodes.${members[0]}`, `cycle: ${members.join(', ')}; bounded by maxSteps`, 'cycle')
270
+ const exits = members
271
+ .flatMap(id => analysis.outgoing.get(id) ?? [])
272
+ .filter(edge => !members.includes(edge.to))
273
+ if (!exits.some(edge => edge.when !== undefined)) {
274
+ warn(`nodes.${members[0]}`, 'cycle has no conditional exit; it runs until maxSteps', 'cycle-exit')
275
+ }
276
+ if (!members.some(id => numericWriter(analysis.nodes.get(id)))) {
277
+ warn(`nodes.${members[0]}`, 'cycle has no numeric counter; it may never terminate', 'cycle-counter')
278
+ }
279
+ if (spec.maxSteps === undefined) {
280
+ warn('maxSteps', 'cycle relies on the default 25-step budget; set maxSteps explicitly', 'cycle-budget')
281
+ }
282
+ }
283
+
284
+ // --- over-decomposition lint ------------------------------------------------
285
+ // Advisory only. The main failure mode of a composed graph is turning every
286
+ // tool call into a node; these warnings point at an `agent` node or ordinary
287
+ // tools instead.
288
+ const nodes = spec.nodes ?? []
289
+ if (nodes.length > 12) {
290
+ warn('nodes', `${nodes.length} nodes; coarse-first graphs usually use 4-8 phase nodes`, 'too-many-nodes')
291
+ }
292
+
293
+ const containsStateRef = value => {
294
+ if (hasStateKey(value)) return true
295
+ if (Array.isArray(value)) return value.some(containsStateRef)
296
+ if (isPlainObject(value)) return Object.values(value).some(containsStateRef)
297
+ return false
298
+ }
299
+
300
+ for (const node of nodes) {
301
+ if (node.do === 'tool') {
302
+ const component = analysis.sccs[analysis.sccOf.get(node.id)]
303
+ const cyclic = (component?.length ?? 1) > 1
304
+ || (analysis.outgoing.get(node.id) ?? []).some(edge => edge.to === node.id)
305
+ if (!cyclic && Object.values(node.args ?? {}).every(value => !containsStateRef(value))) {
306
+ warn(`nodes.${node.id}`, 'tool node has only literal arguments and runs once; consider merging it into an agent node', 'literal-tool')
307
+ }
308
+ }
309
+ if (node.do === 'model') {
310
+ const outgoing = analysis.outgoing.get(node.id) ?? []
311
+ if (outgoing.length === 1 && analysis.nodes.get(outgoing[0].to)?.do === 'tool') {
312
+ warn(`nodes.${node.id}`, 'model feeds a single tool node; an agent node usually covers that step better', 'model-then-tool')
313
+ }
314
+ }
315
+ }
316
+
317
+ if (nodes.length > 0 && nodes.length <= 2
318
+ && nodes.every(node => !['agent', 'gate', 'map', 'subagent'].includes(node.do))
319
+ && nodes.every(node => (analysis.outgoing.get(node.id) ?? []).length <= 1
320
+ && (analysis.incoming.get(node.id) ?? []).length <= 1
321
+ && analysis.reachableFromStart.has(node.id)
322
+ && analysis.canReachEnd.has(node.id))) {
323
+ warn('nodes', 'a one- or two-step linear graph; use ordinary DSH tools instead', 'tiny-graph')
324
+ }
325
+
326
+ // Longest chain in the SCC condensation, so a loop counts as one phase.
327
+ const relevant = new Set([...analysis.reachableFromStart].filter(id => analysis.canReachEnd.has(id)))
328
+ const components = analysis.sccs
329
+ const adjacency = components.map(() => new Set())
330
+ for (const [source, edges] of analysis.outgoing) {
331
+ if (!analysis.sccOf.has(source)) continue
332
+ const from = analysis.sccOf.get(source)
333
+ if (!components[from].some(id => relevant.has(id))) continue
334
+ for (const edge of edges) {
335
+ if (!analysis.sccOf.has(edge.to)) continue
336
+ const to = analysis.sccOf.get(edge.to)
337
+ if (from !== to) adjacency[from].add(to)
338
+ }
339
+ }
340
+ const lengths = new Map()
341
+ const longestFrom = index => {
342
+ if (lengths.has(index)) return lengths.get(index)
343
+ let best = 1
344
+ for (const next of adjacency[index]) best = Math.max(best, 1 + longestFrom(next))
345
+ lengths.set(index, best)
346
+ return best
347
+ }
348
+ let longest = { length: 0, index: -1 }
349
+ components.forEach((component, index) => {
350
+ if (!component.some(id => relevant.has(id))) return
351
+ const length = longestFrom(index)
352
+ if (length > longest.length) longest = { length, index }
353
+ })
354
+ if (longest.length > 8) {
355
+ warn(`nodes.${components[longest.index][0]}`, `linear chain of ${longest.length} phases; coarse-first graphs usually use 4-8 nodes`, 'long-chain')
356
+ }
357
+
358
+ return warnings
359
+ }