geneseed 5.2.0 → 5.3.1

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 (190) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +4 -4
  3. package/SHIPPED.md +1 -1
  4. package/adapters/bob/README.md +31 -18
  5. package/adapters/claude-code/README.md +27 -22
  6. package/adapters/openclaude/README.md +18 -8
  7. package/adapters/opencode/HOW-OPENCODE-LOADS.md +8 -3
  8. package/adapters/opencode/plugins/geneseed-activity.js +20 -21
  9. package/adapters/opencode/plugins/geneseed-context.js +224 -71
  10. package/adapters/opencode/plugins/geneseed-guard.js +420 -203
  11. package/adapters/opencode/plugins/geneseed-workflow.js +3 -2
  12. package/adapters/opencode/workflows/_runtime.js +3 -2
  13. package/bin/geneseed-cli.mjs +61 -16
  14. package/bin/geneseed-hook.mjs +94 -12
  15. package/docs/concepts/enforcement-table.md +1 -1
  16. package/docs/concepts/exclusions.md +2 -2
  17. package/docs/concepts/factories.md +40 -6
  18. package/docs/concepts/footprint.md +11 -1
  19. package/docs/concepts/foreman-mode.md +2 -2
  20. package/docs/concepts/hook-gates.md +3 -3
  21. package/docs/concepts/host-matrix.md +22 -4
  22. package/docs/concepts/loop-gates.md +1 -1
  23. package/docs/concepts/loops.md +2 -2
  24. package/docs/concepts/shared-tier.md +1 -1
  25. package/docs/design-history.md +148 -0
  26. package/docs/extending.md +97 -163
  27. package/docs/guides/install-bob.md +2 -2
  28. package/docs/guides/install-openclaude.md +1 -1
  29. package/docs/guides/run-a-factory.md +15 -2
  30. package/docs/guides/upgrade.md +2 -2
  31. package/docs/guides/verify.md +12 -0
  32. package/docs/reference/environment.md +1 -0
  33. package/docs/reference/factory-actions.md +6 -5
  34. package/docs/reference/troubleshoot-doctor.md +1 -1
  35. package/docs/reference/troubleshoot-update.md +1 -1
  36. package/docs/token-footprint.md +66 -2
  37. package/docs/understand/design-choices-hosts.md +1 -1
  38. package/docs/understand/design-choices-shape.md +1 -0
  39. package/docs/understand/enforced-vs-asked.md +1 -1
  40. package/docs/understand/machine-bob.md +1 -1
  41. package/docs/web-ui.md +21 -3
  42. package/harness.config.json +1 -1
  43. package/js/README.md +7 -5
  44. package/js/build/args.mjs +4 -4
  45. package/js/build/driver.mjs +1 -1
  46. package/js/build/emit-claude.mjs +1 -1
  47. package/js/build/generate.mjs +5 -14
  48. package/js/build/render.mjs +44 -24
  49. package/js/cli-table.json +135 -59
  50. package/js/factory/cli.mjs +24 -5
  51. package/js/factory/graph.mjs +13 -9
  52. package/js/factory/metrics.mjs +93 -0
  53. package/js/factory/registry.mjs +37 -12
  54. package/js/factory/state.mjs +25 -6
  55. package/js/hosts/done-checks.mjs +6 -0
  56. package/js/hosts/geneseed-dir.mjs +3 -2
  57. package/js/hosts/gitref.mjs +5 -3
  58. package/js/hosts/hook-tap.mjs +104 -0
  59. package/js/hosts/hooks-context.mjs +30 -3
  60. package/js/hosts/hooks-learn.mjs +47 -16
  61. package/js/hosts/hooks-prims.mjs +52 -3
  62. package/js/hosts/hooks.mjs +69 -42
  63. package/js/hosts/hosts.mjs +80 -12
  64. package/js/hosts/installs.mjs +7 -0
  65. package/js/hosts/loss.mjs +6 -1
  66. package/js/hosts/native.mjs +14 -5
  67. package/js/hosts/owned.mjs +7 -6
  68. package/js/hosts/ownership-gate.mjs +14 -1
  69. package/js/hosts/settings.mjs +245 -103
  70. package/js/hosts/shim.mjs +4 -4
  71. package/js/hosts/usage.mjs +9 -3
  72. package/js/inspect/checks-probe.mjs +66 -5
  73. package/js/inspect/checks-repo.mjs +196 -2
  74. package/js/inspect/cost.mjs +34 -2
  75. package/js/inspect/diff.mjs +16 -1
  76. package/js/inspect/doctor.mjs +13 -4
  77. package/js/inspect/excludes.mjs +18 -6
  78. package/js/inspect/status.mjs +35 -7
  79. package/js/inspect/validate.mjs +44 -21
  80. package/js/lib/machine-dir.mjs +1 -1
  81. package/js/lib/node-floor.mjs +46 -6
  82. package/js/maintain/uninstall.mjs +70 -17
  83. package/js/maintain/update.mjs +31 -7
  84. package/js/ui/cli.mjs +34 -4
  85. package/js/ui/menu.mjs +1 -1
  86. package/js/ui/tui.mjs +11 -14
  87. package/js/web/actions.mjs +3 -9
  88. package/js/web/api.mjs +28 -10
  89. package/js/web/daemon.mjs +0 -1
  90. package/js/web/server.mjs +1 -0
  91. package/js/web/state.mjs +37 -16
  92. package/package.json +1 -1
  93. package/src/AGENT.md.tmpl +23 -17
  94. package/src/agents/_template.md +1 -1
  95. package/src/agents/advocate.md +1 -1
  96. package/src/agents/developer.md +12 -3
  97. package/src/agents/empiricist.md +1 -1
  98. package/src/agents/framer.md +1 -1
  99. package/src/agents/historian.md +1 -1
  100. package/src/agents/operator.md +1 -1
  101. package/src/agents/pragmatist.md +1 -1
  102. package/src/agents/researcher.md +1 -1
  103. package/src/agents/skeptic.md +1 -1
  104. package/src/agents/steward.md +1 -1
  105. package/src/agents/user-advocate.md +1 -1
  106. package/src/agents/visionary.md +1 -1
  107. package/src/bricks/intake.md +10 -3
  108. package/src/bricks/retro.md +13 -3
  109. package/src/doctrines/comms.md +1 -1
  110. package/src/doctrines/ops.md +1 -1
  111. package/src/doctrines/process.md +7 -5
  112. package/src/factories/analysis-to-build.json +1 -0
  113. package/src/factories/bug-report-to-fix.json +1 -0
  114. package/src/factories/issue-to-pr.json +1 -0
  115. package/src/laws/universal.md +2 -2
  116. package/src/modes/foreman.md +8 -14
  117. package/src/skills/commit.md +7 -2
  118. package/src/skills/debug.md +1 -1
  119. package/src/skills/diagram-design/SKILL.md +1 -1
  120. package/src/skills/diagram-design/VENDOR.md +3 -1
  121. package/src/skills/factory-forge.md +5 -3
  122. package/src/skills/factory.md +22 -1
  123. package/src/skills/geneseed.md +1 -1
  124. package/src/skills/handoff.md +1 -1
  125. package/src/skills/parallel-agents.md +1 -1
  126. package/src/skills/pipeline.md +6 -6
  127. package/src/skills/plan.md +7 -3
  128. package/src/skills/spring-testing.md +1 -1
  129. package/themes/biker.json +78 -78
  130. package/themes/commentator.json +81 -81
  131. package/themes/cyberpunk.json +79 -79
  132. package/themes/gamer.json +77 -77
  133. package/themes/imperial.json +82 -82
  134. package/themes/joker.json +79 -79
  135. package/themes/marvin.json +82 -82
  136. package/themes/mean.json +82 -82
  137. package/themes/military.json +78 -78
  138. package/themes/neutral.json +78 -78
  139. package/themes/pirate.json +79 -79
  140. package/themes/sports.json +79 -79
  141. package/themes/verstappen.json +78 -78
  142. package/themes/wizard.json +79 -79
  143. package/web/dist/assets/ActiveLoops-BJJN3P-V.js +1 -0
  144. package/web/dist/assets/Activity-WQ3ykgxU.js +1 -0
  145. package/web/dist/assets/ActivityDetail-7rt04SkS.js +1 -0
  146. package/web/dist/assets/{Bonsai-DSwUbavu.js → Bonsai-BBl4XXqs.js} +1 -1
  147. package/web/dist/assets/{CopyButton-BzRQz7k2.js → CopyButton-Beven8yn.js} +1 -1
  148. package/web/dist/assets/Dashboard-BgLArtgu.js +2 -0
  149. package/web/dist/assets/Docs-B5aHp86J.js +5 -0
  150. package/web/dist/assets/Factories-BjqzXAw8.js +1 -0
  151. package/web/dist/assets/GreenhouseView-Bce212qd.js +1 -0
  152. package/web/dist/assets/Installs-B1OsrHXF.js +3 -0
  153. package/web/dist/assets/JournalView-CV4omyww.js +1 -0
  154. package/web/dist/assets/Kits-CW1e7xNa.js +1 -0
  155. package/web/dist/assets/Laws-1Ckf1lbs.js +4 -0
  156. package/web/dist/assets/LibRows-Dag1s0ZX.js +1 -0
  157. package/web/dist/assets/Library-B3FuFLel.js +3 -0
  158. package/web/dist/assets/Loops-CwqgnLNw.js +2 -0
  159. package/web/dist/assets/Markdown-CxkA7940.js +71 -0
  160. package/web/dist/assets/OperatorHudView-JmYY1pBR.js +1 -0
  161. package/web/dist/assets/Personal-DKLgLa7Z.js +2 -0
  162. package/web/dist/assets/Settings-BwErnh-R.js +1 -0
  163. package/web/dist/assets/Tabs-8zsyEPSK.js +1 -0
  164. package/web/dist/assets/index-CRWqKxfY.css +1 -0
  165. package/web/dist/assets/index-Ce6qF2nG.js +6 -0
  166. package/web/dist/assets/usePoll-D5c_qIFZ.js +1 -0
  167. package/web/dist/index.html +2 -2
  168. package/adapters/claude-code/settings.json +0 -52
  169. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +0 -1
  170. package/web/dist/assets/Activity-DlQ30znB.js +0 -1
  171. package/web/dist/assets/ActivityDetail-CG0mn5fW.js +0 -1
  172. package/web/dist/assets/Dashboard-Ce3UOsxJ.js +0 -2
  173. package/web/dist/assets/Docs-CisVnYqv.js +0 -5
  174. package/web/dist/assets/Factories-Dq5oW4CU.js +0 -1
  175. package/web/dist/assets/GreenhouseView-y9WAfcc_.js +0 -1
  176. package/web/dist/assets/Installs-m4GElwFW.js +0 -3
  177. package/web/dist/assets/JournalView-DeBLRNGc.js +0 -1
  178. package/web/dist/assets/Kits-DJYVAnyE.js +0 -1
  179. package/web/dist/assets/Laws-CNpc_8ZV.js +0 -4
  180. package/web/dist/assets/LibRows-RO5bvXth.js +0 -1
  181. package/web/dist/assets/Library-Dg0ScciC.js +0 -3
  182. package/web/dist/assets/Loops-CjEdo-NG.js +0 -2
  183. package/web/dist/assets/Markdown-0ORz7tAc.js +0 -69
  184. package/web/dist/assets/OperatorHudView-2ujVMjq1.js +0 -1
  185. package/web/dist/assets/Personal-D0yS7ahT.js +0 -2
  186. package/web/dist/assets/Settings-DEN0U8QI.js +0 -1
  187. package/web/dist/assets/Tabs-But5R6_r.js +0 -1
  188. package/web/dist/assets/index-Ck42AbRX.js +0 -6
  189. package/web/dist/assets/index-PG_ukkh6.css +0 -1
  190. package/web/dist/assets/usePoll-o8ul-Sog.js +0 -1
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The numbers of a factory run, computed from `FACTORY.md`'s state and nothing else: no clock, no
3
+ * file, no catalogue. `geneseed factory report` prints them, and the console's board reads them
4
+ * through `js/factory/registry.mjs`, so the `retro` brick, the Rite and the console show the same
5
+ * figures and no model does date arithmetic (D4, D5).
6
+ *
7
+ * WORK TIME AND WAITING TIME. A history entry's duration is its `at` minus the `at` of the entry
8
+ * before it (the run's `started` for the first). On a `record` entry that is the stage's work
9
+ * time. On a `decide` entry it is the time the run waited at a human gate: the entry before it is
10
+ * always the gated record, so the gap is the user's, never the stage's.
11
+ *
12
+ * UNKNOWN IS `null`, NEVER ZERO. An entry with no `at`, or whose predecessor has none (a
13
+ * FACTORY.md written before the engine stamped times), has a duration of `null`, and so has every
14
+ * sum that holds it: a total that silently left a stage out would read as a fast run. A time that
15
+ * does not parse, or one earlier than its predecessor, is unknown too.
16
+ *
17
+ * TOKENS ARE THE SUM OF WHAT WAS REPORTED. `record --tokens` is passed only where the host gave a
18
+ * count, so a stage's `tokens` adds the counts its entries carry and is `null` when none does.
19
+ * A loop stage carries none: nothing sums a loop's agents by hand (D3).
20
+ *
21
+ * A REWORK IS AN OUTCOME THAT SPENT A CYCLE: the stage reported an outcome whose edge routes back
22
+ * into a declared cycle (`spentCycle`, the rule the engine counts laps with). A held outcome
23
+ * spends its cycle only when the user answers `ok`; `amend` re-runs the stage and `no` stops, and
24
+ * neither is a rework. The fork test needs each stage's outcomes, which live in the catalogue;
25
+ * here they are read off the factory's own edges, one edge per outcome (rule 3 of `checkFactory`),
26
+ * so this module needs no catalogue and the daemon can call it on any registered run.
27
+ *
28
+ * THE OPEN WAIT. A wait is counted on the `decide` that ends it, so a run still held at a gate has
29
+ * waited nothing yet by that count. `now` (an ISO time, optional) gives `openWaitMs`: `now` minus
30
+ * the `at` of the gated record, while the run is `awaiting`. It is null without `now`, on a run
31
+ * that is not awaiting, and when that record has no `at`. The caller reads the clock (`factory
32
+ * report` its own, the console the time of its poll); this module stays pure.
33
+ *
34
+ * NEVER THROWS on a state that parsed: the console calls it on a FACTORY.md nobody validated.
35
+ */
36
+ import { edgeFor, laneTargets, spentCycle } from './graph.mjs';
37
+
38
+ const list = (v) => (Array.isArray(v) ? v : []);
39
+ const elapsed = (from, to) => {
40
+ const a = Date.parse(from ?? ''); const b = Date.parse(to ?? '');
41
+ return Number.isFinite(a) && Number.isFinite(b) && b >= a ? b - a : null;
42
+ };
43
+ const sum = (xs) => (xs.includes(null) ? null : xs.reduce((a, b) => a + b, 0));
44
+ const tokensOf = (hs) => {
45
+ const known = hs.map((h) => h.tokens).filter((t) => Number.isSafeInteger(t) && t >= 1);
46
+ return known.length ? known.reduce((a, b) => a + b, 0) : null;
47
+ };
48
+
49
+ /**
50
+ * `{ started, stages, workMs, waitMs, openWaitMs, tokens, transitions, entries }`. `stages` lists each stage
51
+ * the run recorded, in the order it first ran: `{ stage, runs, reworks, workMs, tokens }`.
52
+ * `entries` is parallel to `state.history`: `{ ms, wait, rework }`, `wait` true on a `decide`
53
+ * entry. `transitions` is the run-wide count the engine keeps.
54
+ */
55
+ export function runMetrics(state, { now = null } = {}) {
56
+ const factory = state?.factory;
57
+ const history = list(state?.history).map((h) => (h !== null && typeof h === 'object' ? h : {}));
58
+ const edges = list(factory?.edges);
59
+ const outcomes = new Map(list(factory?.stages).map((s) => [s, { outcomes: edges.filter((e) => e?.from === s).map((e) => e.on) }]));
60
+ const lanes = laneTargets(factory, outcomes);
61
+ const spends = (h) => {
62
+ const edge = edgeFor(factory, h.stage, h.outcome);
63
+ return !!edge && spentCycle(list(factory?.cycles), h.stage, edge.to, lanes) !== null;
64
+ };
65
+
66
+ let prev = state?.started ?? null;
67
+ const entries = history.map((h, i) => {
68
+ const ms = elapsed(prev, h.at);
69
+ prev = h.at ?? null;
70
+ if (h.verdict !== undefined) return { ms, wait: true, rework: false };
71
+ const answer = history[i + 1]?.verdict; // set when this record held a gate that was answered
72
+ const held = answer !== undefined || (i === history.length - 1 && state?.awaiting != null);
73
+ return { ms, wait: false, rework: (held ? answer === 'ok' : true) && spends(h) };
74
+ });
75
+
76
+ const byStage = new Map();
77
+ history.forEach((h, i) => {
78
+ if (entries[i].wait) return;
79
+ const row = byStage.get(h.stage) ?? { stage: h.stage, runs: 0, reworks: 0, ms: [], hs: [] };
80
+ row.runs += 1; row.reworks += entries[i].rework ? 1 : 0; row.ms.push(entries[i].ms); row.hs.push(h);
81
+ byStage.set(h.stage, row);
82
+ });
83
+ return {
84
+ started: typeof state?.started === 'string' ? state.started : null,
85
+ stages: [...byStage.values()].map(({ stage, runs, reworks, ms, hs }) => ({ stage, runs, reworks, workMs: sum(ms), tokens: tokensOf(hs) })),
86
+ workMs: sum(entries.filter((e) => !e.wait).map((e) => e.ms)),
87
+ waitMs: sum(entries.filter((e) => e.wait).map((e) => e.ms)),
88
+ openWaitMs: state?.status === 'awaiting' && now ? elapsed(history.at(-1)?.at, now) : null,
89
+ tokens: tokensOf(history),
90
+ transitions: Number.isInteger(state?.runTransitions) ? state.runTransitions : null,
91
+ entries,
92
+ };
93
+ }
@@ -6,8 +6,16 @@
6
6
  *
7
7
  * EVERY CONVENTION IS THE LOOP REGISTRY'S, and so is the code (`js/loop/registry.mjs`: `loadRows`,
8
8
  * `saveRows`, `sweepRows`): atomic tmp + rename, every function swallows its own errors, rows keyed
9
- * by their normalised root, no `lastSeen`, a save only when the kept set changed, and a finished
10
- * run dropped 7 days after it was first seen without its FACTORY.md.
9
+ * by their normalised root, no `lastSeen`, and a finished run dropped 7 days after it was first
10
+ * seen without its FACTORY.md.
11
+ *
12
+ * THE CONSOLE'S POLL NEVER WRITES (spec 2026-11-11 D7). The board polls every 5 s; a sweep there
13
+ * would stamp `finishedAt`, drop rows, and race `recordFactory` on the one `factories.json.tmp`
14
+ * during a `factory init`. So `listFactories` is read-only, as `runningLoops` is beside
15
+ * `activeLoops` (but with no sweeping twin: nothing else needs one), and the sweep (stamp,
16
+ * 7-day prune, drop of a vanished root) runs in
17
+ * `recordFactory`, which writes the file anyway. A finished run is first stamped by the next
18
+ * `factory init` on the machine, so it is pruned 7 days after that, not after it closed.
11
19
  *
12
20
  * THE ROOT IS THE JOIN KEY. A child loop runs in the factory's own worktree, so its `loops.json`
13
21
  * row has the same root, and carries `factory: <slug>` (`loop init --factory`). A reader groups a
@@ -15,9 +23,12 @@
15
23
  */
16
24
  import path from 'node:path';
17
25
 
26
+ import { readText, isDir, isFile } from '../lib/fs.mjs';
27
+
18
28
  import { userLoopsDir } from '../loop/catalog.mjs';
19
29
  import { loadRows, saveRows, sweepRows, normalize, sameRoot } from '../loop/registry.mjs';
20
30
  import { FACTORY_FILE, parseFactoryFile } from './state.mjs';
31
+ import { runMetrics } from './metrics.mjs';
21
32
 
22
33
  export function factoryRegistryPath() {
23
34
  return path.join(userLoopsDir(), 'factories.json');
@@ -34,7 +45,7 @@ const save = (rows) => saveRows(factoryRegistryPath(), 'factories', rows);
34
45
  export function recordFactory({ root, branch, factory, title, now = new Date() }) {
35
46
  try {
36
47
  const key = normalize(root);
37
- const rows = load();
48
+ const rows = sweep(load(), now).kept; // the registry's one sweep: see the docblock
38
49
  const idx = rows.findIndex((r) => sameRoot(r.root, key));
39
50
  if (idx >= 0) rows[idx] = { ...rows[idx], root: key, branch, factory, title };
40
51
  else rows.push({ root: key, branch, factory, title, started: now.toISOString() });
@@ -46,7 +57,7 @@ export function recordFactory({ root, branch, factory, title, now = new Date() }
46
57
 
47
58
  const identity = (e) => ({ root: e.root, branch: e.branch, factory: e.factory, title: e.title, started: e.started });
48
59
 
49
- function runningRow(entry, state) {
60
+ function runningRow(entry, state, now = null) {
50
61
  return {
51
62
  ...identity(entry), status: state.status, stage: state.stage, awaiting: state.awaiting,
52
63
  reason: state.reason, transitions: state.transitions, counters: state.counters,
@@ -54,18 +65,32 @@ function runningRow(entry, state) {
54
65
  // The graph the run was started from, as the loop row carries its `graph`: the console draws
55
66
  // it, and a run started in another project names a factory this install may not have.
56
67
  graph: state.factory,
68
+ // D7: the board's numbers, from the one function `factory report` prints (it never throws on
69
+ // a state that parsed, and nothing here validated this one).
70
+ metrics: runMetrics(state, { now }),
57
71
  };
58
72
  }
59
73
 
74
+ const sweep = (rows, now) => sweepRows(rows, {
75
+ stateFile: FACTORY_FILE, parse: parseFactoryFile, project: runningRow, identity, now,
76
+ });
77
+
60
78
  /**
61
- * The rows the console renders, read fresh off each registered worktree's FACTORY.md: a running
62
- * row, `unreadable` (kept, R4), or `finished` (FACTORY.md gone; pruned 7 days later). A root that
63
- * no longer exists is dropped. Saves only when the kept set changed.
79
+ * The rows the console renders, READ-ONLY: never a save, a stamp or a prune. A running row read
80
+ * fresh off each registered worktree's FACTORY.md (its metrics' open wait measured to `now`, the
81
+ * time of the poll), `unreadable` when it does not parse, and
82
+ * `finished` when it is gone. A row whose root no longer exists is skipped: the sweep in
83
+ * `recordFactory` drops it, and a card for a deleted worktree would open on nothing.
64
84
  */
65
- export function activeFactories({ now = new Date() } = {}) {
66
- const { kept, rows, changed } = sweepRows(load(), {
67
- stateFile: FACTORY_FILE, parse: parseFactoryFile, project: runningRow, identity, now,
68
- });
69
- if (changed) save(kept);
85
+ export function listFactories({ now = new Date().toISOString() } = {}) {
86
+ const rows = [];
87
+ for (const entry of load()) {
88
+ if (!isDir(entry.root)) continue;
89
+ const file = path.join(entry.root, FACTORY_FILE);
90
+ if (!isFile(file)) { rows.push({ ...identity(entry), status: 'finished' }); continue; }
91
+ let state;
92
+ try { state = parseFactoryFile(readText(file)); } catch { rows.push({ ...identity(entry), status: 'unreadable' }); continue; }
93
+ rows.push(runningRow(entry, state, now));
94
+ }
70
95
  return rows;
71
96
  }
@@ -80,6 +80,13 @@
80
80
  * budget or a higher ceiling. And it is capped at `FACTORY_MAX_TASKS` (20), so the
81
81
  * ceiling is at most 1200 transitions: past twenty tasks a requirement is a project, to be split
82
82
  * into several factory runs a human can review, not one run nobody reads to the end.
83
+ *
84
+ * TIME AND TOKENS ARE RECORDED, NEVER READ BACK (D2, D3). `init` stamps `started`, and `record`
85
+ * and `decide` stamp `at` on the history entry they push: the ISO time the CLI passes as `now`,
86
+ * as `next` does for a launch. `record` also stores `tokens`, the count the host reported for the
87
+ * agent that ran the stage. No transition reads either one, so both are optional in a state: a
88
+ * FACTORY.md written before them still validates and still runs. `runMetrics`
89
+ * (`js/factory/metrics.mjs`) is their one reader.
83
90
  */
84
91
  import { writeText } from '../lib/fs.mjs';
85
92
  import { renameWithRetry, filterPorcelain } from '../loop/state.mjs';
@@ -117,6 +124,7 @@ export function parseFactoryFile(text) {
117
124
  }
118
125
 
119
126
  const count = (v) => Number.isInteger(v) && v >= 0;
127
+ const tokenCount = (v) => Number.isSafeInteger(v) && v >= 1;
120
128
  const plainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
121
129
 
122
130
  /**
@@ -150,6 +158,12 @@ export function validateFactoryState(state, catalog) {
150
158
  }
151
159
  if (!STATUSES.includes(state.status)) bad(`status must be one of ${STATUSES.join(', ')}`);
152
160
  if (!Array.isArray(state.history)) bad('history must be a list');
161
+ // D2, D3: optional, so a state written before them validates; a wrong shape would feed `runMetrics` nonsense
162
+ if (state.started != null && typeof state.started !== 'string') bad('started must be a time');
163
+ for (const h of state.history) {
164
+ if (h?.at != null && typeof h.at !== 'string') bad('a history entry\'s at must be a time');
165
+ if (h?.tokens !== undefined && !tokenCount(h.tokens)) bad('a history entry\'s tokens must be a positive integer');
166
+ }
153
167
  if (!plainObject(state.gateAmends) || !Object.values(state.gateAmends).every((n) => count(n) && n <= GATE_MAX_AMENDS)) {
154
168
  bad(`gateAmends must map each gate to an integer from 0 to ${GATE_MAX_AMENDS}`);
155
169
  }
@@ -236,13 +250,14 @@ export function countSpecTasks(text) {
236
250
  return count;
237
251
  }
238
252
 
239
- export function initFactory({ title, requirement, factory, input = null }) {
253
+ export function initFactory({ title, requirement, factory, input = null, now = null }) {
240
254
  return {
241
255
  v: 1, title, requirement, input, factory, stage: factory.start,
242
256
  status: 'running', awaiting: null, reason: null,
243
257
  counters: {}, transitions: 0, runTransitions: 0, runCeiling: FACTORY_MAX_TRANSITIONS, taskHigh: 0, taskCount: null,
244
258
  lane: null, tasks: null, carry: null, launched: null,
245
259
  history: [], gateAmends: {},
260
+ ...(now ? { started: now } : {}),
246
261
  };
247
262
  }
248
263
 
@@ -361,13 +376,16 @@ export function unquotePath(p) {
361
376
  * with `taskCount` (a stage that wrote a spec), `carry` (the reason the next stage — above all a
362
377
  * re-entered loop — must hear). `loopTemplate` is the graph name in the LOOP.md the CLI read,
363
378
  * `head` the HEAD commit now, `loopInitAt` the registry row's last `loop init` time for this
364
- * worktree, or null (R2). Every refusal throws before the state changes.
379
+ * worktree, or null (R2). `now` is the ISO time stamped on the history entry as `at`, and `tokens`
380
+ * the count the host reported for the stage's agent (D2, D3); both are left out when null.
381
+ * Every refusal throws before the state changes.
365
382
  */
366
383
  export function recordStage(state, { bricks }, outcome, {
367
384
  porcelain = null, specPath = null, taskCount = null, carry = null, loopStatus = null,
368
- loopTemplate = null, head = null, loopInitAt = null,
385
+ loopTemplate = null, head = null, loopInitAt = null, now = null, tokens = null,
369
386
  } = {}) {
370
387
  assertRunning(state);
388
+ if (tokens !== null && !tokenCount(tokens)) throw new Error('--tokens must be a positive integer: the count the host reported, never an estimate');
371
389
  assertNoLoop(loopStatus);
372
390
  const from = state.stage;
373
391
  const outcomes = stageOutcomes(from, bricks);
@@ -440,6 +458,7 @@ export function recordStage(state, { bricks }, outcome, {
440
458
  state.carry = carry || null;
441
459
  state.history.push({
442
460
  stage: from, outcome, task: taskNo(state), ...(carry ? { carry } : {}),
461
+ ...(tokens !== null ? { tokens } : {}), ...(now ? { at: now } : {}),
443
462
  });
444
463
  const brick = isLoop ? null : bricks.get(from);
445
464
  if (brick?.gate === 'human' && (!brick.gateOn || brick.gateOn.includes(outcome))) {
@@ -487,16 +506,16 @@ function transition(state, from, edge, bricks) {
487
506
  /**
488
507
  * The answer to a held `gate: human` stage (D14: the loop engine's gate and verdicts, reused).
489
508
  * `ok` follows the held edge; `no` stops; `amend` re-runs the stage with the note as its `carry`,
490
- * `GATE_MAX_AMENDS` times per stage per task.
509
+ * `GATE_MAX_AMENDS` times per stage per task. `now` is stamped on the history entry as `at` (D2).
491
510
  */
492
- export function decideFactory(state, { bricks }, verdict, note = '') {
511
+ export function decideFactory(state, { bricks }, verdict, note = '', { now = null } = {}) {
493
512
  if (state.status !== 'awaiting') throw new Error('nothing is awaiting a decision');
494
513
  if (!['ok', 'no', 'amend'].includes(verdict)) throw new Error(`verdict must be ok, no or amend, not ${JSON.stringify(verdict)}`);
495
514
  const { stage, outcome } = state.awaiting;
496
515
  const edge = edgeFor(state.factory, stage, outcome) ?? { from: stage, on: outcome, to: '$stop' };
497
516
  if (verdict === 'ok') assertLane(state, edge);
498
517
  state.awaiting = null; state.status = 'running';
499
- state.history.push({ stage, verdict, task: taskNo(state), ...(note ? { note } : {}) });
518
+ state.history.push({ stage, verdict, task: taskNo(state), ...(note ? { note } : {}), ...(now ? { at: now } : {}) });
500
519
  if (verdict === 'no') return stop(state, `gate rejected at ${stage}${note ? `: ${note}` : ''}`);
501
520
  if (verdict === 'amend') {
502
521
  const key = `${stage}@${taskNo(state)}`;
@@ -23,6 +23,10 @@ export function readDoneChecks(root) {
23
23
  }
24
24
  }
25
25
 
26
+ // ---- done-check tables twin: BEGIN — adapters/opencode/plugins/geneseed-context.js carries
27
+ // everything down to the END marker verbatim, with `export ` dropped (node tests/twins.mjs --write
28
+ // keeps it). Its `inferDoneChecks` is the async reading of the one below, kept by hand.
29
+
26
30
  // The package manager a lockfile names; first hit wins, npm without one. Exported for the gate that
27
31
  // holds the factory `checks` brick's restatement of these rules to this list (factory_graph test).
28
32
  export const PM_LOCKS = [['bun.lockb', 'bun'], ['bun.lock', 'bun'], ['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn']];
@@ -58,6 +62,8 @@ const MANIFEST_CHECKS = [
58
62
  ['Cargo.toml', { label: 'cargo test', forms: ['cargo test'], refuse: /(?:^|\s)--no-run(?=\s|$)/ }],
59
63
  ['go.mod', { label: 'go test', forms: ['go test'] }],
60
64
  ];
65
+
66
+ // ---- done-check tables twin: END
61
67
  /**
62
68
  * Every root manifest the checks are inferred from — what an emit seeds into the protected list.
63
69
  * @type {string[]}
@@ -24,8 +24,9 @@ import { gitRootOf } from './gitref.mjs';
24
24
  /**
25
25
  * The `.geneseed/.gitignore` every writer creates: personal by default, the team paths allowed
26
26
  * back. Anchored `/*`: a bare `*` matches at every depth and would hide `bricks/x.md` even under
27
- * `!bricks/`. The same string lives in `adapters/opencode/plugins/geneseed-workflow.js`,
28
- * `adapters/opencode/workflows/_runtime.js` and `src/skills/_checkpoints.md`; tests pin them.
27
+ * `!bricks/`. `adapters/opencode/plugins/geneseed-workflow.js` and
28
+ * `adapters/opencode/workflows/_runtime.js` carry this line (`node tests/twins.mjs --write`
29
+ * after changing it); `src/skills/_checkpoints.md` restates it by hand, and a test pins that.
29
30
  */
30
31
  export const GENESEED_GITIGNORE = '/*\n!/.gitignore\n!/bricks/\n!/loops/\n!/factories/\n!/protected-checks.txt\n!/done-checks.txt\n';
31
32
 
@@ -13,10 +13,12 @@
13
13
  * import. A module that is fs/path only is importable from anywhere.
14
14
  *
15
15
  * The OpenCode guard plugin (`adapters/opencode/plugins/geneseed-guard.js`) is copied whole
16
- * into an install and cannot import this, so it carries twins of `gitRootOf`, `gitDirOf`,
16
+ * into an install and cannot import this, so it carries copies of `gitRootOf`, `gitDirOf`,
17
17
  * `gitCommonDirOf`, `currentBranch`, `protectedBranches` and `stashExists` for its Law IV and
18
- * protected-checks gates. `tests/plugins/guard.test.mjs` compares each with the original here;
19
- * change one, change both.
18
+ * protected-checks gates, and the activity plugin of `gitRootOf`, `gitDirOf` and
19
+ * `mainWorktreeOf`. After changing one here, `node tests/twins.mjs --write` — so those
20
+ * functions may use nothing the plugins do not import (`existsSync`, `statSync`,
21
+ * `readFileSync`, `readdirSync`, `path`).
20
22
  */
21
23
  import { existsSync, statSync, lstatSync, readFileSync, readdirSync, openSync, readSync, closeSync } from 'node:fs';
22
24
  import path from 'node:path';
@@ -0,0 +1,104 @@
1
+ /**
2
+ * THE HOOK TAP: an opt-in record of what a host really sends a hook, as a fixture.
3
+ *
4
+ * `GENESEED_HOOK_TAP=<dir>` in the environment the HOST runs under, and every hook call writes
5
+ * one file, `<dir>/<host>-<event>-<n>.json`, after the verb has decided and printed.
6
+ *
7
+ * WHY IT EXISTS. What a host puts on a hook's stdin is the one input this repo cannot derive:
8
+ * Bob's payload was first read off its docs (`{event, tool, input}`), then off its shipped
9
+ * bundle (Claude's keys plus `cwd`), and neither is a recording. Bob is not on npm, so the
10
+ * canary cannot ask it (docs/concepts/host-matrix.md, "What is verified"). A person with the
11
+ * host can: set the variable, do one thing per event, send the files. Each is then a row in a
12
+ * test instead of a sentence in a docblock.
13
+ *
14
+ * WHAT IT WRITES IS THE SHAPE, NOT THE VALUES. A payload carries the user's prompt, file
15
+ * contents, commands and paths, and a tap file is made to be sent to someone else. So every
16
+ * string becomes `{ type: 'string', length: n }`, at any depth. The exceptions are the few
17
+ * top-level strings that say which event and which tool this is (`KEPT`); they come from the
18
+ * host's own vocabulary, and still pass through Law I's pattern (`SECRET_RE`, the activity
19
+ * writer's redaction). Numbers, booleans and null are kept: they are flags and counts. Keys
20
+ * are kept: they are the whole point.
21
+ *
22
+ * WHAT IT REFUSES, silently, like everything on the hook path:
23
+ * - a tap directory inside a git worktree (`gitRootOf`): a capture must not be one `git add`
24
+ * away from a commit;
25
+ * - a relative directory: a hook's cwd is the session's project;
26
+ * - a model-CLI child `learn` spawned (`GENESEED_LEARN_CHILD`), whose hooks are not the host's.
27
+ *
28
+ * IT NEVER PRINTS AND NEVER THROWS. A hook's stdout is its verdict and its exit code is the
29
+ * block; the caller wraps this too. The variable is read from the environment only and no emit
30
+ * ever writes it into a settings file (`tests/unit/hook_tap.test.mjs` holds both).
31
+ *
32
+ * Loaded by `bin/geneseed-hook.mjs` through a dynamic import, and only when the variable is
33
+ * set, so a hook that is not tapped pays one `process.env` read.
34
+ */
35
+ import { mkdirSync, writeFileSync } from 'node:fs';
36
+ import path from 'node:path';
37
+
38
+ import { gitRootOf } from './gitref.mjs';
39
+ import { SECRET_RE } from './hooks-prims.mjs';
40
+
41
+ /** The top-level strings kept as written: which event, which tool, and how it was triggered. */
42
+ const KEPT = new Set(['hook_event_name', 'event', 'tool_name', 'tool', 'source', 'trigger',
43
+ 'permission_mode', 'agent_type', 'matcher']);
44
+
45
+ const SECRET_ALL = new RegExp(SECRET_RE.source, 'g');
46
+ /** A kept string, cut and with anything credential-shaped replaced. */
47
+ const kept = (s) => s.slice(0, 80).replace(SECRET_ALL, '[redacted]');
48
+
49
+ /** How deep a payload is followed. Deeper values become `{ type: 'depth' }`. */
50
+ const MAX_DEPTH = 12;
51
+ /** The most files one event name may fill; the tap then stops rather than fill a disk. */
52
+ const MAX_FILES = 1000;
53
+
54
+ /**
55
+ * `value` with every string replaced by its type and length, keys and structure kept.
56
+ * `top` is true for the payload's own keys, the only place `KEPT` applies.
57
+ */
58
+ export function shapeOf(value, top = true, depth = 0) {
59
+ if (typeof value === 'string') return { type: 'string', length: value.length };
60
+ if (value === null || typeof value !== 'object') return value;
61
+ if (depth >= MAX_DEPTH) return { type: 'depth' };
62
+ if (Array.isArray(value)) return value.map((v) => shapeOf(v, false, depth + 1));
63
+ const out = {};
64
+ for (const [k, v] of Object.entries(value)) {
65
+ out[k] = top && KEPT.has(k) && typeof v === 'string' ? kept(v) : shapeOf(v, false, depth + 1);
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /** A file-name part: letters, digits, `_` and `-` only, never empty. */
71
+ const part = (s, fallback) => (typeof s === 'string' && s.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 40)) || fallback;
72
+
73
+ /**
74
+ * Write one tap file for `raw`, the hook's stdin. Returns the file's path, or null when
75
+ * nothing was written (refused, or the directory is full). Never throws.
76
+ */
77
+ export function tapPayload(dir, raw, { verb, host }) {
78
+ try {
79
+ if (process.env.GENESEED_LEARN_CHILD) return null;
80
+ if (typeof dir !== 'string' || !path.isAbsolute(dir) || gitRootOf(dir)) return null;
81
+ let payload = null;
82
+ try { payload = JSON.parse(raw); } catch { /* not JSON: recorded as such, by length */ }
83
+ const isObject = payload !== null && typeof payload === 'object' && !Array.isArray(payload);
84
+ const event = part(isObject ? (payload.hook_event_name ?? payload.event) : null, verb);
85
+ const body = `${JSON.stringify({
86
+ tap: { host, verb, json: payload !== null || raw.trim() === 'null', bytes: raw.length },
87
+ payload: shapeOf(payload),
88
+ }, null, 2)}\n`;
89
+ mkdirSync(dir, { recursive: true });
90
+ for (let n = 1; n <= MAX_FILES; n += 1) {
91
+ const file = path.join(dir, `${part(host, 'host')}-${event}-${n}.json`);
92
+ try {
93
+ // `wx`: two hooks of one turn run at once, and neither may take the other's number.
94
+ writeFileSync(file, body, { flag: 'wx' });
95
+ return file;
96
+ } catch (e) {
97
+ if (e.code !== 'EEXIST') return null;
98
+ }
99
+ }
100
+ return null;
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
@@ -97,7 +97,7 @@ const EXCLUDE_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'vendor',
97
97
  // The OpenCode context plugin carries the same rule for AGENT.md/AGENTS.md/CLAUDE.md.
98
98
  // OpenClaude's root file is AGENTS.md, or CLAUDE.md when AGENTS.md is absent — resolved
99
99
  // per repo in `discoverContext`, since which one it loads depends on what is on disk.
100
- const NATIVE_ROOT = {
100
+ export const NATIVE_ROOT = {
101
101
  claude: ['CLAUDE.md'], bob: ['AGENTS.md'],
102
102
  openclaude: ['AGENTS.md', 'CLAUDE.md'],
103
103
  };
@@ -219,13 +219,38 @@ function runtimeFloorLine(root) {
219
219
  return pkg && typeof pkg === 'object' && !Array.isArray(pkg) && pkg.engines === undefined ? FLOOR_LINE : null;
220
220
  }
221
221
 
222
+ // ---- rules preamble twin: BEGIN — adapters/opencode/plugins/geneseed-context.js carries everything
223
+ // down to the END marker verbatim, with `export ` dropped (node tests/twins.mjs --write keeps it).
224
+
225
+ /**
226
+ * SHA-256 of the `user-rules.md` seed with its trailing newlines trimmed: the explanation every
227
+ * rules file starts with, until its owner edits it. Hashed, not imported, for `SEED_SHA256`'s
228
+ * reason; tests/unit/claude.test.mjs derives it from `SESSION_SEEDS`.
229
+ */
230
+ export const RULES_PREAMBLE_SHA256 = 'd6973e837c9bf25b50ce068832ceef0a5e5ed2b5931c2c488428ad68aad758c3';
231
+ // A rule's heading, at column 0: the seed's own example (` ## R1 — …`) is indented.
232
+ const RULE_HEADING_RE = /^## R\d+\b/m;
233
+
234
+ /**
235
+ * `text` from its first rule on, when the text above that rule is still the seed's, byte for byte
236
+ * once CRLF is folded: the seed explains the file to its owner, and it cost 1 331 of 4 474
237
+ * characters at every session and sub-agent start. Any prose the owner wrote above the rules stays.
238
+ */
239
+ export function withoutRulesPreamble(text) {
240
+ const rule = RULE_HEADING_RE.exec(text);
241
+ const head = rule ? text.slice(0, rule.index).replace(/\n+$/, '') : null;
242
+ return head !== null && createHash('sha256').update(head).digest('hex') === RULES_PREAMBLE_SHA256
243
+ ? text.slice(rule.index) : text;
244
+ }
245
+ // ---- rules preamble twin: END
246
+
222
247
  /** A session file's text, CRLF-folded and trimmed; null when missing, unreadable or still its seed. */
223
248
  function sessionText(abs) {
224
249
  if (!isFile(abs)) return null;
225
250
  let text;
226
251
  try { text = readFileSync(abs, 'utf8').replace(/\r\n/g, '\n'); } catch { return null; }
227
252
  if (SEED_SHA256.has(createHash('sha256').update(text).digest('hex'))) return null;
228
- return text.replace(/\n+$/, '');
253
+ return withoutRulesPreamble(text).replace(/\n+$/, '');
229
254
  }
230
255
 
231
256
  /** The machine tier's copy of a session file; null for what stays per host (the notebook). */
@@ -823,6 +848,8 @@ export function cmdContext(args) {
823
848
  // Discovery (and the stand-down) runs against the SESSION's project root, not the harness
824
849
  // package dir: `$CLAUDE_PROJECT_DIR` when the host sets it (`hookProjectDir`), because
825
850
  // SessionStart also fires on resume/compact/clear, after the agent may have `cd`'d away.
851
+ // `args.cwd` is the payload's `cwd`, which the hook entry already parsed: Bob sets no such
852
+ // variable, and its payload names the root workspace.
826
853
  // The only two `resolvePath` calls in this file whose argument can be a `~user` path the
827
854
  // user typed — `$GENESEED_ROOT` and `--root` — and `resolvePath` expands, so both can now
828
855
  // throw. Every other caller either builds its argument by `path.join` from an absolute
@@ -832,7 +859,7 @@ export function cmdContext(args) {
832
859
  let hookRoot;
833
860
  try {
834
861
  ({ root, hookRoot } = withDiscardableStderr(() => ({
835
- root: resolvePath(process.env.GENESEED_ROOT || hookProjectDir()),
862
+ root: resolvePath(process.env.GENESEED_ROOT || hookProjectDir(args && args.cwd)),
836
863
  hookRoot: args.root ? resolvePath(args.root) : null,
837
864
  })));
838
865
  } catch {
@@ -24,9 +24,9 @@ const ROOT = path.resolve(import.meta.dirname, '../..');
24
24
 
25
25
  const AGENT_NAME_RE = /^[a-z][a-z0-9-]{1,40}$/;
26
26
  const MAX_NOTES_CHARS = 16000;
27
- // Host payloads name the finished subagent inconsistently; try each.
28
- const SUBAGENT_NAME_FIELDS = ['agent_name', 'agent_type', 'subagent_type', 'agent',
29
- 'agent_id'];
27
+ // Host payloads name the finished subagent inconsistently. Never `agent_id`: it is one dispatch's
28
+ // id, so a lesson keyed on it is a file per dispatch that no later dispatch ever reads.
29
+ const SUBAGENT_NAME_FIELDS = ['agent_name', 'agent_type', 'subagent_type', 'agent'];
30
30
 
31
31
  const PLUGIN_LEARN = path.join(ROOT, 'adapters', 'opencode', 'plugins', 'geneseed-learn.js');
32
32
 
@@ -74,6 +74,17 @@ export function resolveAgentName(raw) {
74
74
  return name && AGENT_NAME_RE.test(name) ? name : null;
75
75
  }
76
76
 
77
+ /**
78
+ * The agent a SubagentStop payload names, as a safe slug, or null. The FIRST field present
79
+ * decides, and a value that is no slug yields no lesson: a plugin's agent arrives namespaced
80
+ * (`plug:rev`), and falling through to a later field would file its lesson under another name.
81
+ * Exported for the unit tier, like `readNotes` below.
82
+ */
83
+ export function subagentNameOf(meta) {
84
+ const field = SUBAGENT_NAME_FIELDS.find((f) => meta[f] !== undefined && meta[f] !== null && meta[f] !== '');
85
+ return field ? resolveAgentName(meta[field]) : null;
86
+ }
87
+
77
88
  /** The lifecycle-hook payload if stdin is one, else `{}`. */
78
89
  function hookMeta(raw) {
79
90
  const s = raw.trim();
@@ -216,9 +227,22 @@ export function buildLearnPrompt(notes, facts) {
216
227
  * distilled memory carrying an accent or an em dash is WRITTEN to the store, so a
217
228
  * mis-decode outlives the process. `maxBuffer` is lifted off Node's 1 MB default, which
218
229
  * would truncate a long reply into a silently-half-parsed set of memory files.
230
+ *
231
+ * BOUNDED: a model CLI that hangs (a login prompt, a dead network) used to hold Stop until the
232
+ * host's own hook timeout killed the hook, and that kill loses whatever the hook had still to
233
+ * say. `$GENESEED_LLM_TIMEOUT` is the limit in seconds, 120 unless it names a positive number.
234
+ * A CLI stopped at the limit has said nothing usable, so its partial reply is dropped, never
235
+ * parsed into half a memory file: one stderr line, and the run ends as if it answered nothing.
219
236
  */
237
+ const LLM_TIMEOUT_S = 120;
238
+ function llmTimeoutSeconds() {
239
+ const n = Number(process.env.GENESEED_LLM_TIMEOUT);
240
+ return Number.isFinite(n) && n > 0 ? n : LLM_TIMEOUT_S;
241
+ }
242
+
220
243
  function runLlm(llm, prompt) {
221
244
  const argv = splitWords(llm);
245
+ const seconds = llmTimeoutSeconds();
222
246
  // `NO_WINDOW` folds in `CREATE_NO_WINDOW`; a model CLI invoked from the windowless daemon
223
247
  // otherwise pops a console for as long as it takes to answer.
224
248
  //
@@ -228,8 +252,12 @@ function runLlm(llm, prompt) {
228
252
  // killing the outermost call. The marker rides in the child's own environment (inherited by
229
253
  // every grandchild too), and `cmdLearn`'s first line stands down the instant it sees it.
230
254
  const proc = spawnSync(argv[0], [...argv.slice(1), prompt],
231
- { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024,
255
+ { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: seconds * 1000, killSignal: 'SIGKILL',
232
256
  env: { ...process.env, GENESEED_LEARN_CHILD: '1' }, ...NO_WINDOW });
257
+ if (proc.error && /** @type {NodeJS.ErrnoException} */ (proc.error).code === 'ETIMEDOUT') {
258
+ err(`[learn] ${argv[0]} gave no answer in ${seconds} s and was stopped - nothing learned.\n`);
259
+ return { stdout: '', stderr: '', returncode: 0, error: null };
260
+ }
233
261
  // Universal newlines, because Python reads the pipe in TEXT mode: a model CLI that is
234
262
  // itself a Python script emits CRLF on Windows, `subprocess` folds it to `\n`, and
235
263
  // `write_text` expands it again on the way into the memory file. Node hands back the raw
@@ -253,11 +281,7 @@ function runLlm(llm, prompt) {
253
281
  * parity of mechanism, degrading to a no-op, never a crash.
254
282
  */
255
283
  function learnAgentLesson(meta, notes, args) {
256
- let agent = null;
257
- for (const field of SUBAGENT_NAME_FIELDS) {
258
- agent = resolveAgentName(meta[field]);
259
- if (agent) break;
260
- }
284
+ const agent = subagentNameOf(meta);
261
285
  if (!agent) return 0;
262
286
  const memDir = resolveMemoryDir(args.memory);
263
287
  if (!memDir) return 0;
@@ -283,7 +307,9 @@ function learnAgentLesson(meta, notes, args) {
283
307
  }
284
308
  }
285
309
  if (proc.returncode !== 0 && proc.stderr) err(proc.stderr);
286
- return proc.returncode;
310
+ // Only a SubagentStop hook reaches this, and the model CLI's code is not the hook's: exit 2
311
+ // there sends the subagent back to work. The failure is on stderr above.
312
+ return 0;
287
313
  }
288
314
 
289
315
  /** `--memory` of a global install's hook, swapped for the shared store when that exists. */
@@ -428,13 +454,18 @@ export function cmdLearn(args) {
428
454
  if (!created.length && !updated.length && !archived.length) {
429
455
  err('[learn] nothing new to store (all duplicates).\n');
430
456
  }
431
- } else if (verdict === 'advisory') {
432
- err(output);
433
- } else {
457
+ } else if (!hookEvent) {
458
+ // A person running `learn` by hand with no store: the reply is what they asked to see.
434
459
  out(output);
460
+ } else if (output.trim() && output.trim().toUpperCase() !== 'NOTHING') {
461
+ // On a hook call stdout is the host's: it holds at most ONE JSON document (the change report
462
+ // or an advisory above), and the model's raw words after it made two, which no host parses,
463
+ // so the report was lost. A bare NOTHING says nothing and is dropped.
464
+ err(output);
435
465
  }
436
466
  if (proc.returncode !== 0 && proc.stderr) err(proc.stderr);
437
- // After an advisory, the model CLI's code is not this hook's: exit 2 on Stop would turn the
438
- // advisory into a block, and any non-zero drops the JSON already on stdout.
439
- return verdict === 'advisory' ? 0 : proc.returncode;
467
+ // On a hook call the model CLI's code is not this hook's: exit 2 on Stop or PreCompact blocks
468
+ // the turn's end or the compaction, and any non-zero drops the JSON already on stdout. The
469
+ // failure is on stderr above. A manual run keeps the code, so a script can test it.
470
+ return hookEvent ? 0 : proc.returncode;
440
471
  }