geneseed 5.0.3 → 5.0.4

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 (128) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +3 -3
  3. package/SHIPPED.md +2 -2
  4. package/adapters/claude-code/README.md +5 -1
  5. package/adapters/openclaude/README.md +3 -1
  6. package/adapters/opencode/plugins/geneseed-workflow.js +1 -1
  7. package/adapters/opencode/workflows/_runtime.js +1 -1
  8. package/bin/geneseed-cli.mjs +3 -0
  9. package/bin/geneseed-hook.mjs +10 -2
  10. package/docs/PRD.md +1 -1
  11. package/docs/README.md +4 -1
  12. package/docs/concepts/enforcement-table.md +1 -1
  13. package/docs/concepts/exclusions.md +1 -1
  14. package/docs/concepts/factories.md +151 -0
  15. package/docs/concepts/hooks.md +1 -1
  16. package/docs/concepts/host-matrix.md +1 -0
  17. package/docs/concepts/loop-gates.md +3 -0
  18. package/docs/concepts/loops.md +1 -0
  19. package/docs/concepts/rules.md +1 -1
  20. package/docs/extending.md +5 -1
  21. package/docs/guides/autostart.md +2 -0
  22. package/docs/guides/run-a-factory.md +88 -0
  23. package/docs/guides/set-up-ownership.md +1 -0
  24. package/docs/reference/factory-actions.md +22 -0
  25. package/docs/reference/loop-actions.md +1 -1
  26. package/docs/reference/plugin-activity.md +1 -1
  27. package/docs/web-ui.md +35 -2
  28. package/harness.config.json +1 -1
  29. package/js/README.md +20 -2
  30. package/js/build/args.mjs +14 -2
  31. package/js/build/source.mjs +19 -0
  32. package/js/cli-table.json +166 -2
  33. package/js/factory/cli.mjs +153 -0
  34. package/js/factory/graph.mjs +245 -0
  35. package/js/factory/registry.mjs +71 -0
  36. package/js/factory/state.mjs +429 -0
  37. package/js/hosts/activity.mjs +3 -3
  38. package/js/hosts/geneseed-dir.mjs +1 -1
  39. package/js/hosts/gitref.mjs +21 -0
  40. package/js/hosts/hooks-context.mjs +63 -9
  41. package/js/hosts/hooks-prims.mjs +1 -1
  42. package/js/hosts/settings.mjs +5 -4
  43. package/js/inspect/checks-authoring.mjs +11 -1
  44. package/js/inspect/cost.mjs +91 -5
  45. package/js/inspect/doctor.mjs +2 -1
  46. package/js/inspect/inventory.mjs +1 -1
  47. package/js/loop/catalog.mjs +24 -12
  48. package/js/loop/cli.mjs +21 -15
  49. package/js/loop/graph.mjs +13 -4
  50. package/js/loop/registry.mjs +65 -28
  51. package/js/loop/state.mjs +18 -8
  52. package/js/web/api.mjs +43 -1
  53. package/js/web/catalog.mjs +38 -2
  54. package/js/web/daemon.mjs +136 -6
  55. package/js/web/handler.mjs +14 -5
  56. package/js/web/routes.mjs +10 -3
  57. package/js/web/server.mjs +4 -1
  58. package/package.json +1 -1
  59. package/registry.json +14 -0
  60. package/src/AGENT.md.tmpl +5 -7
  61. package/src/bricks/docs-update.md +5 -0
  62. package/src/bricks/holdout-write.md +23 -0
  63. package/src/bricks/holdout.md +25 -0
  64. package/src/bricks/intake.md +18 -0
  65. package/src/bricks/merge-gate.md +22 -0
  66. package/src/bricks/pr-open.md +21 -0
  67. package/src/bricks/retro.md +17 -0
  68. package/src/bricks/test.md +4 -1
  69. package/src/bricks/triage.md +19 -0
  70. package/src/doctrines/comms.md +29 -41
  71. package/src/doctrines/craft.md +3 -10
  72. package/src/doctrines/ops.md +4 -15
  73. package/src/doctrines/rigor.md +1 -5
  74. package/src/factories/analysis-to-build.json +34 -0
  75. package/src/factories/bug-report-to-fix.json +32 -0
  76. package/src/factories/issue-to-pr.json +49 -0
  77. package/src/skills/_checkpoints.md +1 -0
  78. package/src/skills/adhd.md +1 -1
  79. package/src/skills/factory-forge.md +97 -0
  80. package/src/skills/factory.md +126 -0
  81. package/src/skills/parallel-agents.md +1 -1
  82. package/src/skills/workflow.md +2 -1
  83. package/themes/_TEMPLATE.json +4 -2
  84. package/themes/biker.json +4 -2
  85. package/themes/commentator.json +4 -2
  86. package/themes/cyberpunk.json +4 -2
  87. package/themes/gamer.json +4 -2
  88. package/themes/imperial.json +4 -2
  89. package/themes/joker.json +4 -2
  90. package/themes/marvin.json +4 -2
  91. package/themes/mean.json +4 -2
  92. package/themes/military.json +4 -2
  93. package/themes/neutral.json +4 -2
  94. package/themes/pirate.json +4 -2
  95. package/themes/sports.json +4 -2
  96. package/themes/verstappen.json +4 -2
  97. package/themes/wizard.json +4 -2
  98. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +1 -0
  99. package/web/dist/assets/{Activity-Ck_Xffpo.js → Activity-BaoxwVFH.js} +1 -1
  100. package/web/dist/assets/{ActivityDetail-CBxVS4mU.js → ActivityDetail-C_bFD0rW.js} +1 -1
  101. package/web/dist/assets/{Bonsai-BlOwsvW6.js → Bonsai-B01lLf0m.js} +1 -1
  102. package/web/dist/assets/{CopyButton-DFMOIGbe.js → CopyButton-Bc66KPyA.js} +1 -1
  103. package/web/dist/assets/Dashboard-X7GZzGJp.js +2 -0
  104. package/web/dist/assets/{Docs-D_2Jt6gU.js → Docs-LRYVnGLG.js} +2 -2
  105. package/web/dist/assets/Factories-ARenKBiP.js +1 -0
  106. package/web/dist/assets/{GreenhouseView-WalcX5bp.js → GreenhouseView-CfWR2-sX.js} +1 -1
  107. package/web/dist/assets/{Installs-UGiPDMDt.js → Installs-nfFHnovH.js} +3 -3
  108. package/web/dist/assets/{JournalView-CZtXQz-v.js → JournalView-lpOHcHKK.js} +1 -1
  109. package/web/dist/assets/{Kits-XQHsazCN.js → Kits-Bw5EQl_i.js} +1 -1
  110. package/web/dist/assets/Laws-CnZJ0wjZ.js +4 -0
  111. package/web/dist/assets/LibRows-Hqvf1beK.js +1 -0
  112. package/web/dist/assets/Library-JaSsp6Yr.js +3 -0
  113. package/web/dist/assets/Loops-ZaHC5MVl.js +2 -0
  114. package/web/dist/assets/{OperatorHudView-CeDw5qMB.js → OperatorHudView-CggG0_sK.js} +1 -1
  115. package/web/dist/assets/{Personal-PVmGA2-M.js → Personal-BObvlb70.js} +2 -2
  116. package/web/dist/assets/{Settings-DWuxwh4i.js → Settings-BFfPMPc9.js} +1 -1
  117. package/web/dist/assets/{Tabs-d2RIRAKT.js → Tabs-B594Pad_.js} +1 -1
  118. package/web/dist/assets/api-DLDVY3K-.js +1 -0
  119. package/web/dist/assets/{index-BNttaGQb.js → index-DsLmKHw0.js} +3 -3
  120. package/web/dist/assets/index-DvPjphz0.css +1 -0
  121. package/web/dist/index.html +3 -3
  122. package/web/dist/assets/Dashboard-BUdUTjbB.js +0 -2
  123. package/web/dist/assets/Laws-B6A55S-2.js +0 -4
  124. package/web/dist/assets/Library-D7L0Wdbh.js +0 -3
  125. package/web/dist/assets/Loops-C0loS73u.js +0 -2
  126. package/web/dist/assets/RailCats-BGZnJ6fa.js +0 -1
  127. package/web/dist/assets/api-BMFDSXoB.js +0 -1
  128. package/web/dist/assets/index-BEI5ugYQ.css +0 -1
@@ -0,0 +1,429 @@
1
+ /**
2
+ * The factory engine: a state machine over a factory graph (`js/factory/graph.mjs`), persisted as
3
+ * a JSON block in FACTORY.md — the loop engine's model (`js/loop/state.mjs`) one level up.
4
+ *
5
+ * ONE STATE FILE PER LEVEL (D5). FACTORY.md sits beside LOOP.md in the same worktree; a `loop:`
6
+ * stage is a whole child loop with its own LOOP.md, and this engine never reads or writes inside
7
+ * it. The child engine is unchanged: it only learned to treat FACTORY.md as bookkeeping
8
+ * (`ENGINE_FILES`) and to start from the factory's `carry` (`initState`'s `notes`, D16).
9
+ *
10
+ * WHY THE MODEL NEVER DECIDES. As in the loop engine, every transition, counter and stop is
11
+ * computed here; the `factory` Rite runs the stage it is handed and reports the outcome.
12
+ *
13
+ * WHICH CYCLE A BACK-ROUTE SPENDS. Cycles are declared as node sets (J6). An edge spends the
14
+ * smallest cycle whose FIRST stage is the edge's target and which also holds its source — the loop
15
+ * engine's `repairRing` convention, so `{ nodes: ["loop:bugfix", "pr-open", "merge-gate"] }` is
16
+ * spent by `merge-gate --fail--> loop:bugfix`, once per lap. `checkFactory` refuses a graph where
17
+ * that convention would miscount: a cycle entered anywhere but its first stage, or a lap that
18
+ * crosses no spending edge (a route back into the middle of a cycle).
19
+ *
20
+ * NO SCORING, AND A CLEAN TREE. Risk is the loop engine's job (J5). A stage outside a loop records
21
+ * only on a clean worktree — a mutate brick such as a `docs-update` lane (D12) commits its change
22
+ * first — so `recordStage` refuses a dirty porcelain after one — engine files and
23
+ * the run's spec at `specs/<slug>/spec.md` excepted (the one being recorded, else the one on
24
+ * record: it is uncommitted until the gate approves it, and the Rite commits it then, before the
25
+ * first loop, whose first read brick would stop on it otherwise) — instead of carrying
26
+ * uncommitted work into the next loop. The porcelain must be
27
+ * `git status --porcelain --untracked-files=all`: plain `--porcelain` folds a new directory into `?? specs/`, which no exemption can match. No porcelain
28
+ * at all (`null`, a TTY stdin) is refused too: it proves nothing. The limit: an empty pipe reads
29
+ * as a clean tree, so the engine trusts whoever pipes it.
30
+ *
31
+ * A LOOP STAGE REPORTS WHAT ITS LOOP DID (R2). `next` on a loop stage stores the launch
32
+ * (`launched`: the stage, its template, the HEAD commit and the time then). `record` on it then
33
+ * needs evidence. With a LOOP.md left, the evidence is that file: its template must be the stage's,
34
+ * and its status must match the outcome (stopped is fail, done is pass). With no LOOP.md left, HEAD
35
+ * must have moved since the launch (the loop's close commit, or the commit that removed a stopped
36
+ * loop's LOOP.md), and `fail` needs nothing more. `pass` also needs the loop registry
37
+ * (`js/loop/registry.mjs`): its row for this worktree must carry an `initAt` later than the launch,
38
+ * so a `geneseed loop init` ran here after `next`, and with no LOOP.md left that loop has ended.
39
+ * What this does NOT prove: that the ended loop closed rather than stopped (the registry keeps no
40
+ * status), or that it ran the stage's template. A stopped loop whose LOOP.md was removed by hand
41
+ * can still pass. The registry row's `started` cannot serve: it is set once per worktree, so a
42
+ * re-entered loop would never pass.
43
+ *
44
+ * R4 COVERS WHAT A HAND CAN EDIT. FACTORY.md is a file; `validateFactoryState` refuses counters
45
+ * that are not non-negative integers, a ceiling above 600, a task block out of its bounds, a gate
46
+ * amend count above 3, a `lane` no fork of the factory leads to, a status the engine does not
47
+ * write, a `history` or `factory.cycles` that is not a list, and a factory that no longer passes
48
+ * `checkFactory` — the termination argument below holds only for a state this engine could have
49
+ * written.
50
+ *
51
+ * LANES (D11, D13). A fork is a brick stage with named outcomes (`isFork`, `js/factory/graph.mjs`).
52
+ * `next` hands it `lanes` (each outcome with the stage it leads to), and `record` on it stores the
53
+ * stage its outcome's edge reaches as `lane`. An edge to `$lane` resolves to that stage, and spends
54
+ * the cycle `spentCycle` names for the literal `$lane` target, the rule `checkFactory` proves the
55
+ * graph against. A route to `$lane` with no lane on record (a state `check` cannot produce) is
56
+ * refused before the state changes, on `record` and on a gate's `ok` alike: never guessed.
57
+ *
58
+ * TASKS (D9). A stage that writes a spec records its path and task count (`tasks`). The first
59
+ * `loop:` stage recorded after it owns the tasks (`tasks.stage`) and alone is replayed once per
60
+ * task, `index` 1 to `count`; a fix loop that runs in between follows its own edges. A task the
61
+ * run reaches for the FIRST time starts with fresh cycle counters and a fresh per-task ceiling
62
+ * (J6); `taskHigh` is the highest index reached, so a spec re-recorded after a route back (index
63
+ * back to 1) gives no task a second fresh budget. A route back into the owner after its last task
64
+ * (J7: red CI at `merge-gate`) is ONE EXTRA TASK: `next` marks it `extra`, read off `history`
65
+ * alone, and it reaches no task never reached, so it spends the route's cycle and both ceilings
66
+ * like any lap and resets nothing.
67
+ *
68
+ * TERMINATION BY CONSTRUCTION (J3, R8). `transitions` counts per task and resets with it. On top,
69
+ * `runTransitions` counts every transition of the run, never resets, and stops the run past
70
+ * `runCeiling`: `FACTORY_MAX_TRANSITIONS` until a spec is recorded, then
71
+ * `FACTORY_MAX_TRANSITIONS` x its task count, set ONCE at the first --spec record. The count is
72
+ * frozen there: a later --spec record may keep or lower it, never raise it, so no lap can buy a
73
+ * task, a fresh budget or a higher ceiling. And it is capped at `FACTORY_MAX_TASKS` (20), so the
74
+ * ceiling is at most 600 transitions: past twenty tasks a requirement is a project, to be split
75
+ * into several factory runs a human can review, not one run nobody reads to the end.
76
+ */
77
+ import { writeText } from '../lib/fs.mjs';
78
+ import { renameWithRetry, filterPorcelain } from '../loop/state.mjs';
79
+ import { loopOf, stageOutcomes, checkFactory, LANE, isFork, lanesOf, laneTargets, spentCycle } from './graph.mjs';
80
+
81
+ const BEGIN = '<!-- factory-state:begin -->';
82
+ const END = '<!-- factory-state:end -->';
83
+ export const FACTORY_FILE = 'FACTORY.md';
84
+ export const FACTORY_MAX_TRANSITIONS = 30;
85
+ export const FACTORY_MAX_TASKS = 20;
86
+ const GATE_MAX_AMENDS = 3;
87
+ const STATUSES = ['running', 'awaiting', 'done', 'stopped'];
88
+ const PORCELAIN = 'git status --porcelain --untracked-files=all';
89
+ const slash = (p) => String(p).replaceAll('\\', '/');
90
+
91
+ export function renderFactoryFile(state) {
92
+ return `# Factory — ${state.title}\n\n${state.requirement}\n\n`
93
+ + 'The block below belongs to the engine: `geneseed factory` rewrites it on every action.\n\n'
94
+ + `${BEGIN}\n\`\`\`json\n${JSON.stringify(state, null, 2)}\n\`\`\`\n${END}\n`;
95
+ }
96
+
97
+ /** R4: anything that is not a well-formed block throws, so every action refuses and none repairs. */
98
+ export function parseFactoryFile(text) {
99
+ const t = String(text).replace(/\r\n/g, '\n');
100
+ const a = t.indexOf(BEGIN); const b = t.lastIndexOf(END);
101
+ if (a < 0 || b < a) throw new Error('FACTORY.md has no factory-state block');
102
+ const inner = t.slice(a + BEGIN.length, b).replace(/^\s*```json\s*/, '').replace(/\s*```\s*$/, '');
103
+ let state;
104
+ try { state = JSON.parse(inner); } catch (e) {
105
+ throw new Error(`FACTORY.md is unreadable: ${e.message}`, { cause: e });
106
+ }
107
+ if (state?.v !== 1) throw new Error('FACTORY.md is unreadable: no state of version 1');
108
+ return state;
109
+ }
110
+
111
+ const count = (v) => Number.isInteger(v) && v >= 0;
112
+ const plainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
113
+
114
+ /**
115
+ * R4, past the JSON: a state this engine could have written, and a factory that still passes
116
+ * `checkFactory` against today's catalogue. Throws "FACTORY.md is unreadable: ..." like the parse.
117
+ */
118
+ export function validateFactoryState(state, catalog) {
119
+ const bad = (what) => { throw new Error(`FACTORY.md is unreadable: ${what}`); };
120
+ for (const k of ['transitions', 'runTransitions', 'runCeiling', 'taskHigh']) {
121
+ if (!count(state[k])) bad(`${k} must be a non-negative integer`);
122
+ }
123
+ if (state.runCeiling > FACTORY_MAX_TRANSITIONS * FACTORY_MAX_TASKS) {
124
+ bad(`runCeiling must be ${FACTORY_MAX_TRANSITIONS * FACTORY_MAX_TASKS} at most`);
125
+ }
126
+ if (!plainObject(state.counters) || !Object.values(state.counters).every(count)) {
127
+ bad('counters must map each cycle to a non-negative integer');
128
+ }
129
+ const { taskCount, tasks, launched } = state;
130
+ if (taskCount !== null && !(Number.isInteger(taskCount) && taskCount >= 1 && taskCount <= FACTORY_MAX_TASKS)) {
131
+ bad(`taskCount must be null or an integer from 1 to ${FACTORY_MAX_TASKS}`);
132
+ }
133
+ if (tasks !== null && !(plainObject(tasks) && SPEC_PATH.test(tasks.path) && Number.isInteger(tasks.count)
134
+ && tasks.count >= 1 && tasks.count <= (taskCount ?? 0) && Number.isInteger(tasks.index) && tasks.index >= 1
135
+ && tasks.index <= tasks.count && (tasks.stage === null || typeof tasks.stage === 'string'))) {
136
+ bad('tasks must be null or a spec path with 1 <= index <= count <= taskCount');
137
+ }
138
+ if (launched != null && !(plainObject(launched) && typeof launched.stage === 'string'
139
+ && typeof launched.template === 'string' && (launched.head === null || typeof launched.head === 'string')
140
+ && (launched.at == null || typeof launched.at === 'string'))) {
141
+ bad('launched must be null or a stage, a template, a head and a time');
142
+ }
143
+ if (!STATUSES.includes(state.status)) bad(`status must be one of ${STATUSES.join(', ')}`);
144
+ if (!Array.isArray(state.history)) bad('history must be a list');
145
+ if (!plainObject(state.gateAmends) || !Object.values(state.gateAmends).every((n) => count(n) && n <= GATE_MAX_AMENDS)) {
146
+ bad(`gateAmends must map each gate to an integer from 0 to ${GATE_MAX_AMENDS}`);
147
+ }
148
+ // `cycles` may be absent (`transition` reads it `?? []`), never another shape: `checkFactory`
149
+ // reads a non-list as no cycles, and `transition` would then throw iterating it.
150
+ if (plainObject(state.factory) && state.factory.cycles !== undefined && !Array.isArray(state.factory.cycles)) {
151
+ bad('factory.cycles must be a list');
152
+ }
153
+ const problems = checkFactory(state.factory, catalog);
154
+ if (problems.length) bad(`its factory no longer passes factory check: ${problems.join('; ')}`);
155
+ // absent in a state written before lanes existed: that reads as none on record
156
+ if (state.lane != null && !laneTargets(state.factory, catalog.bricks).has(state.lane)) {
157
+ bad('lane must be null or a stage a fork of the factory leads to');
158
+ }
159
+ }
160
+
161
+ /** `<file>.tmp` then `renameWithRetry`, as `writeLoopFile`: a killed write never tears FACTORY.md. */
162
+ export function writeFactoryFile(file, state) {
163
+ const tmp = `${file}.tmp`;
164
+ writeText(tmp, renderFactoryFile(state));
165
+ renameWithRetry(tmp, file);
166
+ }
167
+
168
+ /**
169
+ * The tasks of a spec (`specs/<slug>/spec.md`, the `spec` brick's format): the top-level numbered
170
+ * items (`1.` or `1)`, indented 3 spaces at most) under the first heading that names tasks, up to
171
+ * the next heading of the same or a higher level.
172
+ */
173
+ export function countSpecTasks(text) {
174
+ let level = 0; let count = 0;
175
+ for (const line of String(text).replace(/\r\n/g, '\n').split('\n')) {
176
+ const h = /^(#{1,6})\s+(.*)$/.exec(line);
177
+ if (h) {
178
+ if (level && h[1].length <= level) break;
179
+ if (!level && /\btasks?\b/i.test(h[2])) level = h[1].length;
180
+ continue;
181
+ }
182
+ if (level && /^ {0,3}\d+[.)]\s+\S/.test(line)) count += 1;
183
+ }
184
+ return count;
185
+ }
186
+
187
+ export function initFactory({ title, requirement, factory, input = null }) {
188
+ return {
189
+ v: 1, title, requirement, input, factory, stage: factory.start,
190
+ status: 'running', awaiting: null, reason: null,
191
+ counters: {}, transitions: 0, runTransitions: 0, runCeiling: FACTORY_MAX_TRANSITIONS, taskHigh: 0, taskCount: null,
192
+ lane: null, tasks: null, carry: null, launched: null,
193
+ history: [], gateAmends: {},
194
+ };
195
+ }
196
+
197
+ const taskNo = (state) => state.tasks?.index ?? 0;
198
+ // The task as `next` and a replay hand it out: the owning stage is the engine's bookkeeping.
199
+ const taskOut = ({ stage: _owner, ...task }) => task;
200
+
201
+ function stop(state, reason) {
202
+ state.status = 'stopped'; state.reason = reason;
203
+ return { stopped: reason };
204
+ }
205
+
206
+ const summary = (state) => ({ transitions: state.transitions, history: state.history });
207
+
208
+ function assertRunning(state) {
209
+ if (state.status !== 'running') throw new Error(`the factory is ${state.status}, not running`);
210
+ }
211
+
212
+ // R3: the child loop owns the worktree while its LOOP.md says neither `done` nor `stopped`.
213
+ // `loopStatus` is that status as the CLI read it, null when there is no LOOP.md; a LOOP.md that
214
+ // does not parse reaches here as running.
215
+ const ENDED = ['done', 'stopped'];
216
+ function assertNoLoop(loopStatus) {
217
+ if (loopStatus !== null && !ENDED.includes(loopStatus)) {
218
+ throw new Error('a loop is still running in this worktree (LOOP.md exists): finish it with '
219
+ + '`geneseed loop next` and its final commit before the factory moves on');
220
+ }
221
+ }
222
+
223
+ const rulesOf = (state) => (state.factory.rules?.length ? { rules: state.factory.rules } : {});
224
+
225
+ /**
226
+ * `loopStatus`: the status in the LOOP.md at the worktree root, or null (the CLI looks; this stays
227
+ * pure). A loop stage refuses ANY LOOP.md: `loop init` refuses to overwrite one, and a stopped
228
+ * loop leaves its own behind, tracked, so the error names the removal. On a loop stage it stores
229
+ * the launch with `head` (the HEAD commit, null when unreadable) and `at` (`now`, an ISO time the
230
+ * CLI passes; null leaves `pass` with no LOOP.md unprovable) — once per stage visit, so a second
231
+ * `next` after the loop committed does not move the baseline `record` compares with.
232
+ */
233
+ export function nextStage(state, { bricks }, { loopStatus = null, head = null, now = null } = {}) {
234
+ if (state.status === 'awaiting') return { awaiting: state.awaiting };
235
+ if (state.status === 'done') return { terminal: '$close', summary: summary(state) };
236
+ if (state.status === 'stopped') return { terminal: '$stop', reason: state.reason, summary: summary(state) };
237
+ assertNoLoop(loopStatus);
238
+ const { stage } = state;
239
+ const loop = loopOf(stage);
240
+ if (loop !== null) {
241
+ if (loopStatus !== null) {
242
+ throw new Error('the previous loop left its LOOP.md at the worktree root: run `git rm -f LOOP.md` and commit '
243
+ + `that removal before \`geneseed loop init\` starts ${stage}`);
244
+ }
245
+ const owned = state.tasks && (state.tasks.stage === null || state.tasks.stage === stage);
246
+ if (state.launched?.stage !== stage) state.launched = { stage, template: loop, head, at: now };
247
+ // J7: the owner, recorded since the spec, entered by an edge rather than its own replay, has
248
+ // passed its last task: this visit is one extra task, to fix what the stage before reported.
249
+ const last = state.history.at(-1);
250
+ const extra = owned && state.tasks.stage === stage && state.tasks.index === state.tasks.count && last?.stage !== stage
251
+ ? { extra: `${last.stage} reported ${last.outcome ?? last.verdict}` } : {};
252
+ return {
253
+ stage, loop, notes: state.carry ? [state.carry] : [],
254
+ ...(owned ? { task: { ...taskOut(state.tasks), ...extra } } : {}), ...rulesOf(state),
255
+ };
256
+ }
257
+ const brick = bricks.get(stage);
258
+ if (!brick) throw new Error(`no brick named ${stage} in the catalogue`);
259
+ return {
260
+ stage, effect: brick.effect, agent: brick.agent, skill: brick.skill, outcomes: brick.outcomes,
261
+ prompt: brick.body, requirement: state.requirement, input: state.input, carry: state.carry,
262
+ // D11: a fork picks from its own edges; the factory is their one writer, so the stage reads them here
263
+ ...(isFork(stage, bricks) ? { lanes: lanesOf(state.factory, stage) } : {}),
264
+ ...rulesOf(state),
265
+ };
266
+ }
267
+
268
+ // J5: the porcelain after a stage outside a loop, minus engine files and the run's spec — at the
269
+ // `spec` brick's own path only (one slug segment, never `.` or `..`).
270
+ const SPEC_PATH = /^specs\/(?!\.\.?\/)[^/]+\/spec\.md$/;
271
+ // R2: a loop init strictly after the launch; an absent or unparsable time on either side proves nothing.
272
+ const initedSince = (initAt, launchAt) => {
273
+ const a = Date.parse(initAt ?? ''); const b = Date.parse(launchAt ?? '');
274
+ return Number.isFinite(a) && Number.isFinite(b) && a > b;
275
+ };
276
+ function dirtyLines(porcelain, specPath) {
277
+ const exempt = specPath !== null && SPEC_PATH.test(specPath) ? specPath : null;
278
+ return filterPorcelain(porcelain).split('\n').filter((l) => l && slash(l.slice(3).replace(/^"|"$/g, '')) !== exempt);
279
+ }
280
+
281
+ /**
282
+ * Record the current stage's outcome and follow its edge. On a fork, the stage the outcome's edge
283
+ * reaches becomes the run's `lane`. `specPath`
284
+ * with `taskCount` (a stage that wrote a spec), `carry` (the reason the next stage — above all a
285
+ * re-entered loop — must hear). `loopTemplate` is the graph name in the LOOP.md the CLI read,
286
+ * `head` the HEAD commit now, `loopInitAt` the registry row's last `loop init` time for this
287
+ * worktree, or null (R2). Every refusal throws before the state changes.
288
+ */
289
+ export function recordStage(state, { bricks }, outcome, {
290
+ porcelain = null, specPath = null, taskCount = null, carry = null, loopStatus = null,
291
+ loopTemplate = null, head = null, loopInitAt = null,
292
+ } = {}) {
293
+ assertRunning(state);
294
+ assertNoLoop(loopStatus);
295
+ const from = state.stage;
296
+ const outcomes = stageOutcomes(from, bricks);
297
+ if (!outcomes) throw new Error(`no brick named ${from} in the catalogue`);
298
+ if (!outcomes.includes(outcome)) {
299
+ throw new Error(`${from} cannot report ${JSON.stringify(outcome)} — one of ${outcomes.join(', ')}`);
300
+ }
301
+ const isLoop = loopOf(from) !== null;
302
+ if (specPath !== null && isLoop) throw new Error('--spec is recorded by a stage outside a loop');
303
+ if (isLoop) {
304
+ // R2: the loop's evidence — its own LOOP.md, or the commit it closed with (docblock above).
305
+ const launch = state.launched;
306
+ if (launch?.stage !== from) throw new Error(`${from} was never launched: run \`geneseed factory next\` before its loop, then record`);
307
+ const said = { stopped: 'fail', done: 'pass' }[loopStatus];
308
+ if (said) {
309
+ if (loopTemplate !== launch.template) {
310
+ throw new Error(`the LOOP.md at the worktree root ran ${loopTemplate ?? 'an unnamed graph'}, not ${launch.template}: it is not ${from}'s loop`);
311
+ }
312
+ if (outcome !== said) {
313
+ throw new Error(`${from} cannot report ${outcome}: its LOOP.md says the loop ${loopStatus === 'done' ? 'is done' : 'stopped'} — report ${said}`);
314
+ }
315
+ } else if (head === null || head === launch.head) {
316
+ // shortcut: "moved" is "differs", not "descends from"; an fs-only reader cannot walk ancestry.
317
+ throw new Error(`${from} cannot report ${outcome}: no LOOP.md is left and HEAD has not moved since \`factory next\` — `
318
+ + 'record after the loop\'s close commit, or after the commit that removes a stopped loop\'s LOOP.md');
319
+ } else if (outcome === 'pass' && !initedSince(loopInitAt, launch.at)) {
320
+ throw new Error(`${from} cannot report pass on a HEAD move alone: no LOOP.md is left, and the loop registry `
321
+ + 'records no `geneseed loop init` in this worktree since `factory next` — report fail, or record pass '
322
+ + 'while the done LOOP.md is still at the root');
323
+ }
324
+ } else {
325
+ if (porcelain === null) {
326
+ throw new Error(`${from} is a stage outside a loop: pipe \`${PORCELAIN}\` into record, so the engine can see the tree is clean`);
327
+ }
328
+ const dirty = dirtyLines(porcelain, specPath ?? state.tasks?.path ?? null);
329
+ if (dirty.length) {
330
+ const folded = dirty.some((l) => /\/"?$/.test(l))
331
+ ? ` — a path ending in / is a whole untracked directory: pipe \`${PORCELAIN}\`, which lists each file` : '';
332
+ throw new Error(`${from} left the worktree dirty, and a stage outside a loop records only on a clean tree, so a brick `
333
+ + `that changes files commits them first: ${dirty.join('; ')}${folded}`);
334
+ }
335
+ }
336
+ const edge = state.factory.edges.find((e) => e.from === from && e.on === outcome)
337
+ ?? (outcome === 'error' ? { from, on: 'error', to: '$stop' } : null);
338
+ if (specPath !== null) {
339
+ if (!Number.isInteger(taskCount) || taskCount < 1) throw new Error(`${specPath} has no ordered task list under a Tasks heading`);
340
+ if (taskCount > FACTORY_MAX_TASKS) {
341
+ throw new Error(`${specPath} lists ${taskCount} tasks; a factory runs ${FACTORY_MAX_TASKS} at most — split the requirement`);
342
+ }
343
+ if (state.taskCount !== null && taskCount > state.taskCount) {
344
+ throw new Error(`${specPath} lists ${taskCount} tasks, more than the ${state.taskCount} frozen at the first --spec record`);
345
+ }
346
+ }
347
+ if (!edge) throw new Error(`no edge from ${from} on ${outcome}`);
348
+ assertLane(state, edge);
349
+
350
+ if (isFork(from, bricks) && state.factory.stages.includes(edge.to)) state.lane = edge.to;
351
+ if (isLoop) state.launched = null;
352
+ if (specPath !== null) {
353
+ if (state.taskCount === null) { state.taskCount = taskCount; state.runCeiling = FACTORY_MAX_TRANSITIONS * taskCount; }
354
+ state.tasks = { path: specPath, count: taskCount, index: 1, stage: null };
355
+ state.taskHigh = Math.max(state.taskHigh, 1);
356
+ }
357
+ if (isLoop && state.tasks && state.tasks.stage === null) state.tasks.stage = from;
358
+ state.carry = carry || null;
359
+ state.history.push({
360
+ stage: from, outcome, task: taskNo(state), ...(carry ? { carry } : {}),
361
+ });
362
+ const brick = isLoop ? null : bricks.get(from);
363
+ if (brick?.gate === 'human' && (!brick.gateOn || brick.gateOn.includes(outcome))) {
364
+ state.status = 'awaiting';
365
+ state.awaiting = { kind: 'gate', stage: from, outcome, ...(carry ? { note: carry } : {}) };
366
+ return { awaiting: state.awaiting };
367
+ }
368
+ // D9: a passed task replays the same loop stage for the next one; only a task never reached
369
+ // before gets fresh budgets (J6), so a re-recorded spec cannot reset its way into a lap forever.
370
+ if (isLoop && outcome === 'pass' && state.tasks?.stage === from && state.tasks.index < state.tasks.count) {
371
+ state.tasks.index += 1; state.carry = null;
372
+ if (state.tasks.index > state.taskHigh) {
373
+ state.taskHigh = state.tasks.index; state.counters = {}; state.transitions = 0;
374
+ }
375
+ return { stage: from, task: taskOut(state.tasks) };
376
+ }
377
+ return transition(state, from, edge, bricks);
378
+ }
379
+
380
+ // D13: an edge to `$lane` needs a lane on record; checked before any state changes.
381
+ function assertLane(state, edge) {
382
+ if (edge.to === LANE && state.lane == null) {
383
+ throw new Error(`${edge.from} routes to ${LANE}, but no fork has chosen a lane in this run`);
384
+ }
385
+ }
386
+
387
+ function transition(state, from, edge, bricks) {
388
+ if (edge.to === '$stop') return stop(state, `${from} reported ${edge.on}`);
389
+ if (edge.to === '$close') { state.status = 'done'; state.stage = '$close'; return { done: true }; }
390
+ state.transitions += 1; state.runTransitions += 1;
391
+ if (state.transitions > FACTORY_MAX_TRANSITIONS) return stop(state, `transition ceiling of ${FACTORY_MAX_TRANSITIONS} reached`);
392
+ if (state.runTransitions > state.runCeiling) {
393
+ return stop(state, `run-wide transition ceiling of ${state.runCeiling} reached (${FACTORY_MAX_TRANSITIONS} per task)`);
394
+ }
395
+ const cycle = spentCycle(state.factory.cycles ?? [], from, edge.to, laneTargets(state.factory, bricks));
396
+ if (cycle) {
397
+ state.counters[cycle.name] = (state.counters[cycle.name] ?? 0) + 1;
398
+ if (state.counters[cycle.name] > cycle.max) return stop(state, `cycle ${cycle.name} exhausted its max of ${cycle.max}`);
399
+ }
400
+ const to = edge.to === LANE ? state.lane : edge.to;
401
+ state.stage = to;
402
+ return { stage: to };
403
+ }
404
+
405
+ /**
406
+ * The answer to a held `gate: human` stage (D14: the loop engine's gate and verdicts, reused).
407
+ * `ok` follows the held edge; `no` stops; `amend` re-runs the stage with the note as its `carry`,
408
+ * `GATE_MAX_AMENDS` times per stage per task.
409
+ */
410
+ export function decideFactory(state, { bricks }, verdict, note = '') {
411
+ if (state.status !== 'awaiting') throw new Error('nothing is awaiting a decision');
412
+ if (!['ok', 'no', 'amend'].includes(verdict)) throw new Error(`verdict must be ok, no or amend, not ${JSON.stringify(verdict)}`);
413
+ const { stage, outcome } = state.awaiting;
414
+ const edge = state.factory.edges.find((e) => e.from === stage && e.on === outcome) ?? { from: stage, on: outcome, to: '$stop' };
415
+ if (verdict === 'ok') assertLane(state, edge);
416
+ state.awaiting = null; state.status = 'running';
417
+ state.history.push({ stage, verdict, task: taskNo(state), ...(note ? { note } : {}) });
418
+ if (verdict === 'no') return stop(state, `gate rejected at ${stage}${note ? `: ${note}` : ''}`);
419
+ if (verdict === 'amend') {
420
+ const key = `${stage}@${taskNo(state)}`;
421
+ // Checked before the count moves, so a stored count never passes the cap R4 holds it to.
422
+ const spent = state.gateAmends?.[key] ?? 0;
423
+ if (spent >= GATE_MAX_AMENDS) return stop(state, `gate amended ${GATE_MAX_AMENDS} times at ${stage}`);
424
+ state.gateAmends = { ...state.gateAmends, [key]: spent + 1 };
425
+ state.stage = stage; state.carry = note || null;
426
+ return { resumed: true };
427
+ }
428
+ return transition(state, stage, edge, bricks);
429
+ }
@@ -10,9 +10,9 @@
10
10
  * (`normalizeEntry` never returns them).
11
11
  *
12
12
  * NOT A NEW HOOK ON EVERY TOOL CALL. `bin/geneseed-hook.mjs` calls `recordActivity` after the verb
13
- * the host ran anyway has decided (the gates, `context`, `learn`), plus the `activity` verb for
14
- * the events no other verb is wired to (UserPromptSubmit, SessionEnd, SubagentStart). So a Claude
15
- * session's live phase moves only on the gated tools (`Bash|PowerShell`, `Write|Edit|NotebookEdit`,
13
+ * the host ran anyway has decided (the gates, `context` on SessionStart and SubagentStart, `learn`),
14
+ * plus the `activity` verb for the events no other verb is wired to (UserPromptSubmit, SessionEnd).
15
+ * So a Claude session's live phase moves only on the gated tools (`Bash|PowerShell`, `Write|Edit|NotebookEdit`,
16
16
  * `Skill|Agent|Task`); the rest of the turn's tool calls arrive at Stop, read out of the
17
17
  * transcript from a stored byte offset (`readTranscriptDelta`). Bob sends no `transcript_path`,
18
18
  * so a Bob session shows only what its matcher-less `tool-gate` sees, call by call.
@@ -27,7 +27,7 @@ import { gitRootOf } from './gitref.mjs';
27
27
  * `!bricks/`. The same string lives in `adapters/opencode/plugins/geneseed-workflow.js`,
28
28
  * `adapters/opencode/workflows/_runtime.js` and `src/skills/_checkpoints.md`; tests pin them.
29
29
  */
30
- export const GENESEED_GITIGNORE = '/*\n!/.gitignore\n!/bricks/\n!/loops/\n!/protected-checks.txt\n!/done-checks.txt\n';
30
+ export const GENESEED_GITIGNORE = '/*\n!/.gitignore\n!/bricks/\n!/loops/\n!/factories/\n!/protected-checks.txt\n!/done-checks.txt\n';
31
31
 
32
32
  /**
33
33
  * Create-if-absent; a file holding only `*` is Geneseed's former output (it hid team bricks),
@@ -96,6 +96,27 @@ export function currentBranch(cwd) {
96
96
  }
97
97
  }
98
98
 
99
+ /**
100
+ * The commit HEAD names in `root`, read without spawning git: a detached sha as it stands, else
101
+ * the branch ref — loose in the SHARED gitdir (a linked worktree's private gitdir holds only its
102
+ * HEAD), then `packed-refs`. null on anything else: an unborn branch, a reftable repository, no
103
+ * repo. The factory engine compares it before and after a child loop (`js/factory/state.mjs`, R2).
104
+ */
105
+ export function headCommit(root) {
106
+ try {
107
+ const head = readFileSync(path.join(gitDirOf(root), 'HEAD'), 'utf8').trim();
108
+ if (/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(head)) return head;
109
+ const ref = /^ref:\s*(refs\/heads\/\S+)$/.exec(head)?.[1];
110
+ if (!ref) return null;
111
+ const common = gitCommonDirOf(root);
112
+ try { return readFileSync(path.join(common, ref), 'utf8').trim(); } catch { /* packed, or unborn */ }
113
+ const packed = readFileSync(path.join(common, 'packed-refs'), 'utf8');
114
+ return packed.split(/\r?\n/).map((l) => l.split(' ')).find(([, name]) => name === ref)?.[0] ?? null;
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+
99
120
  /**
100
121
  * The SHARED `.git` directory for `root`: the gitdir itself in a main worktree, the one its
101
122
  * `commondir` names in a linked worktree. Refs under `refs/remotes/`, `refs/stash` and
@@ -410,10 +410,10 @@ function sessionEntry(rel, abs, text, label) {
410
410
  * A missing or unreadable file is simply absent — this is best-effort context, never a gate.
411
411
  * `host` is what the emitted hook passes (`emittedHost`), null for none, which reads as claude.
412
412
  */
413
- export function sessionFiles(hookRoot, host = null, carrier = installCarrier(hookRoot, host)) {
413
+ export function sessionFiles(hookRoot, host = null, carrier = installCarrier(hookRoot, host), rels = SESSION_FILES) {
414
414
  const tier = readsTier(hookRoot, host) || projectReadsTier(carrier);
415
415
  const found = [];
416
- for (const rel of SESSION_FILES) {
416
+ for (const rel of rels) {
417
417
  const wiki = rel === 'geneseed-wiki.jsonc';
418
418
  const pinned = wiki && process.env.GENESEED_WIKI && isFile(process.env.GENESEED_WIKI);
419
419
  const hostAbs = pinned ? process.env.GENESEED_WIKI
@@ -676,7 +676,12 @@ const installCarrier = (hookRoot, host) => installCarrierFile(hookRoot, host)[1]
676
676
  * instead of injected; a lazy listing shortened is not, since it only names files. `heads` are the
677
677
  * lines above the session block; `root` places `eager` and `lazy`. Reads, never prints.
678
678
  */
679
- function renderPayload({ heads, session, eager, lazy, source, root }) {
679
+ const SESSION_TITLE = '=== SESSION FILES — your harness files, injected at session start '
680
+ + '(untouched seeds skipped) ===';
681
+ // The sub-agent's banner (`subagentRules`): the user's rules alone, under their own title.
682
+ export const USER_RULES_TITLE = '=== USER RULES — the user\'s standing rules; obey them as you obey the Dictates ===';
683
+
684
+ function renderPayload({ heads, session, eager, lazy, source, root, title = SESSION_TITLE, budget = OUTPUT_BUDGET }) {
680
685
  const lines = [];
681
686
  // `spent` counts every character pushed, headers included: the budget is the host's cap on
682
687
  // the whole payload, not on the file bodies alone.
@@ -685,8 +690,7 @@ function renderPayload({ heads, session, eager, lazy, source, root }) {
685
690
  const push = (...ls) => { for (const l of ls) { lines.push(l); spent += cost(l); } };
686
691
  if (heads.length) push(...heads, '');
687
692
  if (session.length) {
688
- push('=== SESSION FILES \u2014 your harness files, injected at session start '
689
- + '(untouched seeds skipped) ===', '');
693
+ push(title, '');
690
694
  // Rules answer only to their own size: the lines above them never push one out, so they are
691
695
  // capped when their layers together pass the share, and everything after them spends `spent`.
692
696
  let rulesSpent = 0;
@@ -694,7 +698,7 @@ function renderPayload({ heads, session, eager, lazy, source, root }) {
694
698
  for (const s of session) {
695
699
  const head = `----- ${s.rel}${s.label ? ` (${s.label})` : ''} -----`;
696
700
  const rules = s.rel === 'user-rules.md';
697
- const room = OUTPUT_BUDGET - LAZY_RESERVE - (rules ? rulesSpent : spent) - cost(head) - cost('');
701
+ const room = budget - LAZY_RESERVE - (rules ? rulesSpent : spent) - cost(head) - cost('');
698
702
  const where = `${s.abs} on demand`;
699
703
  if (room <= 0) {
700
704
  left.push({ rel: s.rel, line: `[context] ${s.rel} not injected (session budget) \u2014 read ${where}` });
@@ -708,7 +712,7 @@ function renderPayload({ heads, session, eager, lazy, source, root }) {
708
712
  // Paths have no length limit, so these lines answer to the budget like any listing.
709
713
  if (left.length) {
710
714
  cut = true;
711
- const room = OUTPUT_BUDGET - LIST_RESERVE - spent - cost('');
715
+ const room = budget - LIST_RESERVE - spent - cost('');
712
716
  const tail = (n) => `[context] ${n} more session files not injected (session budget)`;
713
717
  // The memory map first, and by its short name when its path cannot fit: a count line must
714
718
  // never replace the one file C12 owes a line that names it.
@@ -739,7 +743,7 @@ function renderPayload({ heads, session, eager, lazy, source, root }) {
739
743
  push(head, `[context] MISSING eager file: ${asOsError(e, target)}`, '');
740
744
  continue;
741
745
  }
742
- if (spent + cost(head) + cost(text) + cost('') > OUTPUT_BUDGET - LAZY_RESERVE) {
746
+ if (spent + cost(head) + cost(text) + cost('') > budget - LAZY_RESERVE) {
743
747
  demoted.push({ ...entry, over: true });
744
748
  continue;
745
749
  }
@@ -749,7 +753,7 @@ function renderPayload({ heads, session, eager, lazy, source, root }) {
749
753
  if (lazy.length || demoted.length) {
750
754
  const title = '--- Lazy entries (load only when the task needs them) ---';
751
755
  push(title);
752
- push(...lazyLines([...lazy, ...demoted], root, OUTPUT_BUDGET - spent - cost('')), '');
756
+ push(...lazyLines([...lazy, ...demoted], root, budget - spent - cost('')), '');
753
757
  }
754
758
  return { text: `${lines.join('\n')}\n`, spent, cut: cut || demoted.length > 0 };
755
759
  }
@@ -769,6 +773,51 @@ export function sessionStartSize(hookRoot, host) {
769
773
  return { chars: spent, budget: OUTPUT_BUDGET, cut };
770
774
  }
771
775
 
776
+ /**
777
+ * The user-rules layers a sub-agent gets, in SessionStart's order and under its labels: the tier
778
+ * and the install, then the project root's own `user-rules.md`, each file once. Only these files
779
+ * are read: a sub-agent start must not pay for the profile, the memory map or a wiki walk. The
780
+ * project root is `root`, the same `$GENESEED_ROOT || $CLAUDE_PROJECT_DIR || cwd` SessionStart
781
+ * discovers from, and its file is read directly, as discovery's root entry: a `context.json` that
782
+ * names it lazy or leaves it out does not keep it from a sub-agent.
783
+ */
784
+ export function userRuleLayers(root, hookRoot, host) {
785
+ const rules = hookRoot ? sessionFiles(hookRoot, host, installCarrier(hookRoot, host), ['user-rules.md']) : [];
786
+ const abs = root ? path.join(root, 'user-rules.md') : null;
787
+ if (abs && !rules.some((s) => normcase(path.resolve(s.abs)) === normcase(path.resolve(abs)))) {
788
+ const text = sessionText(abs);
789
+ if (text !== null) rules.push({ rel: disp(abs, root), abs, label: '', text });
790
+ }
791
+ return rules;
792
+ }
793
+
794
+ /**
795
+ * A sub-agent's start (`SubagentStart`): no host hands a sub-agent the SessionStart output, so the
796
+ * user's rules reach it here, and nothing else (spec 2026-11-08, D4): not the profile, not the
797
+ * project context, which the root file already brings. Same renderer and same cut as SessionStart.
798
+ * Claude Code documents only the JSON form for this event, so the payload is ONE JSON object on
799
+ * stdout, and the budget holds for that line, not for the text inside it: `JSON.stringify` adds a
800
+ * character per `"`, `\` and line break, so a render whose line runs over is redone with the budget
801
+ * scaled by how far over it ran (each pass shrinks it, so a few converge). No rule anywhere prints
802
+ * nothing, as an empty SessionStart does.
803
+ */
804
+ function subagentRules(root, hookRoot, host) {
805
+ const rules = userRuleLayers(root, hookRoot, host);
806
+ if (!rules.length) return 0;
807
+ let budget = OUTPUT_BUDGET;
808
+ for (let pass = 0; pass < 6; pass += 1) {
809
+ const { text } = renderPayload({ heads: [], session: rules, eager: [], lazy: [], source: '', root, title: USER_RULES_TITLE, budget });
810
+ const line = JSON.stringify({ hookSpecificOutput: { hookEventName: 'SubagentStart', additionalContext: text } });
811
+ if (line.length + 2 <= OUTPUT_BUDGET) {
812
+ out(`${line}\n`);
813
+ return 0;
814
+ }
815
+ // Scaled, not cut by the overrun: a budget unit of escape-heavy text serializes to two or more.
816
+ budget = Math.min(budget - 1, Math.floor((budget * OUTPUT_BUDGET) / (line.length + 2)));
817
+ }
818
+ return 0; // never converged: nothing, rather than a payload the host would cut
819
+ }
820
+
772
821
  export function cmdContext(args) {
773
822
  const host = (args && args.host) || null;
774
823
  // Discovery (and the stand-down) runs against the SESSION's project root, not the harness
@@ -793,6 +842,11 @@ export function cmdContext(args) {
793
842
  // The RAW `args.host`, never defaulted to claude, which would key an older
794
843
  // OpenClaude emit's `~/.openclaude` (no `--host`) on `.claude` instead of its folder name.
795
844
  if (globalHookStandingDown(hookRoot, root, args.host, 'context')) return 0;
845
+ // A sub-agent starts without its rules rather than without its Activity record: a throw here
846
+ // would exit 1 and skip `trackActivity` (spec 2026-11-08, failure table).
847
+ if (args.event === 'SubagentStart') {
848
+ try { return subagentRules(root, hookRoot, host); } catch { return 0; }
849
+ }
796
850
  const [carrierFile, carrier] = hookRoot ? installCarrierFile(hookRoot, host) : ['', ''];
797
851
  const session = hookRoot ? sessionFiles(hookRoot, host, carrier) : [];
798
852
  // A session file discovery would also pick up (a `user-rules.md` at the repo root of an
@@ -493,7 +493,7 @@ export function activityOn(root) {
493
493
 
494
494
  /**
495
495
  * The `activity` verb, wired to the events no other verb runs on (UserPromptSubmit; SessionEnd
496
- * and SubagentStart on Claude and OpenClaude). It decides nothing and prints nothing: the entry's
496
+ * on Claude and OpenClaude; SubagentStart runs `context` since the agent loadout). It decides nothing and prints nothing: the entry's
497
497
  * `trackActivity` records the payload after every verb alike, this one included.
498
498
  */
499
499
  export const cmdActivity = () => 0;
@@ -952,10 +952,11 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
952
952
  // user's prompt, and the `activity` verb decides nothing.
953
953
  UserPromptSubmit: [{ hooks: [{ type: 'command', command: activity }] }],
954
954
  SessionEnd: [{ hooks: [{ type: 'command', command: activity }] }],
955
- // A sub-agent's branch at launch (the Activity garden): a read-only sub-agent fires no gated
956
- // hook, so without this it would never appear. Never on Bob (the early return above): Bob's
957
- // hook schema is strict, and one unknown event key drops its whole hooks block.
958
- SubagentStart: [{ hooks: [{ type: 'command', command: activity }] }],
955
+ // A sub-agent's start: `context` reads the event name and injects the user's rules, which no
956
+ // sub-agent gets from SessionStart (spec 2026-11-08, agent loadout). The Activity garden's
957
+ // branch at launch still records, since `trackActivity` runs after every verb. Never on Bob
958
+ // (the early return above): its schema is strict, one unknown event key drops the whole block.
959
+ SubagentStart: [{ hooks: [{ type: 'command', command: context }] }],
959
960
  };
960
961
  // Claude Code only: OpenClaude always runs Git Bash on Windows (its `findGitBashPath` exits
961
962
  // without one), and Bob takes the early return above.