geneseed 5.0.3 → 5.1.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 (141) hide show
  1. package/CHANGELOG.md +83 -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 +203 -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 +6 -0
  18. package/docs/concepts/loops.md +1 -0
  19. package/docs/concepts/rules.md +1 -1
  20. package/docs/concepts/shared-tier.md +14 -0
  21. package/docs/extending.md +5 -1
  22. package/docs/guides/autostart.md +2 -0
  23. package/docs/guides/migrate.md +1 -1
  24. package/docs/guides/run-a-factory.md +116 -0
  25. package/docs/guides/set-up-ownership.md +1 -0
  26. package/docs/guides/upgrade-to-5.md +2 -2
  27. package/docs/reference/factory-actions.md +22 -0
  28. package/docs/reference/loop-actions.md +1 -1
  29. package/docs/reference/plugin-activity.md +1 -1
  30. package/docs/web-ui.md +47 -2
  31. package/harness.config.json +1 -1
  32. package/js/README.md +21 -2
  33. package/js/build/args.mjs +44 -12
  34. package/js/build/emit-claude.mjs +3 -0
  35. package/js/build/emit-opencode.mjs +4 -0
  36. package/js/build/retired-skills.mjs +158 -0
  37. package/js/build/source.mjs +41 -2
  38. package/js/cli-table.json +193 -3
  39. package/js/factory/cli.mjs +194 -0
  40. package/js/factory/graph.mjs +309 -0
  41. package/js/factory/registry.mjs +71 -0
  42. package/js/factory/state.mjs +511 -0
  43. package/js/hosts/activity.mjs +3 -3
  44. package/js/hosts/done-checks.mjs +3 -2
  45. package/js/hosts/geneseed-dir.mjs +1 -1
  46. package/js/hosts/gitref.mjs +21 -0
  47. package/js/hosts/hooks-context.mjs +63 -9
  48. package/js/hosts/hooks-prims.mjs +1 -1
  49. package/js/hosts/memory-files.mjs +4 -2
  50. package/js/hosts/settings.mjs +5 -4
  51. package/js/inspect/checks-authoring.mjs +11 -1
  52. package/js/inspect/cost.mjs +91 -5
  53. package/js/inspect/doctor.mjs +2 -1
  54. package/js/inspect/inventory.mjs +1 -1
  55. package/js/loop/catalog.mjs +30 -12
  56. package/js/loop/cli.mjs +27 -15
  57. package/js/loop/graph.mjs +13 -4
  58. package/js/loop/registry.mjs +65 -28
  59. package/js/loop/state.mjs +18 -8
  60. package/js/maintain/migrate.mjs +39 -25
  61. package/js/web/api.mjs +43 -1
  62. package/js/web/catalog.mjs +38 -2
  63. package/js/web/daemon.mjs +191 -6
  64. package/js/web/handler.mjs +27 -5
  65. package/js/web/routes.mjs +10 -3
  66. package/js/web/server.mjs +4 -1
  67. package/package.json +1 -1
  68. package/registry.json +14 -0
  69. package/src/AGENT.md.tmpl +5 -7
  70. package/src/bricks/checks.md +62 -0
  71. package/src/bricks/docs-update.md +5 -0
  72. package/src/bricks/holdout-write.md +23 -0
  73. package/src/bricks/holdout.md +25 -0
  74. package/src/bricks/intake.md +27 -0
  75. package/src/bricks/merge-gate.md +31 -0
  76. package/src/bricks/pr-open.md +21 -0
  77. package/src/bricks/retro.md +22 -0
  78. package/src/bricks/review-panel.md +43 -0
  79. package/src/bricks/spec.md +20 -6
  80. package/src/bricks/test.md +4 -1
  81. package/src/bricks/triage.md +19 -0
  82. package/src/doctrines/comms.md +29 -41
  83. package/src/doctrines/craft.md +3 -10
  84. package/src/doctrines/ops.md +4 -15
  85. package/src/doctrines/rigor.md +1 -5
  86. package/src/factories/analysis-to-build.json +52 -0
  87. package/src/factories/bug-report-to-fix.json +50 -0
  88. package/src/factories/issue-to-pr.json +67 -0
  89. package/src/skills/_checkpoints.md +1 -0
  90. package/src/skills/adhd.md +1 -1
  91. package/src/skills/factory-forge.md +115 -0
  92. package/src/skills/factory.md +196 -0
  93. package/src/skills/loop.md +3 -2
  94. package/src/skills/parallel-agents.md +1 -1
  95. package/src/skills/workflow.md +2 -1
  96. package/themes/_TEMPLATE.json +4 -2
  97. package/themes/biker.json +4 -2
  98. package/themes/commentator.json +4 -2
  99. package/themes/cyberpunk.json +4 -2
  100. package/themes/gamer.json +4 -2
  101. package/themes/imperial.json +4 -2
  102. package/themes/joker.json +4 -2
  103. package/themes/marvin.json +4 -2
  104. package/themes/mean.json +4 -2
  105. package/themes/military.json +4 -2
  106. package/themes/neutral.json +4 -2
  107. package/themes/pirate.json +4 -2
  108. package/themes/sports.json +4 -2
  109. package/themes/verstappen.json +4 -2
  110. package/themes/wizard.json +4 -2
  111. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +1 -0
  112. package/web/dist/assets/{Activity-Ck_Xffpo.js → Activity-CpkBwpu7.js} +1 -1
  113. package/web/dist/assets/{ActivityDetail-CBxVS4mU.js → ActivityDetail-DTPziZWM.js} +1 -1
  114. package/web/dist/assets/{Bonsai-BlOwsvW6.js → Bonsai-hiG_gGNU.js} +1 -1
  115. package/web/dist/assets/{CopyButton-DFMOIGbe.js → CopyButton-DUIUfNp6.js} +1 -1
  116. package/web/dist/assets/Dashboard-Dnw6EyX7.js +2 -0
  117. package/web/dist/assets/{Docs-D_2Jt6gU.js → Docs-BEET_l16.js} +2 -2
  118. package/web/dist/assets/Factories-D6KXkfWw.js +1 -0
  119. package/web/dist/assets/{GreenhouseView-WalcX5bp.js → GreenhouseView-BKxy5apE.js} +1 -1
  120. package/web/dist/assets/{Installs-UGiPDMDt.js → Installs-CnFVlVD0.js} +3 -3
  121. package/web/dist/assets/{JournalView-CZtXQz-v.js → JournalView-ChFitHjo.js} +1 -1
  122. package/web/dist/assets/{Kits-XQHsazCN.js → Kits-CcR-OlwQ.js} +1 -1
  123. package/web/dist/assets/Laws-B1s5idOg.js +4 -0
  124. package/web/dist/assets/LibRows-BZgdbI1l.js +1 -0
  125. package/web/dist/assets/Library-x6TkkEVF.js +3 -0
  126. package/web/dist/assets/Loops-BH93KKxn.js +2 -0
  127. package/web/dist/assets/{OperatorHudView-CeDw5qMB.js → OperatorHudView-BO0aIKPL.js} +1 -1
  128. package/web/dist/assets/{Personal-PVmGA2-M.js → Personal-CE_0Vhh0.js} +2 -2
  129. package/web/dist/assets/{Settings-DWuxwh4i.js → Settings-CbpZvVN_.js} +1 -1
  130. package/web/dist/assets/{Tabs-d2RIRAKT.js → Tabs-C2oW7oEj.js} +1 -1
  131. package/web/dist/assets/api-DLDVY3K-.js +1 -0
  132. package/web/dist/assets/{index-BNttaGQb.js → index-BQwOmbor.js} +3 -3
  133. package/web/dist/assets/index-CuIop_pO.css +1 -0
  134. package/web/dist/index.html +3 -3
  135. package/web/dist/assets/Dashboard-BUdUTjbB.js +0 -2
  136. package/web/dist/assets/Laws-B6A55S-2.js +0 -4
  137. package/web/dist/assets/Library-D7L0Wdbh.js +0 -3
  138. package/web/dist/assets/Loops-C0loS73u.js +0 -2
  139. package/web/dist/assets/RailCats-BGZnJ6fa.js +0 -1
  140. package/web/dist/assets/api-BMFDSXoB.js +0 -1
  141. package/web/dist/assets/index-BEI5ugYQ.css +0 -1
@@ -0,0 +1,309 @@
1
+ /**
2
+ * The rules a factory graph must satisfy before a single stage runs: `geneseed factory check`,
3
+ * `factory init` (R7: an unknown factory or loop is refused before anything runs) and the doctor
4
+ * over the shipped factories all call `checkFactory`, so a graph the doctor never sees (a user's
5
+ * `.geneseed/factories/<name>.json`) meets the same rules.
6
+ *
7
+ * A FACTORY IS A LOOP GRAPH ONE LEVEL UP. A stage is a brick name or `loop:<template>` (a whole
8
+ * loop run as one stage, outcomes `pass` and `fail`: the loop closed or it stopped). A failure may
9
+ * route back to an earlier stage (D7), so the graph has cycles, and every cycle must sit inside a
10
+ * declared `cycles` entry with a `max`: the loop engine's own rule 4, reused (`undeclaredCycles`)
11
+ * rather than copied, so the two engines cannot drift on what "declared" means.
12
+ *
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
15
+ * outcome has its own edge (rule 3), so the edges out of a fork ARE its lanes: an outcome whose
16
+ * edge reaches a stage. An edge target or a cycle node may be `$lane`: the stage the run's most
17
+ * recent fork chose, which the engine records in FACTORY.md and resolves at runtime. Statically,
18
+ * `$lane` stands for EVERY lane of every fork (`laneTargets`): reachability, declared cycles and
19
+ * the lap rule all run over the edges with `$lane` expanded that way, an over-approximation, so a
20
+ * graph that passes holds for whichever lane a run takes. A cycle whose first stage is `$lane` is
21
+ * entered at any lane, and spent only by an edge whose literal target is `$lane` (`spentCycle`,
22
+ * which the engine calls too). Such an edge always revisits a stage: the lane is the first stage
23
+ * after its fork. The `loops` allowlist and `loop:$triaged` (D6) are retired: `check` names each
24
+ * with its replacement, and never rewrites a user's file (D15).
25
+ *
26
+ * `max` IS CAPPED AT 5. A factory cycle re-runs whole loops; five laps of "CI is red, fix it" is
27
+ * already a conversation for the user, not a loop, and the per-task ceiling of 60 transitions
28
+ * (`FACTORY_MAX_TRANSITIONS`, J3) sits on top of it.
29
+ *
30
+ * A CYCLE IS ENTERED AT ITS FIRST STAGE, AND EVERY LAP SPENDS ONE. The engine spends a cycle on an
31
+ * edge whose target is the cycle's `nodes[0]` and whose source the cycle holds (`transition`,
32
+ * `js/factory/state.mjs`). That counts laps right only when (a) every way into the cycle — an edge
33
+ * from a stage outside it, or `start` inside it — lands on `nodes[0]`, else the forward edge into
34
+ * `nodes[0]` spends on the first pass; and (b) with every spending edge removed the graph has no
35
+ * cycle left, else some lap (a route back into the middle of a cycle) spends nothing. The rule is
36
+ * topological, never read from the order of `stages`, which is authoring order. (b) runs only when
37
+ * every cycle is declared, so an undeclared one is reported once, not twice.
38
+ *
39
+ * Problems come in a fixed order (shape, stages, edges, outcomes, reachability, cycles,
40
+ * lanes, rules, protected paths, review seats, environment routes) so a test writes the expected list out instead of sorting it. A malformed
41
+ * `cycles` or `edges` entry (an edge needs a string `from`, `on` and `to`) is reported by the shape
42
+ * rule and left out of every later one: the doctor runs this over a user's file, and the engine
43
+ * over a FACTORY.md anyone can edit, so it must never throw.
44
+ */
45
+ import { undeclaredCycles } from '../loop/graph.mjs';
46
+
47
+ const TERMINALS = new Set(['$close', '$stop']);
48
+ export const LOOP_PREFIX = 'loop:';
49
+ /** An edge target or cycle node: the stage the run's most recent fork chose (D13). */
50
+ export const LANE = '$lane';
51
+ const RETIRED_TRIAGED = 'loop:$triaged';
52
+ export const FACTORY_MAX_CYCLE = 5;
53
+ /** What a `loop:` stage reports: its child loop reached `$close`, or it did not. */
54
+ export const LOOP_OUTCOMES = ['pass', 'fail'];
55
+ /**
56
+ * The outcomes that name no lane; any other declared outcome makes its brick a fork (D11).
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.
59
+ */
60
+ const NEEDS_INFO = 'needs-info';
61
+ const PLAIN_OUTCOMES = new Set(['pass', 'fail', 'error', 'none', NEEDS_INFO]);
62
+ /** The work item sizes `intake` rates; `review.seats` needs a list for each (rule 9). */
63
+ const SEAT_SIZES = ['small', 'medium', 'large'];
64
+ /**
65
+ * The outcome on which a shipped brick reports an environment failure (a failed fetch, a missing
66
+ * tool, a timeout, CI pending at the bound): its body says so, and `factory_graph.test.mjs` holds
67
+ * the two in step. Rule 10 refuses a route from it to a loop, which could only spend laps on it.
68
+ */
69
+ export const ENV_OUTCOMES = Object.freeze({ checks: 'error', 'merge-gate': 'none' });
70
+ const plainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
71
+ const edgeShaped = (e) => ['from', 'on', 'to'].every((k) => typeof e?.[k] === 'string');
72
+
73
+ /**
74
+ * 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.
77
+ */
78
+ export function edgeFor(factory, from, outcome) {
79
+ const own = (on) => (Array.isArray(factory?.edges) ? factory.edges : []).find((e) => e?.from === from && e.on === on);
80
+ return own(outcome) ?? (outcome === NEEDS_INFO ? own('pass') : undefined)
81
+ ?? (outcome === 'error' ? { from, on: 'error', to: '$stop' } : null);
82
+ }
83
+
84
+ /** The template a `loop:` stage names, or null for a brick stage. */
85
+ export function loopOf(stage) {
86
+ return typeof stage === 'string' && stage.startsWith(LOOP_PREFIX) ? stage.slice(LOOP_PREFIX.length) : null;
87
+ }
88
+
89
+ /** A stage's declared outcomes, or null when it names nothing the catalogue holds. */
90
+ export function stageOutcomes(stage, bricks) {
91
+ if (loopOf(stage) !== null) return LOOP_OUTCOMES;
92
+ return bricks.get(stage)?.outcomes ?? null;
93
+ }
94
+
95
+ /** A fork: a brick stage that declares a named outcome, one outside pass, fail, error and none. */
96
+ export function isFork(stage, bricks) {
97
+ return loopOf(stage) === null && (bricks.get(stage)?.outcomes ?? []).some((o) => !PLAIN_OUTCOMES.has(o));
98
+ }
99
+
100
+ /** A fork's lanes: each outcome whose edge reaches a stage, mapped to that stage. Never throws. */
101
+ export function lanesOf(factory, stage) {
102
+ const stages = new Set(Array.isArray(factory?.stages) ? factory.stages : []);
103
+ const edges = Array.isArray(factory?.edges) ? factory.edges.filter(edgeShaped) : [];
104
+ return Object.fromEntries(edges.filter((e) => e.from === stage && stages.has(e.to)).map((e) => [e.on, e.to]));
105
+ }
106
+
107
+ /** Every stage a fork of `factory` leads to: what `$lane` may resolve to. Never throws. */
108
+ export function laneTargets(factory, bricks) {
109
+ const stages = Array.isArray(factory?.stages) ? factory.stages : [];
110
+ return new Set(stages.filter((s) => isFork(s, bricks)).flatMap((s) => Object.values(lanesOf(factory, s))));
111
+ }
112
+
113
+ /**
114
+ * The cycle an edge spends: the smallest whose first stage is the edge's literal target (`$lane`
115
+ * unresolved) and which holds its source — a `$lane` node holds every lane. One rule for `check`
116
+ * and the engine, so the two cannot disagree on which edge pays for a lap.
117
+ */
118
+ export function spentCycle(cycles, from, to, lanes) {
119
+ let best = null;
120
+ for (const c of cycles) {
121
+ if (!Array.isArray(c?.nodes) || c.nodes[0] !== to) continue;
122
+ if (!c.nodes.includes(from) && !(c.nodes.includes(LANE) && lanes.has(from))) continue;
123
+ if (!best || c.nodes.length < best.nodes.length) best = c;
124
+ }
125
+ return best;
126
+ }
127
+
128
+ /** The stages and terminals reachable from `startStage`, never entering a stage in `skip`. */
129
+ export const reachable = (startStage, edges, stageSet, skip = new Set()) => {
130
+ const seen = new Set([startStage]); const queue = [startStage];
131
+ while (queue.length) {
132
+ const v = queue.shift();
133
+ for (const e of edges) {
134
+ if (e.from !== v || seen.has(e.to) || skip.has(e.to)) continue;
135
+ seen.add(e.to);
136
+ if (stageSet.has(e.to)) queue.push(e.to);
137
+ }
138
+ }
139
+ return seen;
140
+ };
141
+
142
+ /**
143
+ * Rule 9: the review panel's seat table — a non-empty list per size, an optional list per area,
144
+ * every seat a shipped agent. No `agents` in the catalogue reads as none shipped: closed, not open.
145
+ */
146
+ function seatProblems(review, agents) {
147
+ const seats = plainObject(review) ? review.seats : undefined;
148
+ if (!plainObject(seats)) return ['review: must be an object with a seats table'];
149
+ const out = [];
150
+ const lists = SEAT_SIZES.map((s) => [s, seats[s]]);
151
+ if (seats.areas !== undefined) {
152
+ if (plainObject(seats.areas)) lists.push(...Object.entries(seats.areas).map(([a, l]) => [`areas.${a}`, l]));
153
+ else out.push('review.seats.areas: must map each area to a list of agents');
154
+ }
155
+ for (const [where, list] of lists) {
156
+ if (!Array.isArray(list) || !list.length || !list.every((a) => typeof a === 'string')) {
157
+ out.push(`review.seats.${where}: must be a non-empty list of agent names`);
158
+ continue;
159
+ }
160
+ for (const a of list) if (!agents.has(a)) out.push(`review.seats.${where}: no agent named ${a}`);
161
+ }
162
+ return out;
163
+ }
164
+
165
+ export function checkFactory(factory, { bricks, templates, agents }) {
166
+ if (!factory || typeof factory !== 'object' || Array.isArray(factory)) return ['factory: must be an object'];
167
+ const problems = [];
168
+ const stages = Array.isArray(factory.stages) ? factory.stages : [];
169
+ const allEdges = Array.isArray(factory.edges) ? factory.edges : [];
170
+ const allCycles = Array.isArray(factory.cycles) ? factory.cycles : [];
171
+ const stageSet = new Set(stages);
172
+
173
+ // rule 0 — the shape every later rule assumes
174
+ if (typeof factory.name !== 'string' || !factory.name.trim()) problems.push('name: must be a non-empty string');
175
+ const shaped = (c) => typeof c?.name === 'string' && Array.isArray(c.nodes);
176
+ allCycles.forEach((c, i) => {
177
+ if (!shaped(c)) problems.push(`cycles: entry ${i + 1} must have a string name and a list of nodes`);
178
+ });
179
+ const cycles = allCycles.filter(shaped);
180
+ allEdges.forEach((e, i) => {
181
+ if (!edgeShaped(e)) problems.push(`edges: entry ${i + 1} must have a string from, on and to`);
182
+ });
183
+ const edges = allEdges.filter(edgeShaped);
184
+ for (const s of new Set(stages.filter((s, i) => stages.indexOf(s) !== i))) problems.push(`stages: ${s} is listed twice`);
185
+
186
+ // rule 1 — a stage is an available brick or an existing loop template
187
+ for (const s of stages) {
188
+ if (s === RETIRED_TRIAGED) {
189
+ problems.push(`stage ${s}: retired — list each loop as its own stage, one fork edge per lane `
190
+ + `(triage --bug--> loop:bugfix), and route back to ${LANE}`);
191
+ continue;
192
+ }
193
+ const loop = loopOf(s);
194
+ if (loop !== null) {
195
+ if (!templates.has(loop)) problems.push(`stage ${s}: no loop template named ${loop}`);
196
+ continue;
197
+ }
198
+ const brick = bricks.get(s);
199
+ if (!brick) problems.push(`stage ${s}: no brick named ${s}`);
200
+ else if (!brick.available) problems.push(`stage ${s}: brick unavailable (${brick.reason})`);
201
+ }
202
+ // rule 2 — edge endpoints, and edges use declared outcomes
203
+ for (const e of edges) {
204
+ const label = `edge ${e.from} --${e.on}--> ${e.to}`;
205
+ if (!stageSet.has(e.from)) { problems.push(`${label}: ${e.from} is not a stage`); continue; }
206
+ if (!stageSet.has(e.to) && !TERMINALS.has(e.to) && e.to !== LANE) {
207
+ problems.push(`${label}: ${e.to} is not a stage, $close or $stop`);
208
+ continue;
209
+ }
210
+ const outcomes = stageOutcomes(e.from, bricks);
211
+ if (outcomes && !outcomes.includes(e.on)) problems.push(`${label}: ${e.on} is not an outcome of ${e.from}`);
212
+ }
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`),
215
+ // so a factory written before intake could ask stays valid, and so does a FACTORY.md that embeds one
216
+ for (const s of [...stages].sort()) {
217
+ for (const o of stageOutcomes(s, bricks) ?? []) {
218
+ 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'));
220
+ if (count === 0 && !exempt) problems.push(`stage ${s}: no edge for outcome ${o}`);
221
+ else if (count > 1) problems.push(`stage ${s}: ${count} edges for outcome ${o}`);
222
+ }
223
+ }
224
+ // Rules 4 and 5 read `$lane` as every lane of every fork (module docblock).
225
+ const lanes = laneTargets({ stages, edges }, bricks);
226
+ const expand = (e) => (e.to === LANE ? [...lanes].map((to) => ({ ...e, to })) : [e]);
227
+ const xnodes = (c) => c.nodes.flatMap((n) => (n === LANE ? [...lanes] : [n]));
228
+ const flat = edges.flatMap(expand);
229
+ // rule 4 — start, and $close reachable
230
+ if (!stageSet.has(factory.start)) problems.push(`start ${factory.start} is not a stage`);
231
+ else if (!reachable(factory.start, flat, stageSet).has('$close')) problems.push(`$close is not reachable from ${factory.start}`);
232
+ // rule 5 — cycles are well formed, and every cycle in the graph is declared
233
+ for (const c of cycles) {
234
+ if (!Number.isInteger(c.max) || c.max < 1 || c.max > FACTORY_MAX_CYCLE) {
235
+ problems.push(`cycle ${c.name}: max must be an integer from 1 to ${FACTORY_MAX_CYCLE}`);
236
+ }
237
+ for (const s of c.nodes) if (s !== LANE && !stageSet.has(s)) problems.push(`cycle ${c.name}: ${s} is not a stage`);
238
+ }
239
+ const undeclared = undeclaredCycles(stages, flat, cycles.map((c) => ({ ...c, nodes: xnodes(c) })));
240
+ for (const cycle of undeclared) problems.push(`cycle ${cycle} has no declared cycle around it`);
241
+ const inGraph = (e) => stageSet.has(e.from) && stageSet.has(e.to);
242
+ for (const c of cycles) {
243
+ // a `$lane` cycle with no fork behind it is rule 6's to report
244
+ if (c.nodes[0] === LANE && !lanes.size) continue;
245
+ const inside = new Set(xnodes(c));
246
+ const firsts = c.nodes[0] === LANE ? lanes : new Set([c.nodes[0]]);
247
+ const entries = new Set(flat.filter((e) => inGraph(e) && !inside.has(e.from) && inside.has(e.to)).map((e) => e.to));
248
+ if (inside.has(factory.start)) entries.add(factory.start);
249
+ for (const at of entries) {
250
+ if (!firsts.has(at)) problems.push(`cycle ${c.name}: entered at ${at}, not at its first stage ${c.nodes[0]}`);
251
+ }
252
+ }
253
+ if (!undeclared.length) {
254
+ const unspent = edges.filter((e) => !spentCycle(cycles, e.from, e.to, lanes)).flatMap(expand).filter(inGraph);
255
+ for (const lap of undeclaredCycles(stages, unspent, [])) {
256
+ problems.push(`cycle ${lap} laps without spending a declared cycle: `
257
+ + 'a route back must target the first stage of a declared cycle that holds its source');
258
+ }
259
+ }
260
+ // rule 6 — lanes: the retired allowlist, and a `$lane` only where a fork has chosen one
261
+ if (factory.loops !== undefined) problems.push('loops: retired — the lanes are the edges out of a fork (triage --bug--> loop:bugfix)');
262
+ const toLane = edges.filter((e) => e.to === LANE);
263
+ const forks = stages.filter((s) => isFork(s, bricks));
264
+ if ((toLane.length || cycles.some((c) => c.nodes.includes(LANE))) && !forks.length) {
265
+ problems.push(`${LANE}: no fork chooses a lane — a fork is a brick stage with a named outcome (triage --bug--> loop:bugfix)`);
266
+ } else if (forks.length) {
267
+ for (const e of toLane) {
268
+ if (forks.includes(e.from)) problems.push(`edge ${e.from} --${e.on}--> ${LANE}: a fork's edge names its lane, never ${LANE}`);
269
+ }
270
+ // Literal edges: past an unresolved `$lane` nothing is reachable, so it is reported once.
271
+ if (stageSet.has(factory.start) && !forks.includes(factory.start)) {
272
+ const before = reachable(factory.start, edges, stageSet, new Set(forks));
273
+ for (const e of toLane) {
274
+ if (before.has(e.from)) problems.push(`edge ${e.from} --${e.on}--> ${LANE}: reachable from ${factory.start} before any fork has chosen a lane`);
275
+ }
276
+ }
277
+ }
278
+ // rule 7 — the optional instruction list every stage receives through `factory next`
279
+ const { rules } = factory;
280
+ if (rules !== undefined && !(Array.isArray(rules) && rules.every((r) => typeof r === 'string' && r.trim()))) {
281
+ problems.push('rules: must be a list of non-empty strings');
282
+ }
283
+ // rule 8 — the paths `checks` refuses to see changed, beyond its own fixed list
284
+ const locked = factory.protected;
285
+ if (locked !== undefined && !(Array.isArray(locked) && locked.every((p) => typeof p === 'string' && p.trim()))) {
286
+ problems.push('protected: must be a list of non-empty paths');
287
+ }
288
+ // rule 9 — the `review-panel` seat table
289
+ if (factory.review !== undefined) problems.push(...seatProblems(factory.review, agents ?? new Set()));
290
+ // rule 10 — an outcome that carries environment failures never routes to a loop (M9)
291
+ for (const e of edges) {
292
+ if (ENV_OUTCOMES[e.from] === e.on && (loopOf(e.to) !== null || e.to === LANE)) {
293
+ problems.push(`edge ${e.from} --${e.on}--> ${e.to}: ${e.from} reports environment failures on ${e.on}, which no loop can fix — route it on or to $stop`);
294
+ }
295
+ }
296
+ return problems;
297
+ }
298
+
299
+ /**
300
+ * Every factory in the catalogue, checked and prefixed `factories/<name>: `, after the parse
301
+ * problems `loadCatalog` collected — the factory twin of `catalogProblems`, sorted the same way.
302
+ */
303
+ export function factoryCatalogProblems(catalog) {
304
+ const out = [...catalog.factoryProblems];
305
+ for (const [name, factory] of catalog.factories) {
306
+ out.push(...checkFactory(factory, catalog).map((p) => `factories/${name}: ${p}`));
307
+ }
308
+ return out.sort();
309
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The factory registry — `factories.json`, beside `loops.json` in `userLoopsDir()` — the list of
3
+ * worktrees `geneseed factory init` has started a run in (J9). FACTORY.md stays the only source of
4
+ * run STATE; this file stores identity only (root, branch, factory, title, started, finishedAt),
5
+ * so the console can find a run without scanning every worktree on the machine.
6
+ *
7
+ * EVERY CONVENTION IS THE LOOP REGISTRY'S, and so is the code (`js/loop/registry.mjs`: `loadRows`,
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.
11
+ *
12
+ * THE ROOT IS THE JOIN KEY. A child loop runs in the factory's own worktree, so its `loops.json`
13
+ * row has the same root, and carries `factory: <slug>` (`loop init --factory`). A reader groups a
14
+ * loop under its run by root; the slug is a label, never parsed back into a path.
15
+ */
16
+ import path from 'node:path';
17
+
18
+ import { userLoopsDir } from '../loop/catalog.mjs';
19
+ import { loadRows, saveRows, sweepRows, normalize, sameRoot } from '../loop/registry.mjs';
20
+ import { FACTORY_FILE, parseFactoryFile } from './state.mjs';
21
+
22
+ export function factoryRegistryPath() {
23
+ return path.join(userLoopsDir(), 'factories.json');
24
+ }
25
+
26
+ const load = () => loadRows(factoryRegistryPath(), 'factories');
27
+ const save = (rows) => saveRows(factoryRegistryPath(), 'factories', rows);
28
+
29
+ /**
30
+ * Upsert `root`'s row, `factory` being the factory's name. `started` is set once, on insert; a
31
+ * later init in the same worktree (a new run: `init` refuses while a FACTORY.md exists) updates
32
+ * the rest. Never throws: an init must succeed even when the registry cannot be written.
33
+ */
34
+ export function recordFactory({ root, branch, factory, title, now = new Date() }) {
35
+ try {
36
+ const key = normalize(root);
37
+ const rows = load();
38
+ const idx = rows.findIndex((r) => sameRoot(r.root, key));
39
+ if (idx >= 0) rows[idx] = { ...rows[idx], root: key, branch, factory, title };
40
+ else rows.push({ root: key, branch, factory, title, started: now.toISOString() });
41
+ save(rows);
42
+ } catch {
43
+ /* a registry hiccup must never fail factory init */
44
+ }
45
+ }
46
+
47
+ const identity = (e) => ({ root: e.root, branch: e.branch, factory: e.factory, title: e.title, started: e.started });
48
+
49
+ function runningRow(entry, state) {
50
+ return {
51
+ ...identity(entry), status: state.status, stage: state.stage, awaiting: state.awaiting,
52
+ reason: state.reason, transitions: state.transitions, counters: state.counters,
53
+ lane: state.lane ?? null, tasks: state.tasks, history: state.history,
54
+ // The graph the run was started from, as the loop row carries its `graph`: the console draws
55
+ // it, and a run started in another project names a factory this install may not have.
56
+ graph: state.factory,
57
+ };
58
+ }
59
+
60
+ /**
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.
64
+ */
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);
70
+ return rows;
71
+ }