yadflow 4.9.0 → 4.11.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 (155) hide show
  1. package/CHANGELOG.md +184 -0
  2. package/README.md +15 -5
  3. package/bin/commands.mjs +11 -1
  4. package/bin/yad.mjs +203 -14
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1797 -73
  7. package/cli/agent-rules.mjs +64 -5
  8. package/cli/argv-flags.mjs +2 -2
  9. package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
  10. package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
  11. package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
  12. package/cli/brain/vendor/graphology-library.min.js +2 -0
  13. package/cli/brain/vendor/graphology.umd.min.js +2 -0
  14. package/cli/brain/vendor/sigma.min.js +1369 -0
  15. package/cli/brain/view/app.js +382 -0
  16. package/cli/brain/view/index.html +63 -0
  17. package/cli/brain/view/live.css +228 -0
  18. package/cli/brain/view/live.html +110 -0
  19. package/cli/brain/view/live.js +884 -0
  20. package/cli/brain/view/style.css +141 -0
  21. package/cli/brain-about.mjs +206 -0
  22. package/cli/brain-activity.mjs +285 -0
  23. package/cli/brain-skills.mjs +118 -0
  24. package/cli/brain-vendor.mjs +71 -0
  25. package/cli/brain-view.mjs +344 -0
  26. package/cli/brain.mjs +810 -0
  27. package/cli/ci-check.mjs +48 -4
  28. package/cli/codeowners-command.mjs +72 -6
  29. package/cli/commit.mjs +17 -3
  30. package/cli/docs.mjs +2 -0
  31. package/cli/doctor.mjs +151 -25
  32. package/cli/epic-state.mjs +186 -4
  33. package/cli/epic.mjs +26 -10
  34. package/cli/errors.mjs +2 -1
  35. package/cli/find-product.mjs +69 -15
  36. package/cli/fold.mjs +31 -6
  37. package/cli/foundation-publish.mjs +256 -0
  38. package/cli/gate.mjs +29 -3
  39. package/cli/git-read.mjs +38 -0
  40. package/cli/guard-stream.mjs +409 -0
  41. package/cli/guide.mjs +3 -1
  42. package/cli/hook.mjs +102 -9
  43. package/cli/issue-links.mjs +61 -0
  44. package/cli/issues-act.mjs +371 -0
  45. package/cli/issues-write.mjs +441 -0
  46. package/cli/issues.mjs +513 -0
  47. package/cli/lib.mjs +37 -2
  48. package/cli/lifecycle.mjs +7 -0
  49. package/cli/local-page.mjs +138 -0
  50. package/cli/machine.mjs +1 -1
  51. package/cli/manifest.mjs +59 -3
  52. package/cli/map/view/app.js +712 -0
  53. package/cli/map/view/index.html +50 -0
  54. package/cli/map/view/style.css +142 -0
  55. package/cli/map-view.mjs +186 -0
  56. package/cli/map.mjs +637 -0
  57. package/cli/members.mjs +9 -15
  58. package/cli/next.mjs +1 -1
  59. package/cli/openpr.mjs +26 -6
  60. package/cli/plan.mjs +127 -0
  61. package/cli/platform.mjs +159 -4
  62. package/cli/product-index.mjs +1 -1
  63. package/cli/protection.mjs +53 -3
  64. package/cli/reconcile.mjs +9 -3
  65. package/cli/report.mjs +9 -3
  66. package/cli/reports-dir.mjs +391 -0
  67. package/cli/reports.mjs +65 -0
  68. package/cli/run-checks.mjs +15 -4
  69. package/cli/scan.mjs +314 -0
  70. package/cli/setup.mjs +42 -8
  71. package/cli/standup.mjs +120 -78
  72. package/cli/status.mjs +6 -5
  73. package/cli/story-frames.mjs +17 -6
  74. package/cli/test-agents-file.mjs +985 -12
  75. package/cli/test-brain-activity.mjs +753 -0
  76. package/cli/test-brain-view.mjs +381 -0
  77. package/cli/test-brain.mjs +795 -0
  78. package/cli/test-build.mjs +25 -0
  79. package/cli/test-ci-check.mjs +469 -10
  80. package/cli/test-guide.mjs +218 -0
  81. package/cli/test-machine.mjs +59 -0
  82. package/cli/test-map.mjs +615 -0
  83. package/cli/test-node.mjs +15 -0
  84. package/cli/test-reports.mjs +382 -0
  85. package/cli/test-run-checks.mjs +21 -0
  86. package/cli/test-setup-agent.mjs +14 -0
  87. package/cli/test-story-frames.mjs +74 -4
  88. package/cli/test-worktree.mjs +24 -3
  89. package/cli/toolbox-connect.mjs +259 -0
  90. package/cli/toolbox.mjs +187 -12
  91. package/cli/update-commit.mjs +101 -9
  92. package/cli/usage.mjs +8 -4
  93. package/package.json +12 -4
  94. package/skills/sdlc/config.yaml +1 -1
  95. package/skills/sdlc/module-help.csv +3 -1
  96. package/skills/yad-analysis/SKILL.md +4 -0
  97. package/skills/yad-architecture/SKILL.md +22 -4
  98. package/skills/yad-backfill/SKILL.md +4 -0
  99. package/skills/yad-change/SKILL.md +7 -1
  100. package/skills/yad-change/references/triage.md +2 -0
  101. package/skills/yad-checks/SKILL.md +15 -7
  102. package/skills/yad-checks/references/check-gates.md +70 -35
  103. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  104. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  105. package/skills/yad-checks/templates/checks/member-check.mjs +3 -2
  106. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  107. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  108. package/skills/yad-checks/templates/checks/verified-commits.sh +3 -3
  109. package/skills/yad-checks/templates/github/yad-checks.yml +358 -69
  110. package/skills/yad-checks/templates/github/yad-pr-text.yml +118 -0
  111. package/skills/yad-checks/templates/github/yad-product-checks.yml +130 -54
  112. package/skills/yad-checks/templates/github/yad-product-pr-text.yml +131 -0
  113. package/skills/yad-checks/templates/github/yad-update-guard.yml +2 -1
  114. package/skills/yad-checks/templates/github/yad-verified-commits.yml +49 -3
  115. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +80 -20
  116. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +59 -9
  117. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -0
  118. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +49 -1
  119. package/skills/yad-checks/templates/hooks/agent-guard.mjs +44 -10
  120. package/skills/yad-checks/templates/hooks/ledger-guard-cursor.mjs +12 -6
  121. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  122. package/skills/yad-commit/SKILL.md +3 -1
  123. package/skills/yad-connect-design/SKILL.md +42 -10
  124. package/skills/yad-connect-design/references/design-context.md +35 -5
  125. package/skills/yad-connect-design/references/design-registry.md +3 -3
  126. package/skills/yad-connect-learning/SKILL.md +12 -2
  127. package/skills/yad-connect-repos/SKILL.md +18 -0
  128. package/skills/yad-connect-testing/SKILL.md +22 -5
  129. package/skills/yad-connect-testing/references/testing-context.md +1 -1
  130. package/skills/yad-discovery/SKILL.md +11 -0
  131. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  132. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  133. package/skills/yad-docs/templates/app/package.json +6 -1
  134. package/skills/yad-epic/SKILL.md +7 -0
  135. package/skills/yad-epic/references/state-schema.md +50 -1
  136. package/skills/yad-guide/SKILL.md +8 -4
  137. package/skills/yad-implement/SKILL.md +117 -4
  138. package/skills/yad-implement/references/implement-conventions.md +2 -1
  139. package/skills/yad-issues/SKILL.md +54 -0
  140. package/skills/yad-learn/SKILL.md +4 -0
  141. package/skills/yad-open-pr/SKILL.md +6 -0
  142. package/skills/yad-pr-template/SKILL.md +2 -1
  143. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  144. package/skills/yad-pr-template/templates/checks/pr-title.sh +42 -6
  145. package/skills/yad-product-bridge/references/bridge.md +28 -0
  146. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +25 -11
  147. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +38 -14
  148. package/skills/yad-run/SKILL.md +5 -0
  149. package/skills/yad-scan/SKILL.md +51 -0
  150. package/skills/yad-spec/SKILL.md +32 -2
  151. package/skills/yad-stories/SKILL.md +22 -4
  152. package/skills/yad-stories/references/story-schema.md +1 -1
  153. package/skills/yad-test-cases/SKILL.md +18 -2
  154. package/skills/yad-ui/SKILL.md +43 -8
  155. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
package/cli/brain.mjs ADDED
@@ -0,0 +1,810 @@
1
+ // E176 — the project brain: one knowledge graph of the code AND the work, built on this machine.
2
+ //
3
+ // yad brain build [--repo <name>] [--json] run Graphify in each connected code repo, then merge its code
4
+ // graph with the work items into .sdlc/brain/graph.json
5
+ // yad brain query <text> [--limit n] [--json] the nodes whose name holds <text>, each with its neighbours
6
+ // yad brain status [--json] is the brain there, is it current, is each repo graph current
7
+ //
8
+ // THE RULES, each one the user's decision (2026-11-13; the E176 roadmap row has the reasons):
9
+ // 1. ONE GRAPH, TWO LAYERS. The CODE layer is Graphify's (github.com/Graphify-Labs/graphify): files,
10
+ // symbols, calls, imports, parsed locally with tree-sitter. The WORK layer is yadflow's own: epics,
11
+ // stories, tasks, contract surfaces, ships, repos, read from the Product's files. Edges join them: a task
12
+ // declares files, a story touches a surface, a surface is named in the code.
13
+ // 2. NOTHING LEAVES THE MACHINE. Graphify runs with GRAPHIFY_BACKEND=none (no LLM pass: code only) and
14
+ // GRAPHIFY_QUERY_LOG_DISABLE=1, and without the shell's LLM keys, so a backend it misread has nothing to
15
+ // call. yad never runs `graphify install`, `hook install`, `watch`, its MCP server or its query
16
+ // commands: `yad brain query` reads the merged file itself.
17
+ // 3. DERIVED, LOCAL, NEVER COMMITTED. `.sdlc/brain/` holds its own `.gitignore` (`*`), so the folder ignores
18
+ // itself and no shared file changes. It holds names from private code, and it is rebuilt from git.
19
+ // 4. STALENESS IS A HASH of the exact bytes it was built from (the E19 rule, `indexHash`), plus, per repo,
20
+ // the HEAD its code graph was built at (the `syncedHead` rule).
21
+ // 5. EVERY EDGE SAYS HOW IT IS KNOWN. EXTRACTED: a field or a parse says so (a story's `repos:`, a task's
22
+ // **Files:** line, a call in the code). INFERRED: a name matched a name (a surface `Order` and a class
23
+ // `Order`). Graphify's own edges keep Graphify's word.
24
+ // 6. WITHOUT GRAPHIFY IT STILL WORKS: the work layer alone, with a file node for each declared file.
25
+ //
26
+ // Every name a key is made from comes from a file anyone can edit, so the lookups are Maps, never plain
27
+ // objects: a story naming the repo `constructor` must not reach Object.prototype (E176 review 1).
28
+ import fs from 'node:fs';
29
+ import { spawnSync } from 'node:child_process';
30
+ import path from 'node:path';
31
+ import { c, emitJSON, fail, forTerminal, hand, info, isPlainObject, log, ok, refuse, run, warn } from './lib.mjs';
32
+ import { err } from './errors.mjs';
33
+ import { productConfigPath } from './manifest.mjs';
34
+ import { buildIndex, indexHash, readInput } from './product-index.mjs';
35
+ import { epicRoot, parseFrontmatter, declaredRepos } from './epic-state.mjs';
36
+ import { lightTasksBlock, isLightSpec } from './build.mjs';
37
+ import { readShips } from './ledger.mjs';
38
+ import { judgeRepo, readRegistry } from './workspace.mjs';
39
+ import { whereOnPath } from './toolbox.mjs';
40
+ import { fileAbout, storyAbout } from './brain-about.mjs';
41
+
42
+ export const GRAPHIFY_VERSION = '0.9.108';
43
+ // The `graph.schema_version` values this reader knows. A new one is refused, never guessed at.
44
+ export const GRAPHIFY_SCHEMAS = Object.freeze([1]);
45
+ // Mixed into the hash: move it whenever `composeBrain` changes what it writes.
46
+ export const BRAIN_FORMAT = 'yad-brain-1';
47
+ export const BRAIN_DIR = path.join('.sdlc', 'brain');
48
+ export const BRAIN_FILE = path.join(BRAIN_DIR, 'graph.json');
49
+ const CODE = 'YAD-STATE-011';
50
+ export const GRAPHIFY_ENV = Object.freeze({ GRAPHIFY_BACKEND: 'none', GRAPHIFY_QUERY_LOG_DISABLE: '1' });
51
+ // The shell's LLM settings, which Graphify reads to pick a backend: left out of its environment.
52
+ export const LLM_ENV = /^(?:.*_API_KEY|.*_BASE_URL|ANTHROPIC_.*|OPENAI_.*|AZURE_OPENAI_.*|GEMINI_.*|GOOGLE_API_KEY|GOOGLE_APPLICATION_CREDENTIALS|MOONSHOT_.*|DEEPSEEK_.*|OLLAMA_.*|AWS_.*|GRAPHIFY_.*)$/i;
53
+ // Graphify on a large repo is slow, but never this slow; a hang must not hold `yad` for ever.
54
+ const GRAPHIFY_TIMEOUT_MS = 20 * 60 * 1000;
55
+ // A repo name becomes a folder name under .sdlc/brain/repos/: one plain word, never a path or a key that
56
+ // means something to JavaScript.
57
+ const RESERVED = new Set(['__proto__', 'constructor', 'prototype']);
58
+ export const safeName = (n) => typeof n === 'string' && /^\w[\w.-]*$/.test(n) && !n.includes('..') && !RESERVED.has(n);
59
+ const posix = (p) => String(p).replace(/\\/g, '/').replace(/^\.\//, '');
60
+
61
+ // ---- paths with no link on the way ----------------------------------------------------------------
62
+
63
+ // Make each folder of `parts` under `base`, refusing any that is not a plain folder: writing through a link
64
+ // would put the file wherever it points. Returns the last folder.
65
+ function plainDirs(base, parts, label) {
66
+ let cur = path.resolve(base);
67
+ for (const part of parts) {
68
+ cur = path.join(cur, part);
69
+ let st = null;
70
+ try { st = fs.lstatSync(cur); } catch { /* made below */ }
71
+ if (st && !st.isDirectory()) throw err(CODE, `${label(cur)} is not a plain folder (a link?)`, 'move it aside, then run `yad brain build` again');
72
+ if (!st) fs.mkdirSync(cur);
73
+ }
74
+ return cur;
75
+ }
76
+
77
+ // Make `.sdlc/brain/` with its own `.gitignore`.
78
+ export function ensureBrainDir(root) {
79
+ const cur = plainDirs(root, ['.sdlc', 'brain'], (p) => path.relative(root, p));
80
+ const gi = path.join(cur, '.gitignore');
81
+ let st = null;
82
+ try { st = fs.lstatSync(gi); } catch { /* written below */ }
83
+ if (st && !st.isFile()) throw err(CODE, `${BRAIN_DIR}/.gitignore is not a plain file`, 'remove it, then run `yad brain build` again');
84
+ if (!st || fs.readFileSync(gi, 'utf8') !== '*\n') fs.writeFileSync(gi, '*\n');
85
+ return cur;
86
+ }
87
+
88
+ // A file inside `base`, read only when nothing on its way is a link (a committed link could point anywhere).
89
+ function readPlain(base, rel) {
90
+ let cur = base;
91
+ for (const part of rel.split('/')) {
92
+ cur = path.join(cur, part);
93
+ try { if (fs.lstatSync(cur).isSymbolicLink()) return { error: 'a link' }; } catch { return { absent: true }; }
94
+ }
95
+ return readInput(cur);
96
+ }
97
+
98
+ // Write a file by a temp file and a rename: a rename replaces a link where `writeFileSync` would follow it,
99
+ // and a committed link (`files.txt -> ~/.zshrc`) would take every name from the code repo (E176 review 2).
100
+ export function writePlain(dir, name, data) {
101
+ const file = path.join(dir, name);
102
+ const tmp = `${file}.${process.pid}.tmp`;
103
+ // A temp left by a killed run under a reused pid is removed first; `rmSync` takes a link itself, never
104
+ // what it points at, and `wx` still refuses one made in between.
105
+ fs.rmSync(tmp, { force: true });
106
+ try {
107
+ fs.writeFileSync(tmp, data, { flag: 'wx' });
108
+ fs.renameSync(tmp, file);
109
+ } finally {
110
+ fs.rmSync(tmp, { force: true });
111
+ }
112
+ }
113
+
114
+ // ---- Graphify's file -----------------------------------------------------------------------------
115
+
116
+ // Graphify's graph.json, as { schemaVersion, graphifyVersion, nodes, edges }. Its edges are under `links`
117
+ // (networkx's node-link format); `edges` is read too, for a release that renames it.
118
+ export function readGraphify(text) {
119
+ let g;
120
+ try { g = JSON.parse(text); } catch { throw err(CODE, 'the Graphify graph does not parse', 'run `yad brain build` again'); }
121
+ if (!isPlainObject(g)) throw err(CODE, 'the Graphify graph is not an object', 'run `yad brain build` again');
122
+ const schemaVersion = isPlainObject(g.graph) ? g.graph.schema_version : undefined;
123
+ if (!GRAPHIFY_SCHEMAS.includes(schemaVersion)) {
124
+ throw err(CODE, `the Graphify graph has schema_version ${JSON.stringify(schemaVersion ?? null)}, which this yadflow does not read (it reads ${GRAPHIFY_SCHEMAS.join(', ')})`,
125
+ `install the vetted Graphify: \`uv tool install graphifyy==${GRAPHIFY_VERSION}\`, then run \`yad brain build\` again`);
126
+ }
127
+ const edges = Array.isArray(g.links) ? g.links : g.edges;
128
+ if (!Array.isArray(g.nodes) || !Array.isArray(edges)) throw err(CODE, 'the Graphify graph has no list of nodes or of links', 'run `yad brain build` again');
129
+ return { schemaVersion, graphifyVersion: typeof g.graph.graphify_version === 'string' ? g.graph.graphify_version : null, nodes: g.nodes, edges };
130
+ }
131
+
132
+ // The Graphify program on PATH, as { bin, version }, or null. `bin` is the file found, which is what runs.
133
+ // A file found that cannot be started (on Windows a `.cmd` shim, which needs a shell) is { bin, startError }.
134
+ export function graphifyHere({ runner = run, where = whereOnPath } = {}) {
135
+ const bin = where('graphify');
136
+ if (!bin) return null;
137
+ const r = runner(bin, ['--version'], { timeout: 60_000 });
138
+ // A slow or hung program is installed: it is said as that, not as one that cannot start.
139
+ if (r.error?.code === 'ETIMEDOUT') return { bin, version: null, startError: 'ETIMEDOUT', hung: true };
140
+ if (r.error) return { bin, version: null, startError: r.error.code || r.error.message };
141
+ const m = /graphify\s+v?(\d[\w.+-]*)/i.exec(`${r.stdout}\n${r.stderr}`);
142
+ return { bin, version: m ? m[1] : 'unknown' };
143
+ }
144
+
145
+ // The environment Graphify runs in: the shell's, without its LLM settings, plus ours. Keys are matched
146
+ // without regard to case, as Windows reads them.
147
+ export function graphifyEnv(env = process.env) {
148
+ const out = {};
149
+ for (const [k, v] of Object.entries(env)) if (!LLM_ENV.test(k)) out[k] = v;
150
+ return { ...out, ...GRAPHIFY_ENV };
151
+ }
152
+
153
+ // Keep Graphify's output folder out of the code repo's git, in `.git/info/exclude` — local to this clone,
154
+ // never committed. Returns false when git cannot say where that file is, or it is not a plain file.
155
+ export function excludeGraphifyOut(target, { runner = run } = {}) {
156
+ const r = runner('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd: target });
157
+ if (!r.ok || !r.stdout) return false;
158
+ const file = path.resolve(target, r.stdout);
159
+ let body = '';
160
+ try {
161
+ const st = fs.lstatSync(file);
162
+ if (!st.isFile()) return false;
163
+ body = fs.readFileSync(file, 'utf8');
164
+ } catch (e) { if (e.code !== 'ENOENT') return false; }
165
+ if (body.split(/\r?\n/).some((l) => l.trim() === 'graphify-out/')) return true;
166
+ fs.mkdirSync(path.dirname(file), { recursive: true });
167
+ fs.writeFileSync(file, `${body.replace(/\n*$/, body ? '\n' : '')}# yad brain build (E176): Graphify's output, kept on this machine\ngraphify-out/\n`);
168
+ return true;
169
+ }
170
+
171
+ const headOf = (target, runner) => { const r = runner('git', ['rev-parse', 'HEAD'], { cwd: target }); return r.ok && /^[0-9a-f]{7,64}$/.test(r.stdout) ? r.stdout : null; };
172
+
173
+ // The code repos the brain can read: registered, on disk, with a safe name that no other repo shares in
174
+ // another case (`Backend` and `backend` are one folder on macOS and Windows). The rest, with why.
175
+ export function brainRepos(root, registry) {
176
+ const usable = [];
177
+ const skipped = [];
178
+ const seen = new Set();
179
+ for (const repo of registry.repos) {
180
+ const name = repo && typeof repo === 'object' ? repo.name : null;
181
+ if (!safeName(name)) { skipped.push({ name: forTerminal(name ?? '(unnamed)'), why: 'its name is not one plain word' }); continue; }
182
+ if (seen.has(name.toLowerCase())) { skipped.push({ name, why: 'another repo has the same name in another case' }); continue; }
183
+ seen.add(name.toLowerCase());
184
+ const j = judgeRepo(root, repo);
185
+ if (j.state !== 'present') {
186
+ const absent = j.state === 'missing' || (j.target && !fs.existsSync(j.target));
187
+ skipped.push({ name, why: absent ? 'not cloned here (`yad repo clone`)' : j.reason || j.state });
188
+ continue;
189
+ }
190
+ usable.push({ name, target: j.target, codeMap: typeof repo.codeMap === 'string' ? repo.codeMap : null });
191
+ }
192
+ return { usable, skipped };
193
+ }
194
+
195
+ // Run Graphify in one repo and keep its graph under .sdlc/brain/repos/<name>/, with the files the checkout
196
+ // holds now — what Graphify read — so a declared file that is not code still counts as there.
197
+ // { ok, why?, nodes?, edges?, warning? }
198
+ export function buildRepoGraph(root, repo, { runner = run, env = process.env, bin = 'graphify' } = {}) {
199
+ // Graphify writes into graphify-out/: a link there would send its files, and our read, anywhere; a tracked
200
+ // folder would have committed files rewritten.
201
+ let outSt = null;
202
+ try { outSt = fs.lstatSync(path.join(repo.target, 'graphify-out')); } catch { /* made by Graphify */ }
203
+ if (outSt && !outSt.isDirectory()) return { ok: false, why: 'graphify-out in the repo is not a plain folder (a link?)' };
204
+ const tracked = runner('git', ['ls-files', '--', 'graphify-out'], { cwd: repo.target });
205
+ if (tracked.ok && tracked.stdout) return { ok: false, why: 'graphify-out/ is committed in this repo, and Graphify would rewrite it' };
206
+ const excluded = excludeGraphifyOut(repo.target, { runner });
207
+ // `--force`: write the graph even when it has fewer nodes than the last one. Without it, Graphify keeps the
208
+ // old file after code is deleted, and the brain would show code that is gone. Its stdout is not read.
209
+ const r = runner(bin, ['update', '.', '--force'], {
210
+ cwd: repo.target, env: graphifyEnv(env), timeout: GRAPHIFY_TIMEOUT_MS, stdio: ['ignore', 'ignore', 'pipe'], maxBuffer: 16 * 1024 * 1024,
211
+ });
212
+ if (r.error?.code === 'ETIMEDOUT') return { ok: false, why: `graphify took longer than ${GRAPHIFY_TIMEOUT_MS / 60000} minutes and was stopped` };
213
+ if (!r.ok) return { ok: false, why: `graphify failed — ${forTerminal((r.stderr || String(r.error?.code || 'no output')).split('\n').pop())}` };
214
+ let text;
215
+ try {
216
+ const st = fs.lstatSync(path.join(repo.target, 'graphify-out'));
217
+ if (!st.isDirectory()) return { ok: false, why: 'graphify-out in the repo is not a plain folder (a link?)' };
218
+ const input = readPlain(repo.target, 'graphify-out/graph.json');
219
+ if (!input.bytes) return { ok: false, why: 'graphify wrote no graphify-out/graph.json' };
220
+ text = input.bytes.toString('utf8');
221
+ } catch { return { ok: false, why: 'graphify wrote no graphify-out/graph.json' }; }
222
+ let g;
223
+ try { g = readGraphify(text); } catch (e) { return { ok: false, why: e.message }; }
224
+ const head = headOf(repo.target, runner);
225
+ // Tracked and new files git does not ignore, that are on disk: the working tree Graphify parsed, not HEAD.
226
+ // Spawned directly, never through `run()`, which trims its output and so the first name's leading space.
227
+ // So the injected `runner` does not see this call: a test gives the repo real files instead.
228
+ const lsr = spawnSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], { cwd: repo.target, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
229
+ const ls = { ok: lsr.status === 0, stdout: lsr.stdout || '' };
230
+ const dir = plainDirs(root, [...BRAIN_DIR.split(path.sep), 'repos', repo.name], (p) => path.relative(root, p));
231
+ writePlain(dir, 'graph.json', text);
232
+ // The list git holds is NUL-separated; kept sorted and LF-separated, so it hashes the same everywhere.
233
+ const files = ls.ok ? [...new Set([...ls.stdout.split('\0').filter(Boolean).filter((f) => fs.existsSync(path.join(repo.target, f))), ...g.nodes.map((n) => (isPlainObject(n) && typeof n.source_file === 'string' ? posix(n.source_file) : null)).filter(Boolean)])].sort() : null;
234
+ if (files) writePlain(dir, 'files.txt', `${files.join('\n')}\n`);
235
+ else fs.rmSync(path.join(dir, 'files.txt'), { force: true });
236
+ const meta = { head, graphifyVersion: g.graphifyVersion, schemaVersion: g.schemaVersion, builtAt: new Date().toISOString() };
237
+ writePlain(dir, 'meta.json', `${JSON.stringify(meta, null, 2)}\n`);
238
+ return { ok: true, nodes: g.nodes.length, edges: g.edges.length, ...(excluded ? {} : { warning: 'graphify-out/ could not be added to the repo\'s .git/info/exclude — git may show it' }) };
239
+ }
240
+
241
+ // The code graph kept for one repo, or why there is none: { graph?, meta?, files?, inputs, why? }.
242
+ function storedRepoGraph(root, name) {
243
+ const input = readPlain(root, posix(path.join(BRAIN_DIR, 'repos', name, 'graph.json')));
244
+ const filesIn = readPlain(root, posix(path.join(BRAIN_DIR, 'repos', name, 'files.txt')));
245
+ const inputs = { input, filesIn };
246
+ if (!input.bytes) return { inputs, why: input.absent ? 'not built yet' : `unreadable (${input.error})` };
247
+ let meta = {};
248
+ const metaIn = readPlain(root, posix(path.join(BRAIN_DIR, 'repos', name, 'meta.json')));
249
+ try { if (metaIn.bytes) meta = JSON.parse(metaIn.bytes.toString('utf8')); } catch { /* no head known */ }
250
+ const files = filesIn.bytes ? new Set(filesIn.bytes.toString('utf8').split('\n').filter(Boolean)) : null;
251
+ try { return { graph: readGraphify(input.bytes.toString('utf8')), meta: isPlainObject(meta) ? meta : {}, files, inputs }; } catch (e) { return { inputs, why: e.message }; }
252
+ }
253
+
254
+ // ---- the work layer ------------------------------------------------------------------------------
255
+
256
+ // The backtick names after "Contract surface touched:" in a story's body. `none` is not a name.
257
+ export function surfacesOf(body) {
258
+ const m = /Contract surface touched:\s*(.*)/i.exec(String(body));
259
+ if (!m) return [];
260
+ return [...new Set([...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1].trim()).filter((s) => s && s.toLowerCase() !== 'none'))];
261
+ }
262
+
263
+ // The tasks of one story in one repo: [{ id, goal, files }]. `## T01 — goal` opens a task; its
264
+ // **Files:** line names the files it may touch, each in backticks.
265
+ export function tasksOf(text) {
266
+ const tasks = [];
267
+ let cur = null;
268
+ for (const line of String(text).split(/\r?\n/)) {
269
+ const h = /^##\s+(T\d+)\b\s*(?:[—–:-]\s*)?(.*)$/.exec(line);
270
+ if (h) { cur = { id: h[1], goal: h[2].trim(), files: [] }; tasks.push(cur); continue; }
271
+ const f = /\*\*Files:\*\*\s*(.*)$/.exec(line);
272
+ if (cur && f) {
273
+ for (const x of f[1].matchAll(/`([^`]+)`/g)) {
274
+ const p = posix(x[1].trim());
275
+ if (p && !path.posix.isAbsolute(p) && !/^[A-Za-z]:/.test(p) && !p.split('/').includes('..') && !cur.files.includes(p)) cur.files.push(p);
276
+ }
277
+ }
278
+ }
279
+ return tasks;
280
+ }
281
+
282
+ // Graph builder with de-duplicated nodes and edges. A node first named only in passing (an epic's parent,
283
+ // a repo a story lists) is a placeholder: its own definition fills it in later, and a second mention never
284
+ // overwrites what a definition wrote.
285
+ function graphBuilder() {
286
+ const nodes = new Map();
287
+ const real = new Set();
288
+ const edges = new Map();
289
+ return {
290
+ nodes,
291
+ node(id, fields, { define = false } = {}) {
292
+ const n = nodes.get(id);
293
+ if (!n) nodes.set(id, { id, ...fields });
294
+ else if (define && !real.has(id)) Object.assign(n, fields);
295
+ else for (const [k, v] of Object.entries(fields)) if (!(k in n)) n[k] = v;
296
+ if (define) real.add(id);
297
+ return id;
298
+ },
299
+ edge(source, target, relation, confidence = 'EXTRACTED', extra = {}) {
300
+ const key = `${source}\0${target}\0${relation}`;
301
+ if (!edges.has(key)) edges.set(key, { source, target, relation, confidence, ...extra });
302
+ },
303
+ edges,
304
+ };
305
+ }
306
+
307
+ // The whole brain, built from the files on disk (it runs nothing but `git rev-parse` in status): { brain,
308
+ // inputs, repos }. `repos` is { name: state } in registry order.
309
+ export function composeBrain(root, { registry = readRegistry(root).registry } = {}) {
310
+ const g = graphBuilder();
311
+ const parts = [];
312
+ const { usable, skipped } = brainRepos(root, registry);
313
+ const repoState = new Map();
314
+ const codeFiles = new Map(); // repo -> Set of files git holds (or, for an old build, that the code graph names)
315
+ const codeByLabel = new Map(); // repo -> Map(lower label without "()" -> [node ids])
316
+ const targets = new Map(usable.map((r) => [r.name, r]));
317
+ const mapLines = new Map();
318
+ parts.push({ name: 'repos.json', input: readInput(path.join(root, '.sdlc', 'repos.json')) });
319
+ parts.push({ name: 'skipped', input: { bytes: Buffer.from(JSON.stringify(skipped)) } });
320
+
321
+ // ---- the code layer
322
+ for (const repo of usable) {
323
+ g.node(`repo:${repo.name}`, { kind: 'repo', label: repo.name }, { define: true });
324
+ const stored = storedRepoGraph(root, repo.name);
325
+ parts.push({ name: `brain/repos/${repo.name}/graph.json`, input: stored.inputs.input });
326
+ parts.push({ name: `brain/repos/${repo.name}/files.txt`, input: stored.inputs.filesIn });
327
+ parts.push({ name: `brain/repos/${repo.name}/head`, input: { bytes: Buffer.from(String(stored.meta?.head ?? '')) } });
328
+ if (!stored.graph) { repoState.set(repo.name, { code: false, why: stored.why }); continue; }
329
+ const { graph, meta } = stored;
330
+ const files = new Set();
331
+ const byLabel = new Map();
332
+ for (const n of graph.nodes) {
333
+ if (!isPlainObject(n) || (typeof n.id !== 'string' && typeof n.id !== 'number')) continue;
334
+ const id = `code:${repo.name}:${n.id}`;
335
+ const file = typeof n.source_file === 'string' && n.source_file ? posix(n.source_file) : null;
336
+ g.node(id, {
337
+ kind: 'code', label: String(n.label ?? n.id), repo: repo.name,
338
+ ...(file ? { file } : {}), ...(typeof n.source_location === 'string' ? { at: n.source_location } : {}),
339
+ ...(n.community !== undefined ? { community: n.community } : {}),
340
+ }, { define: true });
341
+ if (file) {
342
+ files.add(file);
343
+ const fid = g.node(`file:${repo.name}:${file}`, { kind: 'file', label: file, repo: repo.name }, { define: true });
344
+ g.edge(fid, id, 'defines');
345
+ }
346
+ const key = String(n.label ?? '').replace(/\(\)$/, '').replace(/^\./, '').toLowerCase();
347
+ if (key) byLabel.set(key, [...(byLabel.get(key) || []), id]);
348
+ }
349
+ for (const f of files) g.edge(`repo:${repo.name}`, `file:${repo.name}:${f}`, 'holds');
350
+ let dropped = 0;
351
+ for (const e of graph.edges) {
352
+ if (!isPlainObject(e)) continue;
353
+ const s = `code:${repo.name}:${e.source}`;
354
+ const t = `code:${repo.name}:${e.target}`;
355
+ if (!g.nodes.has(s) || !g.nodes.has(t)) { dropped += 1; continue; }
356
+ g.edge(s, t, String(e.relation || 'related'), ['EXTRACTED', 'INFERRED', 'AMBIGUOUS'].includes(e.confidence) ? e.confidence : 'INFERRED',
357
+ typeof e.confidence_score === 'number' ? { score: e.confidence_score } : {});
358
+ }
359
+ codeFiles.set(repo.name, stored.files || files);
360
+ codeByLabel.set(repo.name, byLabel);
361
+ repoState.set(repo.name, { code: true, head: meta.head ?? null, graphifyVersion: meta.graphifyVersion ?? null, nodes: graph.nodes.length, ...(dropped ? { droppedEdges: dropped } : {}) });
362
+ }
363
+ for (const s of skipped) if (!repoState.has(s.name)) repoState.set(s.name, { code: false, why: s.why });
364
+
365
+ // ---- the work layer
366
+ const built = buildIndex(root);
367
+ parts.push({ name: 'index', input: { bytes: Buffer.from(built.inputs) } });
368
+ for (const item of built.index.items) {
369
+ if (item.unreadable) continue;
370
+ const eid = g.node(`epic:${item.id}`, { kind: 'epic', label: item.title || item.id, ...(item.currentStep ? { step: item.currentStep } : {}), ...(item.type ? { type: item.type } : {}) }, { define: true });
371
+ if (item.parent) g.edge(eid, g.node(`epic:${item.parent}`, { kind: 'epic', label: item.parent }), 'changes');
372
+ for (const r of item.repos || []) g.edge(eid, g.node(`repo:${r}`, { kind: 'repo', label: r }), 'touches');
373
+ const dir = epicRoot(root, item.id);
374
+ const contractIn = readInput(path.join(dir, 'contract.md'));
375
+ parts.push({ name: `${item.id}/contract.md`, input: contractIn });
376
+ const contractText = contractIn.bytes ? contractIn.bytes.toString('utf8') : null;
377
+ const cid = contractText !== null ? g.node(`contract:${item.id}`, { kind: 'contract', label: `${item.id} contract` }, { define: true }) : null;
378
+ if (cid) g.edge(eid, cid, 'has-contract');
379
+
380
+ let ships = [];
381
+ try { ships = readShips(dir).filter(isPlainObject); } catch { /* an unreadable ledger: yad doctor says so */ }
382
+ parts.push({ name: `${item.id}/ships`, input: { bytes: Buffer.from(JSON.stringify(ships)) } });
383
+
384
+ const sdir = path.join(dir, 'stories');
385
+ let files = [];
386
+ try { files = fs.readdirSync(sdir).filter((f) => f.endsWith('.md')).sort(); } catch { /* no stories yet */ }
387
+ for (const f of files) {
388
+ const sin = readInput(path.join(sdir, f));
389
+ parts.push({ name: `${item.id}/stories/${f}`, input: sin });
390
+ if (!sin.bytes) continue;
391
+ const text = sin.bytes.toString('utf8');
392
+ const fm = parseFrontmatter(text);
393
+ // One node per story id: ids carry their epic (`EP-x-S01`), so two epics never share one.
394
+ const sidText = typeof fm.id === 'string' && fm.id ? fm.id : f.replace(/\.md$/, '');
395
+ const sid = g.node(`story:${sidText}`, { kind: 'story', label: sidText, ...(typeof fm.status === 'string' ? { status: fm.status } : {}), summary: summaryOf(text) }, { define: true });
396
+ g.edge(eid, sid, 'has-story');
397
+ const repos = declaredRepos(fm);
398
+ for (const r of repos) g.edge(sid, g.node(`repo:${r}`, { kind: 'repo', label: r }), 'builds-in');
399
+
400
+ for (const token of surfacesOf(text)) {
401
+ const surf = g.node(`surface:${token}`, { kind: 'surface', label: token });
402
+ g.edge(sid, surf, 'touches-surface');
403
+ if (cid && contractText.includes(token)) g.edge(cid, surf, 'declares', 'INFERRED');
404
+ for (const r of repos) linkSurface(g, surf, token, r, codeByLabel.get(r), codeMapLines(root, targets.get(r), parts, mapLines));
405
+ }
406
+
407
+ for (const r of repos) {
408
+ // The tasks live in the code repo, so only a repo cloned here has them.
409
+ const t = targets.get(r);
410
+ const state = repoState.get(r);
411
+ for (const task of t ? tasksFor(t.target, sidText, parts, r) : []) {
412
+ const tid = g.node(`task:${sidText}:${r}:${task.id}`, { kind: 'task', label: `${task.id}${task.goal ? ` — ${task.goal}` : ''}`, repo: r }, { define: true });
413
+ g.edge(sid, tid, 'has-task');
414
+ for (const file of task.files) {
415
+ const known = codeFiles.get(r)?.has(file);
416
+ const fid = g.node(`file:${r}:${file}`, { kind: 'file', label: file, repo: r, ...(known || !state?.code ? {} : { missing: true }) });
417
+ g.edge(tid, fid, 'declares-file');
418
+ if (known) g.edge(`repo:${r}`, fid, 'holds');
419
+ }
420
+ }
421
+ // The ships live in the Product's ledger: they are drawn whether or not the repo is cloned here.
422
+ for (const s of ships.filter((x) => x.story === sidText && x.repo === r)) {
423
+ const task = typeof s.task === 'string' && s.task ? s.task : 'ship';
424
+ // One merge commit is one ship, even for a grouped PR's many tasks (#350); a ship with no commit (a
425
+ // retroactive one) is its story's and task's own.
426
+ const key = typeof s.mergeCommit === 'string' && s.mergeCommit ? s.mergeCommit : `${sidText}:${task}:${s.branch ?? ''}`;
427
+ const shid = `ship:${r}:${key}`;
428
+ const prev = g.nodes.get(shid);
429
+ const tasks = [...new Set([...(prev?.tasks || []), `${sidText}/${task}`])].sort();
430
+ // The first PR and date found are kept, so the label does not depend on which row is read last.
431
+ const pr = prev?.pr ?? (s.pr ? s.pr : undefined);
432
+ g.node(shid, { kind: 'ship', repo: r }, { define: true });
433
+ Object.assign(g.nodes.get(shid), {
434
+ tasks, label: `${tasks.length > 1 ? `${tasks.length} tasks` : task}${pr ? ` #${pr}` : ''}`,
435
+ ...(pr ? { pr } : {}), ...(s.shippedAt && !prev?.date ? { date: s.shippedAt } : {}),
436
+ });
437
+ const tid = `task:${sidText}:${r}:${task}`;
438
+ g.edge(g.nodes.has(tid) ? tid : sid, shid, 'shipped-as');
439
+ g.edge(shid, g.node(`repo:${r}`, { kind: 'repo', label: r }), 'merged-into');
440
+ }
441
+ }
442
+ }
443
+ }
444
+
445
+ const nodes = [...g.nodes.values()].sort((a, b) => a.id.localeCompare(b.id));
446
+ const edges = [...g.edges.values()].filter((e) => g.nodes.has(e.source) && g.nodes.has(e.target))
447
+ .sort((a, b) => `${a.source}\0${a.target}\0${a.relation}`.localeCompare(`${b.source}\0${b.target}\0${b.relation}`));
448
+ const inputs = indexHash(parts, BRAIN_FORMAT);
449
+ const repos = Object.fromEntries(repoState);
450
+ return { brain: { format: BRAIN_FORMAT, inputs, repos, counts: countsOf(nodes, edges), nodes, edges }, inputs, repos };
451
+ }
452
+
453
+ function summaryOf(text) {
454
+ const lines = String(text).split(/\r?\n/);
455
+ const at = lines.findIndex((l) => /^##\s+Story\b/i.test(l));
456
+ const first = at < 0 ? null : lines.slice(at + 1).find((l) => l.trim());
457
+ return first ? first.trim().slice(0, 160) : null;
458
+ }
459
+
460
+ function countsOf(nodes, edges) {
461
+ const kinds = new Map();
462
+ for (const n of nodes) kinds.set(n.kind, (kinds.get(n.kind) || 0) + 1);
463
+ return { nodes: nodes.length, edges: edges.length, kinds: Object.fromEntries(kinds) };
464
+ }
465
+
466
+ // A story's tasks in one repo: from specs/<story>/tasks.md, or a light spec's marked block.
467
+ function tasksFor(target, story, parts, repo) {
468
+ if (!safeName(story)) return [];
469
+ const tin = readPlain(target, `specs/${story}/tasks.md`);
470
+ parts.push({ name: `repo:${repo}/specs/${story}/tasks.md`, input: tin });
471
+ if (tin.bytes) return tasksOf(tin.bytes.toString('utf8'));
472
+ const link = readPlain(target, `specs/${story}/link.md`);
473
+ parts.push({ name: `repo:${repo}/specs/${story}/link.md`, input: link });
474
+ if (!link.bytes || !isLightSpec(link.bytes.toString('utf8'))) return [];
475
+ const spec = readPlain(target, `specs/${story}/spec.md`);
476
+ parts.push({ name: `repo:${repo}/specs/${story}/spec.md`, input: spec });
477
+ const block = spec.bytes ? lightTasksBlock(spec.bytes.toString('utf8')) : null;
478
+ return block ? tasksOf(block) : [];
479
+ }
480
+
481
+ // A repo's code-map lines, read once per compose.
482
+ function codeMapLines(root, repo, parts, cache) {
483
+ if (!repo?.codeMap) return [];
484
+ if (cache.has(repo.name)) return cache.get(repo.name);
485
+ const rel = posix(repo.codeMap);
486
+ const input = rel.startsWith('.sdlc/code-context/') && !rel.split('/').includes('..') ? readPlain(root, rel) : { absent: true };
487
+ parts.push({ name: `code-map:${repo.name}`, input });
488
+ const lines = input.bytes ? input.bytes.toString('utf8').split('\n') : [];
489
+ cache.set(repo.name, lines);
490
+ return lines;
491
+ }
492
+
493
+ // Join a surface to the code, by name only — so every edge here is INFERRED:
494
+ // - a code symbol whose name IS the surface (`Order` → class Order);
495
+ // - on a code-map line that names the surface, each backtick handler (`postOrders(body)`) and path.
496
+ function linkSurface(g, surf, token, repo, byLabel, mapLines) {
497
+ if (byLabel) for (const id of byLabel.get(token.toLowerCase()) || []) g.edge(surf, id, 'named-as', 'INFERRED');
498
+ for (const line of mapLines) {
499
+ if (!line.includes(`\`${token}\``)) continue;
500
+ for (const x of line.matchAll(/`([^`]+)`/g)) {
501
+ const v = x[1].trim();
502
+ if (v === token) continue;
503
+ const fn = /^([A-Za-z_$][\w$]*)\(/.exec(v);
504
+ if (fn && byLabel) for (const id of byLabel.get(fn[1].toLowerCase()) || []) g.edge(surf, id, 'handled-by', 'INFERRED');
505
+ if (/^[\w.-]+(\/[\w.-]+)*\.\w+$/.test(v) && v.includes('/')) {
506
+ const fid = `file:${repo}:${posix(v)}`;
507
+ if (g.nodes.has(fid)) g.edge(surf, fid, 'mapped-to', 'INFERRED');
508
+ }
509
+ }
510
+ }
511
+ }
512
+
513
+ // ---- reading the brain back ----------------------------------------------------------------------
514
+
515
+ export function readBrain(root) {
516
+ const input = readPlain(root, posix(BRAIN_FILE));
517
+ if (input.absent) return null;
518
+ if (!input.bytes) throw err(CODE, `${BRAIN_FILE} cannot be read (${input.error})`, 'run `yad brain build`');
519
+ let b;
520
+ try { b = JSON.parse(input.bytes.toString('utf8')); } catch { throw err(CODE, `${BRAIN_FILE} does not parse`, 'run `yad brain build`'); }
521
+ if (!isPlainObject(b) || b.format !== BRAIN_FORMAT || !Array.isArray(b.nodes) || !Array.isArray(b.edges)) {
522
+ throw err(CODE, `${BRAIN_FILE} is not a brain this yadflow reads (format ${JSON.stringify(b?.format ?? null)}, expected ${BRAIN_FORMAT})`, 'run `yad brain build`');
523
+ }
524
+ return b;
525
+ }
526
+
527
+ export function writeBrain(root, brain) {
528
+ writePlain(ensureBrainDir(root), 'graph.json', `${JSON.stringify(brain)}\n`);
529
+ }
530
+
531
+ // How the brain on disk compares with the files it is built from.
532
+ // { state: 'current' | 'behind' | 'missing' | 'unreadable', why?, problem?, repos: [{ name, state, … }] }
533
+ // A repo's state: 'current', 'behind' (its HEAD moved since its code graph was built), 'unknown' (a HEAD that
534
+ // cannot be read), 'not-built', or 'skipped' (not usable here, with why).
535
+ export function brainFreshness(root, { runner = run } = {}) {
536
+ const { registry, problem } = readRegistry(root);
537
+ const now = composeBrain(root, { registry });
538
+ const { usable } = brainRepos(root, registry);
539
+ const byName = new Map(usable.map((r) => [r.name, r]));
540
+ const repos = Object.entries(now.repos).map(([name, s]) => {
541
+ const u = byName.get(name);
542
+ if (!u) return { name, state: 'skipped', why: s.why };
543
+ if (!s.code) return { name, state: 'not-built', why: s.why };
544
+ const head = headOf(u.target, runner);
545
+ const state = !head || !s.head ? 'unknown' : head !== s.head ? 'behind' : 'current';
546
+ return { name, state, builtHead: s.head, head, graphifyVersion: s.graphifyVersion };
547
+ });
548
+ const extra = problem ? { problem } : {};
549
+ let onDisk;
550
+ try { onDisk = readBrain(root); } catch (e) { return { state: 'unreadable', why: e.message, ...extra, repos }; }
551
+ if (!onDisk) return { state: 'missing', ...extra, repos };
552
+ return { state: onDisk.inputs === now.inputs ? 'current' : 'behind', ...extra, repos, counts: onDisk.counts };
553
+ }
554
+
555
+ // The nodes whose label or id holds `text`, best first, each with its neighbours: the edges out first, then
556
+ // the edges in, so a busy node shows both.
557
+ export function queryBrain(brain, text, { limit = 10, neighbours = 12 } = {}) {
558
+ const q = String(text).trim().toLowerCase();
559
+ if (!q) return [];
560
+ const score = (n) => {
561
+ const l = String(n.label).toLowerCase();
562
+ if (l === q || l.replace(/\(\)$/, '') === q) return 4;
563
+ if (l.startsWith(q)) return 3;
564
+ if (l.includes(q)) return 2;
565
+ return String(n.id).toLowerCase().includes(q) ? 1 : 0;
566
+ };
567
+ const byId = new Map(brain.nodes.map((n) => [n.id, n]));
568
+ const hits = brain.nodes.map((n) => ({ n, s: score(n) })).filter((x) => x.s > 0)
569
+ .sort((a, b) => b.s - a.s || (a.n.kind === 'code') - (b.n.kind === 'code') || a.n.id.localeCompare(b.n.id)).slice(0, limit);
570
+ const want = new Set(hits.map((h) => h.n.id));
571
+ const out = new Map();
572
+ const into = new Map();
573
+ for (const e of brain.edges) {
574
+ if (want.has(e.source)) out.set(e.source, [...(out.get(e.source) || []), e]);
575
+ if (want.has(e.target)) into.set(e.target, [...(into.get(e.target) || []), e]);
576
+ }
577
+ const brief = (n) => ({ id: n.id, kind: n.kind, label: n.label, ...(n.repo ? { repo: n.repo } : {}), ...(n.file ? { file: n.file } : {}), ...(n.missing ? { missing: true } : {}) });
578
+ return hits.map(({ n }) => {
579
+ const o = (out.get(n.id) || []).filter((e) => byId.has(e.target)).map((e) => ({ relation: e.relation, direction: 'out', confidence: e.confidence, node: brief(byId.get(e.target)) }));
580
+ const i = (into.get(n.id) || []).filter((e) => byId.has(e.source)).map((e) => ({ relation: e.relation, direction: 'in', confidence: e.confidence, node: brief(byId.get(e.source)) }));
581
+ const half = Math.ceil(neighbours / 2);
582
+ const takeOut = Math.min(o.length, Math.max(half, neighbours - i.length));
583
+ return { node: brief(n), neighbours: [...o.slice(0, takeOut), ...i.slice(0, neighbours - takeOut)], more: Math.max(0, o.length + i.length - neighbours) };
584
+ });
585
+ }
586
+
587
+ // ---- the command ---------------------------------------------------------------------------------
588
+
589
+ export const BRAIN_USAGE = 'usage: yad brain build [--repo <name>] | query <text> [--limit <n>] | file <repo>/<path> [--repo <name>] [--limit <n>] | story <story-id> [--limit <n>] | status | view [--live] [--open] [--html [<file>]] (each with --json; the search text cannot start with -)';
590
+ export const BRAIN_FLAGS = Object.freeze(['--repo', '--limit', '--json', '--dir', '--open', '--html', '--live']);
591
+
592
+ export async function runBrain(root, { action = 'status', args = [], repo = null, limit = null, json = false, open = false, html = false, live = false, unknownFlags = [], runner = run, where = whereOnPath } = {}) {
593
+ if (unknownFlags.length) return refuse(`yad brain does not take ${unknownFlags.join(', ')}`, BRAIN_USAGE, { json });
594
+ if (!fs.existsSync(productConfigPath(root))) {
595
+ return refuse('no Product here (.sdlc/product.json) — run `yad brain` from the Product, or from a repo it registers', null, { json });
596
+ }
597
+ // `--open`, `--html` and `--live` belong to `view` (E177, E178): given to another action they are refused.
598
+ const viewOnly = [[open, '--open'], [html, '--html'], [live, '--live']].filter(([given]) => given && action !== 'view').map(([, flag]) => flag);
599
+ if (viewOnly.length) return refuse(`yad brain ${forTerminal(action)} does not take ${viewOnly.join(', ')}`, BRAIN_USAGE, { json });
600
+ // E177: the viewer is its own module, loaded only when asked for (it is the one that starts a server).
601
+ if (action === 'view' && (repo !== null || limit !== null)) return refuse(`yad brain view does not take ${[repo !== null ? '--repo' : null, limit !== null ? '--limit' : null].filter(Boolean).join(', ')}`, BRAIN_USAGE, { json });
602
+ if (action === 'view') return (await import('./brain-view.mjs')).runBrainView(root, { args, html, open, live, json, runner });
603
+ // E179: `file` and `story` take exactly one name each.
604
+ if ((action === 'file' || action === 'story') && args.length !== 1) {
605
+ return refuse(args.length ? `yad brain ${action} takes one ${action === 'file' ? 'file' : 'story id'}, not ${args.length}` : `yad brain ${action} needs ${action === 'file' ? 'a file: <repo>/<path>' : 'a story id'}`, BRAIN_USAGE, { json });
606
+ }
607
+ if (action === 'story' && repo !== null) return refuse('yad brain story does not take --repo', BRAIN_USAGE, { json });
608
+ if (!['query', 'file', 'story'].includes(action) && args.length) return refuse(`unexpected argument(s): ${args.map(forTerminal).join(' ')}`, BRAIN_USAGE, { json });
609
+ if (action === 'build') return brainBuild(root, { repo, json, runner, where });
610
+ if (action === 'query') return brainQuery(root, { text: args.join(' '), limit, json, runner });
611
+ if (action === 'file') return brainFile(root, { target: args[0], repo, limit, json, runner });
612
+ if (action === 'story') return brainStory(root, { id: args[0], limit, json, runner });
613
+ if (action === 'status') return brainStatus(root, { json, runner, where });
614
+ return refuse(`unknown brain action: ${forTerminal(action)} (build, query, file, story, status, view)`, BRAIN_USAGE, { json });
615
+ }
616
+
617
+ function brainBuild(root, { repo, json, runner, where }) {
618
+ const { registry, problem } = readRegistry(root);
619
+ if (problem) return refuse(problem, 'fix .sdlc/repos.json, then run `yad brain build` again', { json });
620
+ const { usable, skipped } = brainRepos(root, registry);
621
+ if (repo && !usable.some((r) => r.name === repo)) {
622
+ return refuse(`no usable repo named ${forTerminal(repo)} here`, `the repos: ${usable.map((r) => r.name).join(', ') || '(none cloned here)'}`, { json });
623
+ }
624
+ try { ensureBrainDir(root); } catch (e) { return refuse(e.message, e.hint, { json }); }
625
+ if (!json) log(c.bold('\nyad brain build'));
626
+ const here = graphifyHere({ runner, where });
627
+ const results = [];
628
+ if (!here) {
629
+ warn('Graphify is not installed here, so the brain has no code layer: the work items only');
630
+ if (!json) hand(`install it: \`uv tool install graphifyy==${GRAPHIFY_VERSION}\` (or \`yad toolbox connect graphify\`), then run \`yad brain build\` again`);
631
+ } else if (here.startError) {
632
+ warn(here.hung
633
+ ? `Graphify at ${forTerminal(here.bin)} did not answer \`--version\` within a minute, so the brain has no code layer this time: the work items only`
634
+ : `Graphify was found at ${forTerminal(here.bin)} but cannot be started (${forTerminal(here.startError)}), so the brain has no code layer: the work items only`);
635
+ if (!json && !here.hung) hand(`install it with uv, which makes a program that starts directly: \`uv tool install graphifyy==${GRAPHIFY_VERSION}\``);
636
+ } else {
637
+ if (here.version !== GRAPHIFY_VERSION) warn(`Graphify ${forTerminal(here.version)} is installed; yadflow vetted ${GRAPHIFY_VERSION}. It is used anyway`);
638
+ for (const r of usable.filter((x) => !repo || x.name === repo)) {
639
+ if (!json) info(`${r.name}: mapping the code with Graphify (local, no LLM) …`);
640
+ let res;
641
+ try { res = buildRepoGraph(root, r, { runner, bin: here.bin }); } catch (e) { res = { ok: false, why: e.message }; }
642
+ results.push({ name: r.name, ...res });
643
+ if (res.ok) { if (!json) ok(`${r.name}: ${res.nodes} code nodes, ${res.edges} code edges`); if (res.warning) warn(`${r.name}: ${res.warning}`); }
644
+ else warn(`${r.name}: ${res.why} — its last code graph, if any, is kept`);
645
+ }
646
+ }
647
+ for (const s of skipped) if (!json) info(`${forTerminal(s.name)}: skipped — ${forTerminal(s.why)}`);
648
+ let composed;
649
+ try {
650
+ composed = composeBrain(root, { registry });
651
+ writeBrain(root, composed.brain);
652
+ } catch (e) {
653
+ return refuse(`${BRAIN_FILE} was not written (${e.code && !String(e.code).startsWith('YAD-') ? e.code : e.message})`, e.hint || 'run `yad brain build` again', { json });
654
+ }
655
+ const k = composed.brain.counts;
656
+ if (json) {
657
+ return emitJSON({ file: posix(BRAIN_FILE), graphify: here?.version ?? null, ...(here?.startError ? { graphifyError: here.startError } : {}), vetted: GRAPHIFY_VERSION, built: results, skipped, counts: k, inputs: composed.inputs });
658
+ }
659
+ ok(`wrote ${BRAIN_FILE} — ${k.nodes} nodes, ${k.edges} edges (${Object.entries(k.kinds).map(([a, b]) => `${b} ${a}`).join(', ') || 'empty'})`);
660
+ info('it stays on this machine: .sdlc/brain/ ignores itself, and is never committed');
661
+ hand('search it: `yad brain query <text>`');
662
+ return undefined;
663
+ }
664
+
665
+ // The shared start of `query`, `file` and `story`: a --limit in range, the brain read back, and a warning when a
666
+ // repo's code moved since it was built. `{ refused }` or `{ brain, n, behind }`.
667
+ function openBrain(root, { limit, fallback, json, runner }) {
668
+ const n = limit === null || limit === undefined ? fallback : Number(limit);
669
+ if (!Number.isInteger(n) || n < 1 || n > 500) return { refused: refuse(`--limit must be a whole number from 1 to 500, not ${forTerminal(limit)}`, null, { json }) };
670
+ let brain;
671
+ try { brain = readBrain(root); } catch (e) { return { refused: refuse(e.message, e.hint, { json }) }; }
672
+ if (!brain) return { refused: refuse(`no brain here yet (${BRAIN_FILE})`, 'build it: `yad brain build`', { json }) };
673
+ // A cheap check, not `status`'s full rebuild: has any repo's code moved since its graph was built?
674
+ const behind = codeBehind(root, brain, runner);
675
+ if (behind.length) warn(`the code moved in ${behind.join(', ')} since the brain was built — the answer may be out of date; run \`yad brain build\` (\`yad brain status\` checks everything)`);
676
+ return { brain, n, behind };
677
+ }
678
+
679
+ function brainQuery(root, { text, limit, json, runner }) {
680
+ if (!text.trim()) return refuse('nothing to search for', 'usage: yad brain query <text> [--limit <n>] [--json]', { json });
681
+ const opened = openBrain(root, { limit, fallback: 10, json, runner });
682
+ if (opened.refused !== undefined || !opened.brain) return opened.refused;
683
+ const { brain, n, behind } = opened;
684
+ const matches = queryBrain(brain, text, { limit: n });
685
+ if (json) return emitJSON({ query: text, codeBehind: behind, matches });
686
+ log(c.bold(`\nyad brain query ${forTerminal(text)}`));
687
+ if (!matches.length) { info('no node matches'); return undefined; }
688
+ for (const m of matches) {
689
+ log(`\n${c.bold(forTerminal(m.node.label))} ${c.dim(`${m.node.kind} · ${forTerminal(m.node.id)}`)}${m.node.missing ? c.yellow(' (declared, not in the code)') : ''}`);
690
+ for (const x of m.neighbours) {
691
+ const arrow = x.direction === 'out' ? '→' : '←';
692
+ log(` ${arrow} ${x.relation}${x.confidence === 'EXTRACTED' ? '' : c.dim(` (${x.confidence.toLowerCase()})`)} ${forTerminal(x.node.label)} ${c.dim(x.node.kind)}`);
693
+ }
694
+ if (m.more) log(c.dim(` … and ${m.more} more`));
695
+ }
696
+ return undefined;
697
+ }
698
+
699
+ // E179 — `yad brain file <repo>/<path>`: what an agent needs before it plans around a file or edits it.
700
+ function brainFile(root, { target, repo, limit, json, runner }) {
701
+ const opened = openBrain(root, { limit, fallback: 25, json, runner });
702
+ if (!opened.brain) return opened.refused;
703
+ const { brain, n, behind } = opened;
704
+ const inRepo = repo !== null && repo !== undefined ? String(repo) : null;
705
+ const path1 = String(target).trim().replace(/\\/g, '/').replace(/^(?:\.\/)+/, '');
706
+ const asked = inRepo !== null ? `${inRepo}/${path1}` : String(target).trim();
707
+ const r = fileAbout(brain, inRepo !== null ? path1 : target, { limit: n, repo: inRepo });
708
+ if (r.found === 'none') {
709
+ return refuse(`the brain holds no file ${forTerminal(asked)}`, r.suggestions.length
710
+ ? `did you mean: ${r.suggestions.map(forTerminal).join(', ')}`
711
+ : 'name it as <repo>/<path>; a file nothing declares and Graphify did not map is not in the brain (`yad brain status`)', { json });
712
+ }
713
+ if (r.found === 'many') {
714
+ return refuse(`${forTerminal(asked)} is in more than one repo: ${r.candidates.map(forTerminal).join(', ')}`, 'name it as <repo>/<path>, or add --repo <name>', { json });
715
+ }
716
+ const a = r.about;
717
+ if (json) return emitJSON({ codeBehind: behind, ...a });
718
+ log(c.bold(`\nyad brain file ${forTerminal(`${a.file.repo}/${a.file.path}`)}`) + (a.file.missing ? c.yellow(' (declared, not in the code)') : ''));
719
+ const more = (k) => (a.more[k] ? log(c.dim(` … and ${a.more[k]} more`)) : undefined);
720
+ const section = (title, rows, line, k) => {
721
+ log(`\n${c.bold(title)}`);
722
+ if (!rows.length) { log(c.dim(' none')); return; }
723
+ for (const x of rows) log(` ${line(x)}`);
724
+ more(k);
725
+ };
726
+ const conf = (x) => (x.confidence === 'EXTRACTED' ? '' : c.dim(` (${x.confidence.toLowerCase()})`));
727
+ section('Declared by', a.declaredBy, (x) => `${forTerminal(x.task.short)} ${c.dim('of')} ${forTerminal(x.story?.label ?? '?')}${x.epic ? c.dim(` · ${forTerminal(x.epic.id.slice('epic:'.length))}`) : ''} ${c.dim(forTerminal(x.task.label))}`, 'declaredBy');
728
+ section('Defines', a.defines, (x) => `${forTerminal(x.label)}${x.at ? c.dim(` ${forTerminal(x.at)}`) : ''}`, 'defines');
729
+ section('Used by', a.usedBy, (x) => `${forTerminal(x.file)} ${c.dim(x.relations.map(forTerminal).join(', '))}${conf(x)}`, 'usedBy');
730
+ section('Uses', a.uses, (x) => `${forTerminal(x.file)} ${c.dim(x.relations.map(forTerminal).join(', '))}${conf(x)}`, 'uses');
731
+ section('Shipped in', a.shippedIn, (x) => `${forTerminal(x.label)}${x.date ? c.dim(` ${forTerminal(x.date)}`) : ''}`, 'shippedIn');
732
+ section('Contract surfaces', a.surfaces, (x) => `${forTerminal(x.label)} ${c.dim(`(inferred: ${x.via.join(', ')})`)}`, 'surfaces');
733
+ if (!brain.repos?.[a.file.repo]?.code) info(`${forTerminal(a.file.repo)} has no code graph in the brain, so "Defines", "Used by" and "Uses" are empty — \`yad brain status\` says why`);
734
+ return undefined;
735
+ }
736
+
737
+ // E179 — `yad brain story <id>`: a story's tasks and every file they declare.
738
+ function brainStory(root, { id, limit, json, runner }) {
739
+ const opened = openBrain(root, { limit, fallback: 50, json, runner });
740
+ if (!opened.brain) return opened.refused;
741
+ const { brain, n, behind } = opened;
742
+ const r = storyAbout(brain, id, { limit: n });
743
+ if (r.found === 'none') {
744
+ return refuse(`the brain holds no story ${forTerminal(id)}`, r.suggestions.length ? `did you mean: ${r.suggestions.map(forTerminal).join(', ')}` : 'a story id looks like EP-<slug>-S01 (`yad brain query <text>` searches)', { json });
745
+ }
746
+ const a = r.about;
747
+ if (json) return emitJSON({ codeBehind: behind, ...a });
748
+ log(c.bold(`\nyad brain story ${forTerminal(a.story.id)}`) + (a.story.status ? c.dim(` ${forTerminal(a.story.status)}`) : ''));
749
+ if (a.story.summary) log(forTerminal(a.story.summary));
750
+ if (a.epic) info(`epic: ${forTerminal(a.epic.label)}`);
751
+ info(`builds in: ${a.repos.map(forTerminal).join(', ') || '(no repo named)'}`);
752
+ if (a.surfaces.length) info(`contract surface: ${a.surfaces.map(forTerminal).join(', ')}`);
753
+ log(`\n${c.bold('Tasks')}`);
754
+ if (!a.tasks.length) log(c.dim(' none here'));
755
+ for (const t of a.tasks) {
756
+ log(` ${forTerminal(t.label)} ${c.dim(forTerminal(t.repo ?? ''))}${t.shipped.length ? c.green(` shipped ${t.shipped.map((x) => forTerminal(x.label)).join(', ')}`) : ''}`);
757
+ for (const f of t.files) log(` ${forTerminal(f.path)}${f.missing ? c.yellow(' (not in the code yet)') : ''}`);
758
+ }
759
+ if (a.more.tasks) log(c.dim(` … and ${a.more.tasks} more tasks`));
760
+ // Ships recorded on the story itself (its repo is not cloned here, so its tasks have no node): the work is
761
+ // done even when no task shows it (review 1).
762
+ if (a.shipped.length) ok(`shipped: ${a.shipped.map((x) => forTerminal(x.label)).join(', ')}`);
763
+ for (const r2 of a.reposWithoutTasks) info(`${forTerminal(r2)}: no tasks in the brain — the repo is not cloned here, or its tasks.md is not written yet`);
764
+ return undefined;
765
+ }
766
+
767
+ // The repos whose HEAD moved since the brain recorded it.
768
+ export function codeBehind(root, brain, runner = run) {
769
+ const { registry } = readRegistry(root);
770
+ const { usable } = brainRepos(root, registry);
771
+ const out = [];
772
+ for (const r of usable) {
773
+ const built = isPlainObject(brain.repos) && Object.hasOwn(brain.repos, r.name) ? brain.repos[r.name]?.head : null;
774
+ if (!built) continue;
775
+ const head = headOf(r.target, runner);
776
+ if (head && head !== built) out.push(r.name);
777
+ }
778
+ return out;
779
+ }
780
+
781
+ function brainStatus(root, { json, runner, where }) {
782
+ const here = graphifyHere({ runner, where });
783
+ const f = brainFreshness(root, { runner });
784
+ // A brain that cannot be read is a failure, said with exit 1; behind or missing is a state, exit 0.
785
+ if (f.state === 'unreadable') process.exitCode = 1;
786
+ if (json) return emitJSON({ ...(f.state === 'unreadable' ? { ok: false, error: f.why, code: CODE, hint: 'run `yad brain build`' } : {}), file: posix(BRAIN_FILE), ...f, graphify: here?.version ?? null, ...(here?.startError ? { graphifyError: here.startError } : {}), vetted: GRAPHIFY_VERSION });
787
+ log(c.bold('\nyad brain status'));
788
+ if (f.problem) warn(f.problem);
789
+ if (f.state === 'current') ok(`${BRAIN_FILE} is current — ${f.counts?.nodes ?? 0} nodes, ${f.counts?.edges ?? 0} edges`);
790
+ else if (f.state === 'missing') warn('no brain here yet — build it: `yad brain build`');
791
+ else if (f.state === 'unreadable') fail(f.why);
792
+ else warn(`${BRAIN_FILE} is behind the files it is built from — run \`yad brain build\``);
793
+ for (const r of f.repos) {
794
+ const short = (s) => (s ? s.slice(0, 7) : '?');
795
+ const line = `${forTerminal(r.name)}: ${
796
+ r.state === 'behind' ? `code graph built at ${short(r.builtHead)}, the repo is at ${short(r.head)} — run \`yad brain build\``
797
+ : r.state === 'current' ? `code graph current (${short(r.builtHead)})`
798
+ : r.state === 'unknown' ? 'code graph built, but the repo\'s HEAD cannot be read — run `yad brain build`'
799
+ : `${r.state} — ${forTerminal(r.why ?? '')}`}`;
800
+ if (r.state === 'current') ok(line); else if (r.state === 'behind' || r.state === 'unknown') warn(line); else info(line);
801
+ }
802
+ if (!here) info(`Graphify is not installed here (vetted: ${GRAPHIFY_VERSION}); the brain has the work items only`);
803
+ else if (here.startError) {
804
+ warn(here.hung
805
+ ? `Graphify at ${forTerminal(here.bin)} did not answer \`--version\` within a minute`
806
+ : `Graphify was found at ${forTerminal(here.bin)} but cannot be started (${forTerminal(here.startError)})`);
807
+ }
808
+ else if (here.version !== GRAPHIFY_VERSION) warn(`Graphify ${forTerminal(here.version)} is installed; yadflow vetted ${GRAPHIFY_VERSION}`);
809
+ return undefined;
810
+ }