geneseed 5.0.4 → 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 (69) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/SHIPPED.md +1 -1
  3. package/docs/concepts/exclusions.md +1 -1
  4. package/docs/concepts/factories.md +67 -15
  5. package/docs/concepts/loop-gates.md +5 -2
  6. package/docs/concepts/shared-tier.md +14 -0
  7. package/docs/extending.md +1 -1
  8. package/docs/guides/migrate.md +1 -1
  9. package/docs/guides/run-a-factory.md +41 -13
  10. package/docs/guides/upgrade-to-5.md +2 -2
  11. package/docs/reference/factory-actions.md +7 -7
  12. package/docs/web-ui.md +18 -6
  13. package/harness.config.json +1 -1
  14. package/js/README.md +2 -1
  15. package/js/build/args.mjs +34 -14
  16. package/js/build/emit-claude.mjs +3 -0
  17. package/js/build/emit-opencode.mjs +4 -0
  18. package/js/build/retired-skills.mjs +158 -0
  19. package/js/build/source.mjs +31 -11
  20. package/js/cli-table.json +29 -3
  21. package/js/factory/cli.mjs +49 -8
  22. package/js/factory/graph.mjs +72 -8
  23. package/js/factory/state.mjs +109 -27
  24. package/js/hosts/done-checks.mjs +3 -2
  25. package/js/hosts/memory-files.mjs +4 -2
  26. package/js/loop/catalog.mjs +16 -10
  27. package/js/loop/cli.mjs +16 -10
  28. package/js/maintain/migrate.mjs +39 -25
  29. package/js/web/daemon.mjs +69 -14
  30. package/js/web/handler.mjs +22 -9
  31. package/package.json +1 -1
  32. package/src/bricks/checks.md +62 -0
  33. package/src/bricks/intake.md +15 -6
  34. package/src/bricks/merge-gate.md +17 -8
  35. package/src/bricks/retro.md +8 -3
  36. package/src/bricks/review-panel.md +43 -0
  37. package/src/bricks/spec.md +20 -6
  38. package/src/factories/analysis-to-build.json +25 -7
  39. package/src/factories/bug-report-to-fix.json +25 -7
  40. package/src/factories/issue-to-pr.json +29 -11
  41. package/src/skills/factory-forge.md +23 -5
  42. package/src/skills/factory.md +95 -25
  43. package/src/skills/loop.md +3 -2
  44. package/themes/_TEMPLATE.json +1 -1
  45. package/web/dist/assets/{Activity-BaoxwVFH.js → Activity-CpkBwpu7.js} +1 -1
  46. package/web/dist/assets/{ActivityDetail-C_bFD0rW.js → ActivityDetail-DTPziZWM.js} +1 -1
  47. package/web/dist/assets/{Bonsai-B01lLf0m.js → Bonsai-hiG_gGNU.js} +1 -1
  48. package/web/dist/assets/{CopyButton-Bc66KPyA.js → CopyButton-DUIUfNp6.js} +1 -1
  49. package/web/dist/assets/{Dashboard-X7GZzGJp.js → Dashboard-Dnw6EyX7.js} +2 -2
  50. package/web/dist/assets/{Docs-LRYVnGLG.js → Docs-BEET_l16.js} +1 -1
  51. package/web/dist/assets/Factories-D6KXkfWw.js +1 -0
  52. package/web/dist/assets/{GreenhouseView-CfWR2-sX.js → GreenhouseView-BKxy5apE.js} +1 -1
  53. package/web/dist/assets/{Installs-nfFHnovH.js → Installs-CnFVlVD0.js} +1 -1
  54. package/web/dist/assets/{JournalView-lpOHcHKK.js → JournalView-ChFitHjo.js} +1 -1
  55. package/web/dist/assets/{Kits-Bw5EQl_i.js → Kits-CcR-OlwQ.js} +1 -1
  56. package/web/dist/assets/{Laws-CnZJ0wjZ.js → Laws-B1s5idOg.js} +1 -1
  57. package/web/dist/assets/LibRows-BZgdbI1l.js +1 -0
  58. package/web/dist/assets/Library-x6TkkEVF.js +3 -0
  59. package/web/dist/assets/{Loops-ZaHC5MVl.js → Loops-BH93KKxn.js} +1 -1
  60. package/web/dist/assets/{OperatorHudView-CggG0_sK.js → OperatorHudView-BO0aIKPL.js} +1 -1
  61. package/web/dist/assets/{Personal-BObvlb70.js → Personal-CE_0Vhh0.js} +1 -1
  62. package/web/dist/assets/{Settings-BFfPMPc9.js → Settings-CbpZvVN_.js} +1 -1
  63. package/web/dist/assets/{Tabs-B594Pad_.js → Tabs-C2oW7oEj.js} +1 -1
  64. package/web/dist/assets/{index-DsLmKHw0.js → index-BQwOmbor.js} +2 -2
  65. package/web/dist/assets/{index-DvPjphz0.css → index-CuIop_pO.css} +1 -1
  66. package/web/dist/index.html +2 -2
  67. package/web/dist/assets/Factories-ARenKBiP.js +0 -1
  68. package/web/dist/assets/LibRows-Hqvf1beK.js +0 -1
  69. package/web/dist/assets/Library-JaSsp6Yr.js +0 -3
@@ -11,7 +11,7 @@
11
11
  * rather than copied, so the two engines cannot drift on what "declared" means.
12
12
  *
13
13
  * FORKS AND `$lane` (D11, D13). A fork is a brick stage that declares an outcome other than
14
- * `pass`, `fail`, `error` or `none` — a named outcome, such as `triage`'s `bug` or `docs`. Each
14
+ * `pass`, `fail`, `error`, `none` or `needs-info` — a named outcome, such as `triage`'s `bug` or `docs`. Each
15
15
  * outcome has its own edge (rule 3), so the edges out of a fork ARE its lanes: an outcome whose
16
16
  * edge reaches a stage. An edge target or a cycle node may be `$lane`: the stage the run's most
17
17
  * recent fork chose, which the engine records in FACTORY.md and resolves at runtime. Statically,
@@ -24,7 +24,7 @@
24
24
  * with its replacement, and never rewrites a user's file (D15).
25
25
  *
26
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 run-wide ceiling of 30 transitions
27
+ * already a conversation for the user, not a loop, and the per-task ceiling of 60 transitions
28
28
  * (`FACTORY_MAX_TRANSITIONS`, J3) sits on top of it.
29
29
  *
30
30
  * A CYCLE IS ENTERED AT ITS FIRST STAGE, AND EVERY LAP SPENDS ONE. The engine spends a cycle on an
@@ -37,7 +37,7 @@
37
37
  * every cycle is declared, so an undeclared one is reported once, not twice.
38
38
  *
39
39
  * Problems come in a fixed order (shape, stages, edges, outcomes, reachability, cycles,
40
- * lanes, rules) so a test writes the expected list out instead of sorting it. A malformed
40
+ * lanes, rules, protected paths, review seats, environment routes) so a test writes the expected list out instead of sorting it. A malformed
41
41
  * `cycles` or `edges` entry (an edge needs a string `from`, `on` and `to`) is reported by the shape
42
42
  * rule and left out of every later one: the doctor runs this over a user's file, and the engine
43
43
  * over a FACTORY.md anyone can edit, so it must never throw.
@@ -52,10 +52,35 @@ const RETIRED_TRIAGED = 'loop:$triaged';
52
52
  export const FACTORY_MAX_CYCLE = 5;
53
53
  /** What a `loop:` stage reports: its child loop reached `$close`, or it did not. */
54
54
  export const LOOP_OUTCOMES = ['pass', 'fail'];
55
- /** The outcomes that name no lane; any other declared outcome makes its brick a fork (D11). */
56
- const PLAIN_OUTCOMES = new Set(['pass', 'fail', 'error', 'none']);
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);
57
71
  const edgeShaped = (e) => ['from', 'on', 'to'].every((k) => typeof e?.[k] === 'string');
58
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
+
59
84
  /** The template a `loop:` stage names, or null for a brick stage. */
60
85
  export function loopOf(stage) {
61
86
  return typeof stage === 'string' && stage.startsWith(LOOP_PREFIX) ? stage.slice(LOOP_PREFIX.length) : null;
@@ -114,7 +139,30 @@ export const reachable = (startStage, edges, stageSet, skip = new Set()) => {
114
139
  return seen;
115
140
  };
116
141
 
117
- export function checkFactory(factory, { bricks, templates }) {
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 }) {
118
166
  if (!factory || typeof factory !== 'object' || Array.isArray(factory)) return ['factory: must be an object'];
119
167
  const problems = [];
120
168
  const stages = Array.isArray(factory.stages) ? factory.stages : [];
@@ -162,11 +210,14 @@ export function checkFactory(factory, { bricks, templates }) {
162
210
  const outcomes = stageOutcomes(e.from, bricks);
163
211
  if (outcomes && !outcomes.includes(e.on)) problems.push(`${label}: ${e.on} is not an outcome of ${e.from}`);
164
212
  }
165
- // rule 3 — exactly one edge per outcome; `error` may go without one (the engine routes it to $stop)
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
166
216
  for (const s of [...stages].sort()) {
167
217
  for (const o of stageOutcomes(s, bricks) ?? []) {
168
218
  const count = edges.filter((e) => e.from === s && e.on === o).length;
169
- if (count === 0 && o !== 'error') problems.push(`stage ${s}: no edge for outcome ${o}`);
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}`);
170
221
  else if (count > 1) problems.push(`stage ${s}: ${count} edges for outcome ${o}`);
171
222
  }
172
223
  }
@@ -229,6 +280,19 @@ export function checkFactory(factory, { bricks, templates }) {
229
280
  if (rules !== undefined && !(Array.isArray(rules) && rules.every((r) => typeof r === 'string' && r.trim()))) {
230
281
  problems.push('rules: must be a list of non-empty strings');
231
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
+ }
232
296
  return problems;
233
297
  }
234
298
 
@@ -24,7 +24,8 @@
24
24
  * record: it is uncommitted until the gate approves it, and the Rite commits it then, before the
25
25
  * first loop, whose first read brick would stop on it otherwise) — instead of carrying
26
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
27
+ * `git status --porcelain --untracked-files=all`: plain `--porcelain` folds a new directory into `?? specs/`, which no exemption can match.
28
+ * A path git C-quotes (a non-ASCII slug, under the default core.quotePath) is unquoted first (M11). No porcelain
28
29
  * at all (`null`, a TTY stdin) is refused too: it proves nothing. The limit: an empty pipe reads
29
30
  * as a clean tree, so the engine trusts whoever pipes it.
30
31
  *
@@ -42,9 +43,10 @@
42
43
  * re-entered loop would never pass.
43
44
  *
44
45
  * 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
+ * that are not non-negative integers, a ceiling above 1200, a task block out of its bounds, a gate
46
47
  * 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
+ * write, a `stage`, `tasks.stage`, `launched.stage` or `awaiting` gate the graph does not hold,
49
+ * an `awaiting` that disagrees with `status`, a `history` or `factory.cycles` that is not a list, and a factory that no longer passes
48
50
  * `checkFactory` — the termination argument below holds only for a state this engine could have
49
51
  * written.
50
52
  *
@@ -68,20 +70,26 @@
68
70
  * TERMINATION BY CONSTRUCTION (J3, R8). `transitions` counts per task and resets with it. On top,
69
71
  * `runTransitions` counts every transition of the run, never resets, and stops the run past
70
72
  * `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
73
+ * `FACTORY_MAX_TRANSITIONS` x its task count. Until the first task loop launches, each --spec
74
+ * record sets the count and the ceiling again: the spec's gate comes after its record, and an amend
75
+ * there may add tasks (G3). That window spends no fresh budget — no task has been reached, so the
76
+ * per-task count never resets in it — and the gate's amend cap bounds it. Once a task loop has
77
+ * launched (`launched` with a spec on record, or a `loop:` stage in `history` recorded with a
78
+ * task, which never shrinks; a loop that ran before any spec owns no task, F2) the count is frozen:
79
+ * a later --spec record may keep or lower it, never raise it, so no lap can buy a task, a fresh
80
+ * budget or a higher ceiling. And it is capped at `FACTORY_MAX_TASKS` (20), so the
81
+ * ceiling is at most 1200 transitions: past twenty tasks a requirement is a project, to be split
75
82
  * into several factory runs a human can review, not one run nobody reads to the end.
76
83
  */
77
84
  import { writeText } from '../lib/fs.mjs';
78
85
  import { renameWithRetry, filterPorcelain } from '../loop/state.mjs';
79
- import { loopOf, stageOutcomes, checkFactory, LANE, isFork, lanesOf, laneTargets, spentCycle } from './graph.mjs';
86
+ import { loopOf, stageOutcomes, checkFactory, LANE, isFork, lanesOf, laneTargets, spentCycle, edgeFor } from './graph.mjs';
80
87
 
81
88
  const BEGIN = '<!-- factory-state:begin -->';
82
89
  const END = '<!-- factory-state:end -->';
83
90
  export const FACTORY_FILE = 'FACTORY.md';
84
- export const FACTORY_MAX_TRANSITIONS = 30;
91
+ // 60, not 30: `checks` and `review-panel` add two stages, and a lap back through both, to every factory (D15).
92
+ export const FACTORY_MAX_TRANSITIONS = 60;
85
93
  export const FACTORY_MAX_TASKS = 20;
86
94
  const GATE_MAX_AMENDS = 3;
87
95
  const STATUSES = ['running', 'awaiting', 'done', 'stopped'];
@@ -152,6 +160,23 @@ export function validateFactoryState(state, catalog) {
152
160
  }
153
161
  const problems = checkFactory(state.factory, catalog);
154
162
  if (problems.length) bad(`its factory no longer passes factory check: ${problems.join('; ')}`);
163
+ // M5: every stage the state names is one of the graph's, so no action meets a stage it cannot run
164
+ const stages = new Set(state.factory.stages);
165
+ if (!(stages.has(state.stage) || (state.stage === '$close' && state.status === 'done'))) {
166
+ bad('stage must be a stage of the factory');
167
+ }
168
+ if (tasks?.stage != null && !(stages.has(tasks.stage) && loopOf(tasks.stage) !== null)) {
169
+ bad('tasks.stage must be null or a loop stage of the factory');
170
+ }
171
+ if (launched != null && !(stages.has(launched.stage) && loopOf(launched.stage) === launched.template)) {
172
+ bad('launched.stage must be a loop stage of the factory, and launched.template its loop');
173
+ }
174
+ const { awaiting } = state;
175
+ if ((state.status === 'awaiting') !== (awaiting != null)) bad('awaiting must be set when, and only when, status is awaiting');
176
+ if (awaiting != null && !(plainObject(awaiting) && awaiting.kind === 'gate' && stages.has(awaiting.stage)
177
+ && (stageOutcomes(awaiting.stage, catalog.bricks) ?? []).includes(awaiting.outcome))) {
178
+ bad('awaiting must be a gate at a stage of the factory, with one of its outcomes');
179
+ }
155
180
  // absent in a state written before lanes existed: that reads as none on record
156
181
  if (state.lane != null && !laneTargets(state.factory, catalog.bricks).has(state.lane)) {
157
182
  bad('lane must be null or a stage a fork of the factory leads to');
@@ -166,20 +191,47 @@ export function writeFactoryFile(file, state) {
166
191
  }
167
192
 
168
193
  /**
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.
194
+ * The tasks of a spec (`specs/<slug>/spec.md`, the `spec` brick's format): the numbered items
195
+ * (`1.` or `1)`, indented 3 spaces at most) under the first heading that names tasks, up to the
196
+ * next heading of the same or a higher level. A numbered line is a sub-item, as CommonMark nests
197
+ * it, only when its indent reaches the content offset of the task before it (that task's indent,
198
+ * its marker, one space): `1. a` / ` 2. b` and `9. a` / `10. b` / ` 11. c` are siblings,
199
+ * `1. a` / ` 1. b` nest. Any line indented that far belongs to the task (its paragraphs, even
200
+ * after a blank line, and a `---` or `##` of its own), so it never ends the list. Headings are ATX (`#`,
201
+ * indented 3 spaces at most) and setext (a paragraph line underlined with `=` or `-`; under a
202
+ * list item's own text that line is a thematic break, not a heading). A fenced block (``` or ~~~,
203
+ * closed by the same fence) is skipped whole; a backtick fence whose info string holds a backtick
204
+ * is no fence, as in CommonMark.
205
+ * shortcut: a line scanner, not a CommonMark parser (no block quotes, no HTML blocks, no tabs as
206
+ * indentation); a spec written as the `spec` brick says is inside what it reads right.
172
207
  */
173
208
  export function countSpecTasks(text) {
174
- let level = 0; let count = 0;
209
+ let level = 0; let count = 0; let offset = -1; let fence = null;
210
+ let para = ''; let inItem = false; // the paragraph line before ('' for none) / the line before is a list item's text
175
211
  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;
212
+ const f = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
213
+ if (fence) {
214
+ if (f && f[1][0] === fence[0] && f[1].length >= fence.length && !f[2].trim()) fence = null;
180
215
  continue;
181
216
  }
182
- if (level && /^ {0,3}\d+[.)]\s+\S/.test(line)) count += 1;
217
+ if (f && !(f[1][0] === '`' && f[2].includes('`'))) { fence = f[1]; para = ''; continue; }
218
+ if (!line.trim()) { para = ''; inItem = false; continue; }
219
+ // F3: a line indented to the last task's content belongs to that task — its paragraphs, its
220
+ // sub-items, even a `---` or `##` of its own — so it neither ends the list nor adds a task
221
+ if (level && offset >= 0 && line.length - line.trimStart().length >= offset) { para = ''; inItem = true; continue; }
222
+ const atx =/^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/.exec(line);
223
+ const setext = para && /^ {0,3}(=+|-+)[ \t]*$/.exec(line);
224
+ const h = atx ? { depth: atx[1].length, text: atx[2] ?? '' } : setext ? { depth: setext[1][0] === '=' ? 1 : 2, text: para } : null;
225
+ if (h) {
226
+ if (level && h.depth <= level) break;
227
+ if (!level && /\btasks?\b/i.test(h.text)) level = h.depth;
228
+ para = ''; inItem = false; continue;
229
+ }
230
+ const item = /^( {0,3})(\d{1,9}[.)])[ \t]+\S/.exec(line);
231
+ if (item || /^ {0,3}[-*+][ \t]+\S/.test(line)) { para = ''; inItem = true; } else { para = inItem ? '' : line; }
232
+ if (!item || !level) continue;
233
+ if (offset >= 0 && item[1].length >= offset) continue; // inside the last task's content: a sub-item
234
+ count += 1; offset = item[1].length + item[2].length + 1;
183
235
  }
184
236
  return count;
185
237
  }
@@ -195,6 +247,10 @@ export function initFactory({ title, requirement, factory, input = null }) {
195
247
  }
196
248
 
197
249
  const taskNo = (state) => state.tasks?.index ?? 0;
250
+ // G3, F2: the task count is frozen once the first TASK loop launched: a loop launched while a spec
251
+ // is on record, or one in `history` recorded with a task (a loop before any spec records task 0).
252
+ const tasksFrozen = (state) => (state.launched != null && state.tasks != null)
253
+ || state.history.some((h) => loopOf(h?.stage) !== null && h.task >= 1);
198
254
  // The task as `next` and a replay hand it out: the owning stage is the engine's bookkeeping.
199
255
  const taskOut = ({ stage: _owner, ...task }) => task;
200
256
 
@@ -220,7 +276,11 @@ function assertNoLoop(loopStatus) {
220
276
  }
221
277
  }
222
278
 
223
- const rulesOf = (state) => (state.factory.rules?.length ? { rules: state.factory.rules } : {});
279
+ // What every stage receives from the factory itself: its `rules`, and the `protected` paths `checks` refuses to see changed.
280
+ const rulesOf = ({ factory }) => ({
281
+ ...(factory.rules?.length ? { rules: factory.rules } : {}),
282
+ ...(factory.protected?.length ? { protected: factory.protected } : {}),
283
+ });
224
284
 
225
285
  /**
226
286
  * `loopStatus`: the status in the LOOP.md at the worktree root, or null (the CLI looks; this stays
@@ -275,7 +335,24 @@ const initedSince = (initAt, launchAt) => {
275
335
  };
276
336
  function dirtyLines(porcelain, specPath) {
277
337
  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);
338
+ return filterPorcelain(porcelain).split('\n').filter((l) => l && slash(unquotePath(l.slice(3))) !== exempt);
339
+ }
340
+
341
+ // M11: git C-quotes a path with a byte it will not print as is (core.quotePath, on by default):
342
+ // `"specs/caf\303\251/spec.md"` is `specs/café/spec.md`. Octal escapes are UTF-8 bytes.
343
+ const C_ESCAPES = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 };
344
+ export function unquotePath(p) {
345
+ if (!(p.length >= 2 && p.startsWith('"') && p.endsWith('"'))) return p;
346
+ const bytes = [];
347
+ for (let i = 1; i < p.length - 1; i += 1) {
348
+ const c = p[i];
349
+ if (c !== '\\') { bytes.push(...Buffer.from(c, 'utf8')); continue; }
350
+ const oct = /^[0-7]{3}/.exec(p.slice(i + 1));
351
+ if (oct) { bytes.push(parseInt(oct[0], 8)); i += 3; continue; }
352
+ const n = C_ESCAPES[p[i + 1]];
353
+ bytes.push(n ?? 92); if (n !== undefined) i += 1;
354
+ }
355
+ return Buffer.from(bytes).toString('utf8');
279
356
  }
280
357
 
281
358
  /**
@@ -300,6 +377,10 @@ export function recordStage(state, { bricks }, outcome, {
300
377
  }
301
378
  const isLoop = loopOf(from) !== null;
302
379
  if (specPath !== null && isLoop) throw new Error('--spec is recorded by a stage outside a loop');
380
+ // R4 holds `tasks.path` to SPEC_PATH: stored, any other path would make every later action refuse FACTORY.md.
381
+ if (specPath !== null && !SPEC_PATH.test(specPath)) {
382
+ throw new Error(`--spec ${specPath} is not a spec the engine can keep: record a file named spec.md one folder under specs/ (specs/<slug>/spec.md; the folder may have any name but . or ..)`);
383
+ }
303
384
  if (isLoop) {
304
385
  // R2: the loop's evidence — its own LOOP.md, or the commit it closed with (docblock above).
305
386
  const launch = state.launched;
@@ -333,24 +414,25 @@ export function recordStage(state, { bricks }, outcome, {
333
414
  + `that changes files commits them first: ${dirty.join('; ')}${folded}`);
334
415
  }
335
416
  }
336
- const edge = state.factory.edges.find((e) => e.from === from && e.on === outcome)
337
- ?? (outcome === 'error' ? { from, on: 'error', to: '$stop' } : null);
417
+ const edge = edgeFor(state.factory, from, outcome);
338
418
  if (specPath !== null) {
339
419
  if (!Number.isInteger(taskCount) || taskCount < 1) throw new Error(`${specPath} has no ordered task list under a Tasks heading`);
340
420
  if (taskCount > FACTORY_MAX_TASKS) {
341
421
  throw new Error(`${specPath} lists ${taskCount} tasks; a factory runs ${FACTORY_MAX_TASKS} at most — split the requirement`);
342
422
  }
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`);
423
+ if (state.taskCount !== null && tasksFrozen(state) && taskCount > state.taskCount) {
424
+ throw new Error(`${specPath} lists ${taskCount} tasks, more than the ${state.taskCount} frozen when the first task loop launched`);
345
425
  }
346
426
  }
347
427
  if (!edge) throw new Error(`no edge from ${from} on ${outcome}`);
348
428
  assertLane(state, edge);
349
429
 
350
- if (isFork(from, bricks) && state.factory.stages.includes(edge.to)) state.lane = edge.to;
430
+ // M10: every fork record sets the lane, a terminal outcome to none: a gated fork re-run on an
431
+ // amend must not keep the lane its first answer chose.
432
+ if (isFork(from, bricks)) state.lane = state.factory.stages.includes(edge.to) ? edge.to : null;
351
433
  if (isLoop) state.launched = null;
352
434
  if (specPath !== null) {
353
- if (state.taskCount === null) { state.taskCount = taskCount; state.runCeiling = FACTORY_MAX_TRANSITIONS * taskCount; }
435
+ if (state.taskCount === null || !tasksFrozen(state)) { state.taskCount = taskCount; state.runCeiling = FACTORY_MAX_TRANSITIONS * taskCount; }
354
436
  state.tasks = { path: specPath, count: taskCount, index: 1, stage: null };
355
437
  state.taskHigh = Math.max(state.taskHigh, 1);
356
438
  }
@@ -411,7 +493,7 @@ export function decideFactory(state, { bricks }, verdict, note = '') {
411
493
  if (state.status !== 'awaiting') throw new Error('nothing is awaiting a decision');
412
494
  if (!['ok', 'no', 'amend'].includes(verdict)) throw new Error(`verdict must be ok, no or amend, not ${JSON.stringify(verdict)}`);
413
495
  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' };
496
+ const edge = edgeFor(state.factory, stage, outcome) ?? { from: stage, on: outcome, to: '$stop' };
415
497
  if (verdict === 'ok') assertLane(state, edge);
416
498
  state.awaiting = null; state.status = 'running';
417
499
  state.history.push({ stage, verdict, task: taskNo(state), ...(note ? { note } : {}) });
@@ -23,8 +23,9 @@ export function readDoneChecks(root) {
23
23
  }
24
24
  }
25
25
 
26
- // The package manager a lockfile names; first hit wins, npm without one.
27
- const PM_LOCKS = [['bun.lockb', 'bun'], ['bun.lock', 'bun'], ['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn']];
26
+ // The package manager a lockfile names; first hit wins, npm without one. Exported for the gate that
27
+ // holds the factory `checks` brick's restatement of these rules to this list (factory_graph test).
28
+ export const PM_LOCKS = [['bun.lockb', 'bun'], ['bun.lock', 'bun'], ['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn']];
28
29
  const PM_SCRIPTS = ['test', 'lint', 'typecheck'];
29
30
 
30
31
  /** One package.json script as a check: the lockfile's own spellings, plus npm's (npm runs any). */
@@ -441,15 +441,17 @@ function dropLines(p, needle) {
441
441
  * shortcut: rename only, and the day a store can live on another volume this needs a copy path.
442
442
  *
443
443
  * `move` is `copyFileSync` for a file that must stay readable until its replacement lands.
444
+ * `parent` is overridden only for a retired skill folder, whose sibling would sit inside the
445
+ * host's `skills/` scan root and load again: it goes to `<cfg>/archived-skills/<name>/` instead.
444
446
  */
445
- export function archiveStore(store, move = renameSync) {
447
+ export function archiveStore(store, move = renameSync,
448
+ parent = path.join(path.dirname(store), `archived-${path.basename(store)}`)) {
446
449
  // `toLocaleString('sv-SE')` — LOCAL time, matching the old hand-rolled stamp
447
450
  // (`getHours()`/`getMinutes()`/`getSeconds()` are all local-time getters, unlike
448
451
  // `toISOString()`'s UTC). sv-SE's default format is already zero-padded
449
452
  // "YYYY-MM-DD HH:MM:SS"; stripping the punctuation and reinserting one dash reproduces
450
453
  // the exact `YYYYMMDD-HHMMSS` shape the padStart version built by hand.
451
454
  const stamp = new Date().toLocaleString('sv-SE').replace(/\D/g, '').replace(/^(\d{8})/, '$1-');
452
- const parent = path.join(path.dirname(store), `archived-${path.basename(store)}`);
453
455
  // A taken name gets `-2`, …: two moves in one second must not fail the second.
454
456
  let dest = path.join(parent, stamp);
455
457
  for (let n = 2; existsSync(dest); n += 1) dest = path.join(parent, `${stamp}-${n}`);
@@ -93,7 +93,7 @@ export function loadCatalog({
93
93
  // Factories (`js/factory/`) are a third directory per level, same stem rule. Their parse
94
94
  // problems stay apart from `problems`: that list is `catalogProblems`' and so `loop check`'s,
95
95
  // and a broken factory file must not fail a loop.
96
- const factories = new Map(); const factoryProblems = [];
96
+ const factories = new Map(); const factoryProblems = []; const factoryOverridden = [];
97
97
  for (const [origin, dir] of levels) {
98
98
  const brickDir = path.join(dir, 'bricks'); const loopDir = path.join(dir, 'loops');
99
99
  for (const f of listFiles(brickDir, '.md')) {
@@ -116,21 +116,27 @@ export function loadCatalog({
116
116
  }
117
117
  templates.set(stem, { ...graph, origin });
118
118
  }
119
+ // M8: a file that does not load still claims its name at its level: the factory of that name
120
+ // from a lower level is dropped, never run in its place, so `factory init` names the problem.
119
121
  const factoryDir = path.join(dir, 'factories');
120
122
  for (const f of listFiles(factoryDir, '.json')) {
121
- let factory;
122
- try { factory = JSON.parse(readText(path.join(factoryDir, f))); } catch {
123
- factoryProblems.push(`factories/${f}: not JSON`); continue;
124
- }
125
123
  const stem = f.slice(0, -'.json'.length);
126
- if (factory?.name !== stem) {
127
- factoryProblems.push(`factories/${f}: name ${JSON.stringify(factory?.name)} does not match the file name`);
128
- continue;
129
- }
124
+ const broken = (why) => { factoryProblems.push(`factories/${f} (${origin}): ${why}`); factories.delete(stem); };
125
+ let factory;
126
+ try { factory = JSON.parse(readText(path.join(factoryDir, f))); } catch { broken('not JSON'); continue; }
127
+ if (factory?.name !== stem) { broken(`name ${JSON.stringify(factory?.name)} does not match the file name`); continue; }
128
+ const prior = factories.get(stem);
129
+ if (prior) factoryOverridden.push(`${stem} (${origin}, overrides ${prior.origin})`);
130
130
  factories.set(stem, { ...factory, origin });
131
131
  }
132
132
  }
133
- return { bricks, templates, problems, overridden: overridden.sort(), factories, factoryProblems };
133
+ // The shipped agents, by stem: what a factory's `review.seats` may name (`checkFactory` rule 9),
134
+ // read where `availability` reads a brick's agent, so the two cannot disagree.
135
+ const agents = new Set(listFiles(path.join(srcRoot, 'agents'), '.md').map((f) => f.slice(0, -'.md'.length)));
136
+ return {
137
+ bricks, templates, problems, overridden: overridden.sort(), factories, factoryProblems,
138
+ factoryOverridden: factoryOverridden.sort(), agents,
139
+ };
134
140
  }
135
141
 
136
142
  /** `catalog`: an already-loaded `loadCatalog(opts)`, for a caller that needs the catalogue
package/js/loop/cli.mjs CHANGED
@@ -83,22 +83,28 @@ function resolveGraph(spec, catalog) {
83
83
  }
84
84
 
85
85
  /**
86
- * The note of `init` or `record`: `--note`, or `--note-file`'s content. A note too long for a
87
- * shell argument, or one that mentions `git … commit`/`push` (and would otherwise sit inside the
88
- * command line GIT_GATE_RE matches whole), goes through a file instead — never through the shell
89
- * at all. CRLF-folded and trimmed the same way the porcelain stdin is, so a Windows-authored file
90
- * round-trips identically.
86
+ * A text argument: `--<flag>`, or `--<flag>-file`'s content (`args[key]` / `args[key + 'File']`),
87
+ * null when neither is given. Text too long for a shell argument, or text that holds the word
88
+ * `commit` or `push` (GIT_GATE_RE asks on any line that also holds `git`), goes through a file
89
+ * instead — never through the shell at all. The path is relative to the current directory.
90
+ * CRLF-folded and trimmed the same way the porcelain stdin is, so a Windows-authored file
91
+ * round-trips identically. The one writer of this rule: `geneseed factory`'s `--carry-file` and
92
+ * `--note-file` call it too.
91
93
  */
92
- function noteOf(args, action) {
93
- if (args.note && args.noteFile) throw new Error(`${action} takes --note or --note-file, not both`);
94
- if (!args.noteFile) return args.note ?? '';
94
+ export function textArg(args, key, flag, action) {
95
+ const fileKey = `${key}File`;
96
+ if (args[key] && args[fileKey]) throw new Error(`${action} takes --${flag} or --${flag}-file, not both`);
97
+ if (!args[fileKey]) return args[key] ?? null;
95
98
  let raw;
96
- try { raw = readText(path.resolve(args.noteFile)); } catch (e) {
97
- throw new Error(`cannot read --note-file ${args.noteFile}: ${e.message}`, { cause: e });
99
+ try { raw = readText(path.resolve(args[fileKey])); } catch (e) {
100
+ throw new Error(`cannot read --${flag}-file ${args[fileKey]}: ${e.message}`, { cause: e });
98
101
  }
99
102
  return raw.replace(/\r\n/g, '\n').trimEnd();
100
103
  }
101
104
 
105
+ /** The note of `init` or `record`: `--note` or `--note-file`, '' when neither. */
106
+ const noteOf = (args, action) => textArg(args, 'note', 'note', action) ?? '';
107
+
102
108
  const ACTIONS = {
103
109
  check(args) {
104
110
  // The project level of the catalogue is `<git root>/.geneseed/`, as for `init` and `next`,
@@ -29,7 +29,8 @@ import path from 'node:path';
29
29
 
30
30
  import { main as driverMain } from '../build/driver.mjs';
31
31
  import { foldHost, foldSummary } from '../build/fold.mjs';
32
- import { RETIRED_SKILL_IDS, ROOT, knownSkillIds, skillAliases } from '../build/source.mjs';
32
+ import { ROOT } from '../build/source.mjs';
33
+ import { ownsRel, retiredArchiveOf, retiredSkillFolders } from '../build/retired-skills.mjs';
33
34
  import { CLAUDE_STYLE, isCanonical, settingsFile } from '../hosts/hosts.mjs';
34
35
  import {
35
36
  claudeCfg, claudeReadManifest, EMIT_HOST_SCOPE, installState, installTargets,
@@ -130,31 +131,39 @@ function foldPreview(rows) {
130
131
  }
131
132
 
132
133
  /**
133
- * M5 — files no manifest owns, so no emit will ever prune them: the root `AGENT.md` and the folder
134
- * of a skill that no longer ships under its own name. An earlier build likely wrote them, but an
135
- * alias is a plain word and a folder under it may be the user's own, so nothing claims which.
136
- * REPORTED, never moved: they go aside on the user's word.
134
+ * M5 — files no manifest owns, so no emit's ordinary prune will ever reach them: the root
135
+ * `AGENT.md` and the folder of a skill that no longer ships under its own name. The skill
136
+ * folders split the way the next canonical emit treats them (`retiredSkillFolders`,
137
+ * `js/build/retired-skills.mjs`): `prunes`, a plain Geneseed render it moves aside, and
138
+ * `orphans`, everything it leaves — `AGENT.md`, a link, a folder without the render's
139
+ * fingerprint — because an alias is a plain word and such a folder may be the user's own.
137
140
  *
138
141
  * The candidate names come from what git history already settled and the source still records —
139
- * `RETIRED_SKILL_IDS` and the `aliases:` markers — because the CLI may not spawn `git`. Each
140
- * candidate is checked before it is listed: a live skill is never an orphan (`teach` is live,
141
- * `quiz` is its alias), and a path the manifest owns is not one either — the next emit prunes it.
142
+ * `RETIRED_SKILL_IDS` and the `aliases:` markers — because the CLI may not spawn `git`. A live
143
+ * skill is never a candidate (`teach` is live, `quiz` is its alias), and a path the manifest
144
+ * owns is not one either — the ordinary prune handles it.
142
145
  */
143
- export function orphanFindings(cfg, owned, { live = knownSkillIds(), aliases = skillAliases() } = {}) {
144
- const owns = (rel) => owned.some((o) => o === rel || o.startsWith(`${rel}/`));
145
- const names = [...new Set([...aliases.keys(), ...Object.keys(RETIRED_SKILL_IDS)])].filter((n) => !live.includes(n));
146
- return ['AGENT.md', ...names.map((n) => `skills/${n}`)]
147
- .filter((rel) => !owns(rel) && existsSync(path.join(cfg, rel)))
148
- .map((rel) => path.join(cfg, rel));
146
+ export function orphanFindings(cfg, owned, opts = {}) {
147
+ return orphanSplit(cfg, owned, opts).orphans;
149
148
  }
150
149
 
151
- /** The `--dry-run` half of M5: the orphans of each global Claude-style install. */
150
+ function orphanSplit(cfg, owned, opts = {}) {
151
+ const { prune, keep } = retiredSkillFolders(cfg, owned, opts);
152
+ const agent = !ownsRel(owned, 'AGENT.md') && existsSync(path.join(cfg, 'AGENT.md')) ? [path.join(cfg, 'AGENT.md')] : [];
153
+ return { prunes: prune, orphans: [...agent, ...keep] };
154
+ }
155
+
156
+ /** The `--dry-run` half of M5, for each canonical global install of every host. */
152
157
  function orphanPreview(rows) {
153
- return rows.filter(({ host, scope, root }) => scope === 'global' && CLAUDE_STYLE.includes(host) && isCanonical(root, host))
154
- .flatMap(({ root }) => {
155
- const owned = claudeReadManifest(root).owned;
156
- return orphanFindings(root, Array.isArray(owned) ? owned : []);
157
- });
158
+ const out = { prunes: [], orphans: [] };
159
+ for (const { host, scope, root } of rows) {
160
+ if (scope !== 'global' || !isCanonical(root, host)) continue;
161
+ const owned = claudeReadManifest(root).owned;
162
+ const { prunes, orphans } = orphanSplit(root, Array.isArray(owned) ? owned : []);
163
+ out.prunes.push(...prunes);
164
+ out.orphans.push(...orphans);
165
+ }
166
+ return out;
158
167
  }
159
168
 
160
169
  /** The fold and orphan half of `--dry-run`, as the CLI prints it. */
@@ -163,20 +172,25 @@ function printPreview(rows) {
163
172
  printOut(summary ? `[migrate] would fold ${host}: ${summary}\n` : `[migrate] ${host}: nothing to fold\n`);
164
173
  for (const f of failed) printOut(`[migrate] ${host}: the fold would stop at ${f}\n`);
165
174
  }
166
- for (const p of orphanPreview(rows)) {
175
+ const { prunes, orphans } = orphanPreview(rows);
176
+ for (const p of prunes) {
177
+ printOut(`[migrate] would prune: ${p} (Geneseed rendered it and no longer ships it; the next emit moves it to `
178
+ + `${retiredArchiveOf(path.dirname(path.dirname(p)), path.basename(p))})\n`);
179
+ }
180
+ for (const p of orphans) {
167
181
  printOut(`[migrate] orphan: ${p} (no manifest owns it; an earlier build may have written it, or it may be yours). Nothing moves it: if it is not yours, move it by hand.\n`);
168
182
  }
169
183
  }
170
184
 
171
185
  /**
172
- * What the next rebuild would do, for the console: `{folds: [{host, summary, failed}], orphans}`.
173
- * Writes nothing. A marker `migrate` refuses is in here too: `rebuild-all` coerces it, so that
174
- * install still folds. No `would re-emit` plan: that is this verb's, and a clone has none to run.
186
+ * What the next rebuild would do, for the console: `{folds: [{host, summary, failed}], prunes,
187
+ * orphans}`. Writes nothing. A marker `migrate` refuses is in here too: `rebuild-all` coerces it,
188
+ * so that install still folds. No `would re-emit` plan: that is this verb's, and a clone has none.
175
189
  */
176
190
  export function migratePreview() {
177
191
  const { rows, unrecognised } = migrateSurvey({ prune: false });
178
192
  const all = [...rows, ...unrecognised];
179
- return { folds: foldPreview(all), orphans: orphanPreview(all) };
193
+ return { folds: foldPreview(all), ...orphanPreview(all) };
180
194
  }
181
195
 
182
196
  /** A stash key that cannot collide across drives, and is a legal file name on both platforms. */