geneseed 5.1.1 → 5.3.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 (163) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +2 -2
  3. package/SHIPPED.md +1 -1
  4. package/adapters/opencode/README.md +4 -3
  5. package/adapters/opencode/plugins/geneseed-context.js +82 -29
  6. package/adapters/opencode/plugins/geneseed-guard.js +118 -8
  7. package/bin/geneseed-cli.mjs +64 -16
  8. package/bin/geneseed-hook.mjs +37 -3
  9. package/docs/concepts/exclusions.md +1 -1
  10. package/docs/concepts/factories.md +40 -6
  11. package/docs/concepts/footprint.md +1 -1
  12. package/docs/concepts/foreman-mode.md +2 -2
  13. package/docs/concepts/host-matrix.md +1 -1
  14. package/docs/concepts/loop-gates.md +1 -1
  15. package/docs/concepts/loops.md +2 -2
  16. package/docs/concepts/shared-tier.md +1 -1
  17. package/docs/design-history.md +140 -0
  18. package/docs/extending.md +54 -162
  19. package/docs/guides/run-a-factory.md +15 -2
  20. package/docs/guides/setup-doctrines.md +1 -1
  21. package/docs/guides/upgrade.md +2 -2
  22. package/docs/reference/factory-actions.md +6 -5
  23. package/docs/reference/troubleshoot-update.md +1 -1
  24. package/docs/understand/enforced-vs-asked.md +1 -1
  25. package/docs/web-ui.md +16 -3
  26. package/harness.config.json +1 -1
  27. package/js/README.md +10 -7
  28. package/js/build/args.mjs +10 -4
  29. package/js/build/bundle.mjs +122 -23
  30. package/js/build/driver.mjs +32 -12
  31. package/js/build/emit-claude.mjs +2 -1
  32. package/js/build/emit-common.mjs +2 -2
  33. package/js/build/emit-opencode.mjs +22 -10
  34. package/js/build/export.mjs +431 -0
  35. package/js/build/generate.mjs +3 -0
  36. package/js/build/render.mjs +44 -24
  37. package/js/build/source.mjs +6 -1
  38. package/js/cli-table.json +232 -57
  39. package/js/factory/cli.mjs +24 -5
  40. package/js/factory/graph.mjs +13 -9
  41. package/js/factory/metrics.mjs +93 -0
  42. package/js/factory/registry.mjs +37 -12
  43. package/js/factory/state.mjs +25 -6
  44. package/js/hosts/hooks-context.mjs +26 -1
  45. package/js/hosts/hooks-done.mjs +8 -2
  46. package/js/hosts/hooks-prims.mjs +52 -3
  47. package/js/hosts/hooks.mjs +155 -33
  48. package/js/hosts/hosts.mjs +2 -4
  49. package/js/hosts/installs.mjs +28 -0
  50. package/js/hosts/loss.mjs +25 -3
  51. package/js/hosts/native.mjs +30 -2
  52. package/js/hosts/owned.mjs +55 -1
  53. package/js/hosts/ownership-gate.mjs +5 -5
  54. package/js/hosts/settings.mjs +83 -33
  55. package/js/inspect/diff.mjs +16 -1
  56. package/js/inspect/doctor.mjs +7 -3
  57. package/js/inspect/excludes.mjs +18 -6
  58. package/js/inspect/status.mjs +35 -7
  59. package/js/inspect/validate.mjs +44 -21
  60. package/js/lib/managed-block.mjs +74 -0
  61. package/js/maintain/uninstall.mjs +85 -15
  62. package/js/maintain/update.mjs +31 -7
  63. package/js/ui/cli.mjs +34 -4
  64. package/js/ui/menu.mjs +1 -1
  65. package/js/ui/tui.mjs +11 -14
  66. package/js/web/actions.mjs +5 -0
  67. package/js/web/api.mjs +32 -11
  68. package/js/web/daemon.mjs +0 -1
  69. package/js/web/server.mjs +1 -0
  70. package/js/web/state.mjs +37 -16
  71. package/package.json +1 -1
  72. package/src/AGENT.md.tmpl +23 -17
  73. package/src/agents/_template.md +1 -1
  74. package/src/agents/advocate.md +1 -1
  75. package/src/agents/developer.md +12 -3
  76. package/src/agents/empiricist.md +1 -1
  77. package/src/agents/framer.md +1 -1
  78. package/src/agents/historian.md +1 -1
  79. package/src/agents/operator.md +1 -1
  80. package/src/agents/pragmatist.md +1 -1
  81. package/src/agents/researcher.md +1 -1
  82. package/src/agents/skeptic.md +1 -1
  83. package/src/agents/steward.md +1 -1
  84. package/src/agents/user-advocate.md +1 -1
  85. package/src/agents/visionary.md +1 -1
  86. package/src/bricks/intake.md +10 -3
  87. package/src/bricks/retro.md +13 -3
  88. package/src/doctrines/comms.md +1 -1
  89. package/src/doctrines/ops.md +1 -1
  90. package/src/doctrines/process.md +7 -5
  91. package/src/factories/analysis-to-build.json +1 -0
  92. package/src/factories/bug-report-to-fix.json +1 -0
  93. package/src/factories/issue-to-pr.json +1 -0
  94. package/src/laws/universal.md +2 -2
  95. package/src/modes/foreman.md +8 -14
  96. package/src/skills/commit.md +7 -2
  97. package/src/skills/debug.md +1 -1
  98. package/src/skills/diagram-design/SKILL.md +1 -1
  99. package/src/skills/diagram-design/VENDOR.md +3 -1
  100. package/src/skills/factory-forge.md +5 -3
  101. package/src/skills/factory.md +22 -1
  102. package/src/skills/geneseed.md +1 -1
  103. package/src/skills/handoff.md +1 -1
  104. package/src/skills/parallel-agents.md +1 -1
  105. package/src/skills/pipeline.md +6 -6
  106. package/src/skills/plan.md +7 -3
  107. package/src/skills/spring-testing.md +1 -1
  108. package/themes/biker.json +78 -78
  109. package/themes/commentator.json +81 -81
  110. package/themes/cyberpunk.json +79 -79
  111. package/themes/gamer.json +77 -77
  112. package/themes/imperial.json +82 -82
  113. package/themes/joker.json +79 -79
  114. package/themes/marvin.json +82 -82
  115. package/themes/mean.json +82 -82
  116. package/themes/military.json +78 -78
  117. package/themes/neutral.json +78 -78
  118. package/themes/pirate.json +79 -79
  119. package/themes/sports.json +79 -79
  120. package/themes/verstappen.json +78 -78
  121. package/themes/wizard.json +79 -79
  122. package/web/dist/assets/ActiveLoops-BJJN3P-V.js +1 -0
  123. package/web/dist/assets/Activity-CqJiquEq.js +1 -0
  124. package/web/dist/assets/ActivityDetail-BSzevynX.js +1 -0
  125. package/web/dist/assets/{Bonsai-hiG_gGNU.js → Bonsai-Bfpb6W-1.js} +1 -1
  126. package/web/dist/assets/{CopyButton-DUIUfNp6.js → CopyButton-ByIntFtB.js} +1 -1
  127. package/web/dist/assets/Dashboard-DBOEi9lQ.js +2 -0
  128. package/web/dist/assets/Docs-DvlMJhpu.js +5 -0
  129. package/web/dist/assets/Factories-Bpvv7L2H.js +1 -0
  130. package/web/dist/assets/{GreenhouseView-BKxy5apE.js → GreenhouseView-GpBsYn50.js} +1 -1
  131. package/web/dist/assets/Installs-BlGmVrFK.js +3 -0
  132. package/web/dist/assets/{JournalView-ChFitHjo.js → JournalView-iLuLrOxE.js} +1 -1
  133. package/web/dist/assets/Kits-DRwpxC-J.js +1 -0
  134. package/web/dist/assets/Laws-CZkiNOWQ.js +4 -0
  135. package/web/dist/assets/LibRows-DEHjIoD-.js +1 -0
  136. package/web/dist/assets/Library-B4K-1iNF.js +3 -0
  137. package/web/dist/assets/Loops-BWSzaW8E.js +2 -0
  138. package/web/dist/assets/{OperatorHudView-BO0aIKPL.js → OperatorHudView-BAXwCEvY.js} +1 -1
  139. package/web/dist/assets/Personal-Bp9nV4GR.js +2 -0
  140. package/web/dist/assets/Settings-CWWuaIp-.js +1 -0
  141. package/web/dist/assets/Tabs-CWeQTADL.js +1 -0
  142. package/web/dist/assets/index-CsAZq0BQ.css +1 -0
  143. package/web/dist/assets/index-How7SzDZ.js +6 -0
  144. package/web/dist/assets/usePoll-D5c_qIFZ.js +1 -0
  145. package/web/dist/index.html +2 -2
  146. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +0 -1
  147. package/web/dist/assets/Activity-CpkBwpu7.js +0 -1
  148. package/web/dist/assets/ActivityDetail-DTPziZWM.js +0 -1
  149. package/web/dist/assets/Dashboard-Dnw6EyX7.js +0 -2
  150. package/web/dist/assets/Docs-BEET_l16.js +0 -5
  151. package/web/dist/assets/Factories-D6KXkfWw.js +0 -1
  152. package/web/dist/assets/Installs-CnFVlVD0.js +0 -3
  153. package/web/dist/assets/Kits-CcR-OlwQ.js +0 -1
  154. package/web/dist/assets/Laws-B1s5idOg.js +0 -4
  155. package/web/dist/assets/LibRows-BZgdbI1l.js +0 -1
  156. package/web/dist/assets/Library-x6TkkEVF.js +0 -3
  157. package/web/dist/assets/Loops-BH93KKxn.js +0 -2
  158. package/web/dist/assets/Personal-CE_0Vhh0.js +0 -2
  159. package/web/dist/assets/Settings-CbpZvVN_.js +0 -1
  160. package/web/dist/assets/Tabs-C2oW7oEj.js +0 -1
  161. package/web/dist/assets/index-BQwOmbor.js +0 -6
  162. package/web/dist/assets/index-CuIop_pO.css +0 -1
  163. package/web/dist/assets/usePoll-o8ul-Sog.js +0 -1
@@ -11,7 +11,7 @@
11
11
  * rather than copied, so the two engines cannot drift on what "declared" means.
12
12
  *
13
13
  * FORKS AND `$lane` (D11, D13). A fork is a brick stage that declares an outcome other than
14
- * `pass`, `fail`, `error`, `none` or `needs-info` — a named outcome, such as `triage`'s `bug` or `docs`. Each
14
+ * `pass`, `fail`, `error`, `none`, `needs-info` or `reject` — a named outcome, such as `triage`'s `bug` or `docs`. Each
15
15
  * outcome has its own edge (rule 3), so the edges out of a fork ARE its lanes: an outcome whose
16
16
  * edge reaches a stage. An edge target or a cycle node may be `$lane`: the stage the run's most
17
17
  * recent fork chose, which the engine records in FACTORY.md and resolves at runtime. Statically,
@@ -55,10 +55,13 @@ export const LOOP_OUTCOMES = ['pass', 'fail'];
55
55
  /**
56
56
  * The outcomes that name no lane; any other declared outcome makes its brick a fork (D11).
57
57
  * `needs-info` is `intake`'s question to the user (a gate), never a lane: listed here, it sets
58
- * no `state.lane`, hands no `lanes` and leaves `$lane` alone.
58
+ * no `state.lane`, hands no `lanes` and leaves `$lane` alone. `reject` is `intake`'s refusal of
59
+ * the work item (already done, a duplicate, against a stated rule): a gate too, and no lane, so a
60
+ * brick that declares it stays a plain stage.
59
61
  */
60
62
  const NEEDS_INFO = 'needs-info';
61
- const PLAIN_OUTCOMES = new Set(['pass', 'fail', 'error', 'none', NEEDS_INFO]);
63
+ const REJECT = 'reject';
64
+ const PLAIN_OUTCOMES = new Set(['pass', 'fail', 'error', 'none', NEEDS_INFO, REJECT]);
62
65
  /** The work item sizes `intake` rates; `review.seats` needs a list for each (rule 9). */
63
66
  const SEAT_SIZES = ['small', 'medium', 'large'];
64
67
  /**
@@ -72,13 +75,14 @@ const edgeShaped = (e) => ['from', 'on', 'to'].every((k) => typeof e?.[k] === 's
72
75
 
73
76
  /**
74
77
  * The edge an outcome follows: its own, else for `needs-info` the stage's `pass` edge (a factory
75
- * with no needs-info edge goes on as if intake had passed), else for `error` a stop. Null when
76
- * none applies. The engine's one lookup, so `record` and a gate's `ok` cannot disagree.
78
+ * with no needs-info edge goes on as if intake had passed), else for `error` and `reject` a stop
79
+ * (a refused item has nowhere to go but `$stop`, so a factory written before intake could refuse
80
+ * needs no new edge). Null when none applies. The engine's one lookup, so `record` and a gate's `ok` cannot disagree.
77
81
  */
78
82
  export function edgeFor(factory, from, outcome) {
79
83
  const own = (on) => (Array.isArray(factory?.edges) ? factory.edges : []).find((e) => e?.from === from && e.on === on);
80
84
  return own(outcome) ?? (outcome === NEEDS_INFO ? own('pass') : undefined)
81
- ?? (outcome === 'error' ? { from, on: 'error', to: '$stop' } : null);
85
+ ?? (outcome === 'error' || outcome === REJECT ? { from, on: outcome, to: '$stop' } : null);
82
86
  }
83
87
 
84
88
  /** The template a `loop:` stage names, or null for a brick stage. */
@@ -210,13 +214,13 @@ export function checkFactory(factory, { bricks, templates, agents }) {
210
214
  const outcomes = stageOutcomes(e.from, bricks);
211
215
  if (outcomes && !outcomes.includes(e.on)) problems.push(`${label}: ${e.on} is not an outcome of ${e.from}`);
212
216
  }
213
- // rule 3 — exactly one edge per outcome; `error` may go without one (the engine routes it to
214
- // $stop), and so may `needs-info` when the stage has a `pass` edge for it to follow (`edgeFor`),
217
+ // rule 3 — exactly one edge per outcome; `error` and `reject` may go without one (the engine
218
+ // routes each to $stop), and so may `needs-info` when the stage has a `pass` edge for it to follow (`edgeFor`),
215
219
  // so a factory written before intake could ask stays valid, and so does a FACTORY.md that embeds one
216
220
  for (const s of [...stages].sort()) {
217
221
  for (const o of stageOutcomes(s, bricks) ?? []) {
218
222
  const count = edges.filter((e) => e.from === s && e.on === o).length;
219
- const exempt = o === 'error' || (o === NEEDS_INFO && edges.some((e) => e.from === s && e.on === 'pass'));
223
+ const exempt = o === 'error' || o === REJECT || (o === NEEDS_INFO && edges.some((e) => e.from === s && e.on === 'pass'));
220
224
  if (count === 0 && !exempt) problems.push(`stage ${s}: no edge for outcome ${o}`);
221
225
  else if (count > 1) problems.push(`stage ${s}: ${count} edges for outcome ${o}`);
222
226
  }
@@ -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)}`;
@@ -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). */
@@ -98,7 +98,8 @@ export function runsUnpiped(command, line) {
98
98
  const next = cmd[i + line.length];
99
99
  if (next !== undefined && !/[\s;&|]/.test(next)) continue;
100
100
  const head = cmd.slice(0, i);
101
- if (!/(^|&&|\|\||;|\n) ?$/.test(head)) continue;
101
+ // Not after `||`: `true || npm test` never runs the check.
102
+ if (!/(^|&&|(?<!\|)\|(?!\|)|;|\n) ?$/.test(head.replace(/\|\| ?$/, '\u0000'))) continue;
102
103
  let quote = '', esc = false;
103
104
  for (const ch of head) {
104
105
  if (esc) esc = false;
@@ -114,7 +115,12 @@ export function runsUnpiped(command, line) {
114
115
  if (two === '&&' || two === '||' || rest[j] === ';' || rest[j] === '\n') break;
115
116
  if (rest[j] === '|') { piped = true; break; }
116
117
  }
117
- if (!piped && !/\|\||[;\n] ?(?:true|:|exit(?: 0)?)(?= ?(?:$|[;&|\n]))/.test(rest)) return true;
118
+ // MASKED when the line's exit status is not the check's: a `||` after it; behind `;` or a
119
+ // newline, a command that always succeeds (`true`, `:`, `exit`, and `echo`/`printf`, as in
120
+ // the common `npm test; echo "exit: $?"`, which exits 0 on a red suite); or a trailing lone
121
+ // `&`, which backgrounds the check. A real next command is not a mask, and `&&` keeps the status.
122
+ const masked = /\|\||[;\n] ?(?:true|:|exit(?: 0)?|(?:echo|printf)(?: [^;&|\n]*)?)(?= ?(?:$|[;&|\n]))|(?<!&)& ?$/.test(rest);
123
+ if (!piped && !masked) return true;
118
124
  }
119
125
  return false;
120
126
  }
@@ -182,8 +182,37 @@ export function weakenedBy(pairs) {
182
182
  }
183
183
  // ---- test-weakening twin: END
184
184
 
185
- // One Roo-style `apply_diff` block: its SEARCH half, then its REPLACE half.
186
- export const DIFF_BLOCK_RE = /<<<<<<< SEARCH\r?\n(?::start_line:\s*\d+\r?\n)?(?:-------\r?\n)?([\s\S]*?)\r?\n?=======\r?\n([\s\S]*?)\r?\n?>>>>>>> REPLACE/g;
185
+ /**
186
+ * The Roo-style `apply_diff` blocks of `diff` as `[search, replace]` pairs: what
187
+ * `/<<<<<<< SEARCH\r?\n(?::start_line:\s*\d+\r?\n)?(?:-------\r?\n)?([\s\S]*?)\r?\n?=======\r?\n([\s\S]*?)\r?\n?>>>>>>> REPLACE/g`
188
+ * matched, read in one pass. That regex, on blocks opened and never closed, retried every later
189
+ * separator from every opening: 32 KB took 4.7 s and 256 KB ran past 120 s, past Bob's hook
190
+ * timeout, so the secrets gate never judged the call. Each half ends at the FIRST separator after
191
+ * it, as the lazy groups did; a block with no closing after its first separator has none after any
192
+ * later one either, so the scan stops there, where the regex would have found nothing more.
193
+ */
194
+ export function diffBlocks(diff) {
195
+ const at = (re, from) => { re.lastIndex = from; return re.exec(diff); };
196
+ const OPEN = /<<<<<<< SEARCH\r?\n/g;
197
+ const LINE = /:start_line:\s*\d+\r?\n/y;
198
+ const DASH = /-------\r?\n/y;
199
+ const SEP = /\r?\n?=======\r?\n/g;
200
+ const CLOSE = /\r?\n?>>>>>>> REPLACE/g;
201
+ const pairs = [];
202
+ for (let pos = 0, open; (open = at(OPEN, pos));) {
203
+ let start = open.index + open[0].length;
204
+ const line = at(LINE, start);
205
+ if (line) start += line[0].length;
206
+ const dash = at(DASH, start);
207
+ if (dash) start += dash[0].length;
208
+ const sep = at(SEP, start);
209
+ const close = sep && at(CLOSE, sep.index + sep[0].length);
210
+ if (!close) break;
211
+ pairs.push([diff.slice(start, sep.index), diff.slice(sep.index + sep[0].length, close.index)]);
212
+ pos = close.index + close[0].length;
213
+ }
214
+ return pairs;
215
+ }
187
216
 
188
217
  /**
189
218
  * A write tool's input as `[old, new]` pairs for `weakenedBy`. `whole` is the file before a
@@ -200,7 +229,7 @@ export function editPairs(ti, whole = '') {
200
229
  for (const e of Array.isArray(ti.edits) ? ti.edits : []) {
201
230
  if (e && typeof e.new_string === 'string') pairs.push([text(e.old_string), e.new_string]);
202
231
  }
203
- if (typeof ti.diff === 'string') for (const m of ti.diff.matchAll(DIFF_BLOCK_RE)) pairs.push([m[1], m[2]]);
232
+ if (typeof ti.diff === 'string') pairs.push(...diffBlocks(ti.diff));
204
233
  return pairs;
205
234
  }
206
235
 
@@ -474,6 +503,26 @@ export function gateLoss(reason) {
474
503
  }
475
504
  // ---- gate text twin: END
476
505
 
506
+ /**
507
+ * The `permissionDecision: "ask"` document, in Python's compact `json.dumps` spelling: `, ` and
508
+ * `: ` separators, and `ensure_ascii` — every code unit past `~` as a lowercase `\uXXXX`, which is
509
+ * why a reason's em dash reaches stdout as `—`.
510
+ *
511
+ * A TEMPLATE, NOT `js/lib/json.mjs`'s `jsonDumpsCompact`. The keys are fixed and the one value
512
+ * is a string, so the general serializer bought nothing here — and it cost every tool call a
513
+ * 378-line module parse, being the only thing on the gate path that needed it.
514
+ * `tests/unit/hook_gates.test.mjs` holds the two byte-identical over non-ASCII reasons.
515
+ */
516
+ export function askDecision(reason) { return decisionDoc('ask', reason); }
517
+
518
+ export function decisionDoc(decision, reason) {
519
+ return `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "${decision}", `
520
+ + `"permissionDecisionReason": ${asciiJson(reason)}}}\n`;
521
+ }
522
+
523
+ export const asciiJson = (s) => JSON.stringify(s)
524
+ .replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
525
+
477
526
  const OFF = ['off', '0', 'false', 'no'];
478
527
 
479
528
  /**