geneseed 5.0.1 → 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 (185) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +4 -4
  3. package/SHIPPED.md +2 -2
  4. package/adapters/claude-code/README.md +11 -5
  5. package/adapters/openclaude/README.md +3 -1
  6. package/adapters/opencode/HOW-OPENCODE-LOADS.md +3 -0
  7. package/adapters/opencode/plugins/geneseed-context.js +12 -1
  8. package/adapters/opencode/plugins/geneseed-guard.js +594 -73
  9. package/adapters/opencode/plugins/geneseed-learn.js +1 -1
  10. package/adapters/opencode/plugins/geneseed-workflow.js +1 -1
  11. package/adapters/opencode/workflows/_runtime.js +1 -1
  12. package/bin/geneseed-cli.mjs +3 -0
  13. package/bin/geneseed-hook.mjs +31 -9
  14. package/docs/PRD.md +1 -1
  15. package/docs/README.md +4 -1
  16. package/docs/concepts/enforcement-table.md +23 -4
  17. package/docs/concepts/exclusions.md +48 -2
  18. package/docs/concepts/factories.md +151 -0
  19. package/docs/concepts/foreman-mode.md +19 -4
  20. package/docs/concepts/hook-gates.md +1 -1
  21. package/docs/concepts/hooks.md +53 -12
  22. package/docs/concepts/host-matrix.md +5 -3
  23. package/docs/concepts/hosts.md +1 -1
  24. package/docs/concepts/kits.md +18 -0
  25. package/docs/concepts/loop-gates.md +3 -0
  26. package/docs/concepts/loops.md +1 -0
  27. package/docs/concepts/rules.md +1 -1
  28. package/docs/concepts/shared-tier.md +1 -1
  29. package/docs/concepts/skills.md +1 -1
  30. package/docs/extending.md +8 -2
  31. package/docs/guides/autostart.md +29 -3
  32. package/docs/guides/choose-your-setup.md +1 -1
  33. package/docs/guides/migrate.md +1 -1
  34. package/docs/guides/run-a-factory.md +88 -0
  35. package/docs/guides/set-up-ownership.md +1 -0
  36. package/docs/guides/uninstall.md +1 -1
  37. package/docs/reference/factory-actions.md +22 -0
  38. package/docs/reference/loop-actions.md +1 -1
  39. package/docs/reference/plugin-activity.md +1 -1
  40. package/docs/reference/plugin-context.md +1 -1
  41. package/docs/reference/plugin-guard.md +24 -5
  42. package/docs/reference/troubleshoot-doctor.md +2 -2
  43. package/docs/understand/a-day.md +9 -5
  44. package/docs/web-ui.md +101 -17
  45. package/harness.config.json +1 -1
  46. package/js/README.md +21 -3
  47. package/js/build/args.mjs +14 -2
  48. package/js/build/emit-claude.mjs +9 -1
  49. package/js/build/emit-opencode.mjs +2 -1
  50. package/js/build/source.mjs +28 -3
  51. package/js/cli-table.json +287 -3
  52. package/js/factory/cli.mjs +153 -0
  53. package/js/factory/graph.mjs +245 -0
  54. package/js/factory/registry.mjs +71 -0
  55. package/js/factory/state.mjs +429 -0
  56. package/js/hosts/activity.mjs +3 -3
  57. package/js/hosts/geneseed-dir.mjs +2 -2
  58. package/js/hosts/gitref.mjs +21 -0
  59. package/js/hosts/hooks-context.mjs +71 -15
  60. package/js/hosts/hooks-done.mjs +3 -1
  61. package/js/hosts/hooks-learn.mjs +1 -1
  62. package/js/hosts/hooks-prims.mjs +271 -1
  63. package/js/hosts/hooks.mjs +409 -151
  64. package/js/hosts/hosts.mjs +22 -0
  65. package/js/hosts/installs.mjs +9 -5
  66. package/js/hosts/settings.mjs +128 -27
  67. package/js/hosts/shim.mjs +155 -7
  68. package/js/hosts/store-watch.mjs +36 -11
  69. package/js/inspect/checks-authoring.mjs +11 -1
  70. package/js/inspect/cost.mjs +91 -5
  71. package/js/inspect/diff.mjs +2 -1
  72. package/js/inspect/doctor.mjs +2 -1
  73. package/js/inspect/inventory.mjs +2 -1
  74. package/js/inspect/validate.mjs +1 -1
  75. package/js/loop/catalog.mjs +24 -12
  76. package/js/loop/cli.mjs +21 -15
  77. package/js/loop/graph.mjs +13 -4
  78. package/js/loop/registry.mjs +65 -28
  79. package/js/loop/state.mjs +18 -8
  80. package/js/maintain/migrate.mjs +2 -2
  81. package/js/maintain/uninstall.mjs +5 -1
  82. package/js/web/actions.mjs +17 -1
  83. package/js/web/api.mjs +52 -11
  84. package/js/web/catalog.mjs +38 -2
  85. package/js/web/daemon.mjs +136 -6
  86. package/js/web/handler.mjs +14 -5
  87. package/js/web/routes.mjs +12 -4
  88. package/js/web/server.mjs +4 -1
  89. package/package.json +1 -1
  90. package/registry.json +35 -0
  91. package/src/AGENT.md.tmpl +18 -24
  92. package/src/agents/_self-improvement.md +7 -6
  93. package/src/agents/developer.md +3 -2
  94. package/src/agents/docker-expert.md +1 -0
  95. package/src/agents/memory-curator.md +3 -2
  96. package/src/bricks/docs-update.md +5 -0
  97. package/src/bricks/holdout-write.md +23 -0
  98. package/src/bricks/holdout.md +25 -0
  99. package/src/bricks/intake.md +18 -0
  100. package/src/bricks/merge-gate.md +22 -0
  101. package/src/bricks/pr-open.md +21 -0
  102. package/src/bricks/retro.md +17 -0
  103. package/src/bricks/test.md +4 -1
  104. package/src/bricks/triage.md +19 -0
  105. package/src/doctrines/comms.md +29 -41
  106. package/src/doctrines/craft.md +3 -10
  107. package/src/doctrines/ops.md +4 -15
  108. package/src/doctrines/process.md +24 -19
  109. package/src/doctrines/rigor.md +1 -5
  110. package/src/factories/analysis-to-build.json +34 -0
  111. package/src/factories/bug-report-to-fix.json +32 -0
  112. package/src/factories/issue-to-pr.json +49 -0
  113. package/src/kits/ci-pipelines/rules.md +10 -0
  114. package/src/kits/ci-pipelines.json +14 -0
  115. package/src/kits/docker/rules.md +11 -0
  116. package/src/kits/docker.json +12 -0
  117. package/src/memory/README.md +5 -4
  118. package/src/modes/foreman.md +23 -10
  119. package/src/notebook/README.md +1 -1
  120. package/src/skills/_checkpoints.md +1 -0
  121. package/src/skills/_self-improvement.md +12 -9
  122. package/src/skills/adhd.md +1 -1
  123. package/src/skills/compose-ops.md +58 -0
  124. package/src/skills/factory-forge.md +97 -0
  125. package/src/skills/factory.md +126 -0
  126. package/src/skills/gitlab-ci.md +51 -0
  127. package/src/skills/jenkins-pipeline.md +56 -0
  128. package/src/skills/parallel-agents.md +1 -1
  129. package/src/skills/pipeline.md +2 -2
  130. package/src/skills/rule.md +24 -18
  131. package/src/skills/skill-forge.md +24 -6
  132. package/src/skills/workflow.md +2 -1
  133. package/themes/_TEMPLATE.json +9 -4
  134. package/themes/biker.json +9 -4
  135. package/themes/commentator.json +9 -4
  136. package/themes/cyberpunk.json +9 -4
  137. package/themes/gamer.json +9 -4
  138. package/themes/imperial.json +9 -4
  139. package/themes/joker.json +9 -4
  140. package/themes/marvin.json +9 -4
  141. package/themes/mean.json +9 -4
  142. package/themes/military.json +9 -4
  143. package/themes/neutral.json +9 -4
  144. package/themes/pirate.json +9 -4
  145. package/themes/sports.json +9 -4
  146. package/themes/verstappen.json +9 -4
  147. package/themes/wizard.json +9 -4
  148. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +1 -0
  149. package/web/dist/assets/Activity-BaoxwVFH.js +1 -0
  150. package/web/dist/assets/ActivityDetail-C_bFD0rW.js +1 -0
  151. package/web/dist/assets/{Bonsai-C1iBAt4v.js → Bonsai-B01lLf0m.js} +1 -1
  152. package/web/dist/assets/{CopyButton-DJ3a4N88.js → CopyButton-Bc66KPyA.js} +1 -1
  153. package/web/dist/assets/Dashboard-X7GZzGJp.js +2 -0
  154. package/web/dist/assets/{Docs-Kffdg5uV.js → Docs-LRYVnGLG.js} +3 -3
  155. package/web/dist/assets/Factories-ARenKBiP.js +1 -0
  156. package/web/dist/assets/{GreenhouseView-k56_cBSF.js → GreenhouseView-CfWR2-sX.js} +1 -1
  157. package/web/dist/assets/{Installs-DtEKLC9h.js → Installs-nfFHnovH.js} +3 -3
  158. package/web/dist/assets/{JournalView-RQnk5l7I.js → JournalView-lpOHcHKK.js} +1 -1
  159. package/web/dist/assets/Kits-Bw5EQl_i.js +1 -0
  160. package/web/dist/assets/Laws-CnZJ0wjZ.js +4 -0
  161. package/web/dist/assets/LibRows-Hqvf1beK.js +1 -0
  162. package/web/dist/assets/Library-JaSsp6Yr.js +3 -0
  163. package/web/dist/assets/Loops-ZaHC5MVl.js +2 -0
  164. package/web/dist/assets/{OperatorHudView-CM5jNPwL.js → OperatorHudView-CggG0_sK.js} +1 -1
  165. package/web/dist/assets/Personal-BObvlb70.js +2 -0
  166. package/web/dist/assets/Settings-BFfPMPc9.js +1 -0
  167. package/web/dist/assets/Tabs-B594Pad_.js +1 -0
  168. package/web/dist/assets/api-DLDVY3K-.js +1 -0
  169. package/web/dist/assets/index-DsLmKHw0.js +6 -0
  170. package/web/dist/assets/index-DvPjphz0.css +1 -0
  171. package/web/dist/index.html +3 -3
  172. package/web/dist/assets/Activity-Ci4PZco3.js +0 -1
  173. package/web/dist/assets/ActivityDetail-C8hroCND.js +0 -1
  174. package/web/dist/assets/Dashboard-C_On4KXw.js +0 -2
  175. package/web/dist/assets/Kits-CXkEBpnf.js +0 -1
  176. package/web/dist/assets/Laws-DhhIVqmh.js +0 -3
  177. package/web/dist/assets/Library-CAUiEoJo.js +0 -3
  178. package/web/dist/assets/Loops-LKD8mF4E.js +0 -2
  179. package/web/dist/assets/Personal-B6Uoly3C.js +0 -2
  180. package/web/dist/assets/RailCats-DQxxYBEP.js +0 -1
  181. package/web/dist/assets/Settings-BTe6-wda.js +0 -1
  182. package/web/dist/assets/Tabs-CbdDWTp_.js +0 -1
  183. package/web/dist/assets/api-D_r0Jtla.js +0 -1
  184. package/web/dist/assets/index-HfGmYXab.js +0 -3
  185. package/web/dist/assets/index-ao3M-Fhm.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),
@@ -53,7 +53,7 @@ const SEED_REL = '.geneseed/protected-checks.txt';
53
53
  * What a project's checks live in. A string ending `/` is a folder, any other string a file; a
54
54
  * regex matches file names at the root. Lockfiles are not listed: they move on every install.
55
55
  */
56
- const CANDIDATES = [
56
+ export const CANDIDATES = [
57
57
  '.github/workflows/', '.gitlab-ci.yml', 'Jenkinsfile', 'azure-pipelines.yml', '.circleci/',
58
58
  /^eslint\.config\./, /^\.eslintrc/, 'biome.json', 'biome.jsonc', 'tsconfig.json',
59
59
  /^jest\.config\./, /^vitest\.config\./, 'pytest.ini', 'ruff.toml', '.golangci.yml', 'checkstyle.xml',
@@ -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