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,511 @@
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.
28
+ * A path git C-quotes (a non-ASCII slug, under the default core.quotePath) is unquoted first (M11). No porcelain
29
+ * at all (`null`, a TTY stdin) is refused too: it proves nothing. The limit: an empty pipe reads
30
+ * as a clean tree, so the engine trusts whoever pipes it.
31
+ *
32
+ * A LOOP STAGE REPORTS WHAT ITS LOOP DID (R2). `next` on a loop stage stores the launch
33
+ * (`launched`: the stage, its template, the HEAD commit and the time then). `record` on it then
34
+ * needs evidence. With a LOOP.md left, the evidence is that file: its template must be the stage's,
35
+ * and its status must match the outcome (stopped is fail, done is pass). With no LOOP.md left, HEAD
36
+ * must have moved since the launch (the loop's close commit, or the commit that removed a stopped
37
+ * loop's LOOP.md), and `fail` needs nothing more. `pass` also needs the loop registry
38
+ * (`js/loop/registry.mjs`): its row for this worktree must carry an `initAt` later than the launch,
39
+ * so a `geneseed loop init` ran here after `next`, and with no LOOP.md left that loop has ended.
40
+ * What this does NOT prove: that the ended loop closed rather than stopped (the registry keeps no
41
+ * status), or that it ran the stage's template. A stopped loop whose LOOP.md was removed by hand
42
+ * can still pass. The registry row's `started` cannot serve: it is set once per worktree, so a
43
+ * re-entered loop would never pass.
44
+ *
45
+ * R4 COVERS WHAT A HAND CAN EDIT. FACTORY.md is a file; `validateFactoryState` refuses counters
46
+ * that are not non-negative integers, a ceiling above 1200, a task block out of its bounds, a gate
47
+ * amend count above 3, a `lane` no fork of the factory leads to, a status the engine does not
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
50
+ * `checkFactory` — the termination argument below holds only for a state this engine could have
51
+ * written.
52
+ *
53
+ * LANES (D11, D13). A fork is a brick stage with named outcomes (`isFork`, `js/factory/graph.mjs`).
54
+ * `next` hands it `lanes` (each outcome with the stage it leads to), and `record` on it stores the
55
+ * stage its outcome's edge reaches as `lane`. An edge to `$lane` resolves to that stage, and spends
56
+ * the cycle `spentCycle` names for the literal `$lane` target, the rule `checkFactory` proves the
57
+ * graph against. A route to `$lane` with no lane on record (a state `check` cannot produce) is
58
+ * refused before the state changes, on `record` and on a gate's `ok` alike: never guessed.
59
+ *
60
+ * TASKS (D9). A stage that writes a spec records its path and task count (`tasks`). The first
61
+ * `loop:` stage recorded after it owns the tasks (`tasks.stage`) and alone is replayed once per
62
+ * task, `index` 1 to `count`; a fix loop that runs in between follows its own edges. A task the
63
+ * run reaches for the FIRST time starts with fresh cycle counters and a fresh per-task ceiling
64
+ * (J6); `taskHigh` is the highest index reached, so a spec re-recorded after a route back (index
65
+ * back to 1) gives no task a second fresh budget. A route back into the owner after its last task
66
+ * (J7: red CI at `merge-gate`) is ONE EXTRA TASK: `next` marks it `extra`, read off `history`
67
+ * alone, and it reaches no task never reached, so it spends the route's cycle and both ceilings
68
+ * like any lap and resets nothing.
69
+ *
70
+ * TERMINATION BY CONSTRUCTION (J3, R8). `transitions` counts per task and resets with it. On top,
71
+ * `runTransitions` counts every transition of the run, never resets, and stops the run past
72
+ * `runCeiling`: `FACTORY_MAX_TRANSITIONS` until a spec is recorded, then
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
82
+ * into several factory runs a human can review, not one run nobody reads to the end.
83
+ */
84
+ import { writeText } from '../lib/fs.mjs';
85
+ import { renameWithRetry, filterPorcelain } from '../loop/state.mjs';
86
+ import { loopOf, stageOutcomes, checkFactory, LANE, isFork, lanesOf, laneTargets, spentCycle, edgeFor } from './graph.mjs';
87
+
88
+ const BEGIN = '<!-- factory-state:begin -->';
89
+ const END = '<!-- factory-state:end -->';
90
+ export const FACTORY_FILE = 'FACTORY.md';
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;
93
+ export const FACTORY_MAX_TASKS = 20;
94
+ const GATE_MAX_AMENDS = 3;
95
+ const STATUSES = ['running', 'awaiting', 'done', 'stopped'];
96
+ const PORCELAIN = 'git status --porcelain --untracked-files=all';
97
+ const slash = (p) => String(p).replaceAll('\\', '/');
98
+
99
+ export function renderFactoryFile(state) {
100
+ return `# Factory — ${state.title}\n\n${state.requirement}\n\n`
101
+ + 'The block below belongs to the engine: `geneseed factory` rewrites it on every action.\n\n'
102
+ + `${BEGIN}\n\`\`\`json\n${JSON.stringify(state, null, 2)}\n\`\`\`\n${END}\n`;
103
+ }
104
+
105
+ /** R4: anything that is not a well-formed block throws, so every action refuses and none repairs. */
106
+ export function parseFactoryFile(text) {
107
+ const t = String(text).replace(/\r\n/g, '\n');
108
+ const a = t.indexOf(BEGIN); const b = t.lastIndexOf(END);
109
+ if (a < 0 || b < a) throw new Error('FACTORY.md has no factory-state block');
110
+ const inner = t.slice(a + BEGIN.length, b).replace(/^\s*```json\s*/, '').replace(/\s*```\s*$/, '');
111
+ let state;
112
+ try { state = JSON.parse(inner); } catch (e) {
113
+ throw new Error(`FACTORY.md is unreadable: ${e.message}`, { cause: e });
114
+ }
115
+ if (state?.v !== 1) throw new Error('FACTORY.md is unreadable: no state of version 1');
116
+ return state;
117
+ }
118
+
119
+ const count = (v) => Number.isInteger(v) && v >= 0;
120
+ const plainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
121
+
122
+ /**
123
+ * R4, past the JSON: a state this engine could have written, and a factory that still passes
124
+ * `checkFactory` against today's catalogue. Throws "FACTORY.md is unreadable: ..." like the parse.
125
+ */
126
+ export function validateFactoryState(state, catalog) {
127
+ const bad = (what) => { throw new Error(`FACTORY.md is unreadable: ${what}`); };
128
+ for (const k of ['transitions', 'runTransitions', 'runCeiling', 'taskHigh']) {
129
+ if (!count(state[k])) bad(`${k} must be a non-negative integer`);
130
+ }
131
+ if (state.runCeiling > FACTORY_MAX_TRANSITIONS * FACTORY_MAX_TASKS) {
132
+ bad(`runCeiling must be ${FACTORY_MAX_TRANSITIONS * FACTORY_MAX_TASKS} at most`);
133
+ }
134
+ if (!plainObject(state.counters) || !Object.values(state.counters).every(count)) {
135
+ bad('counters must map each cycle to a non-negative integer');
136
+ }
137
+ const { taskCount, tasks, launched } = state;
138
+ if (taskCount !== null && !(Number.isInteger(taskCount) && taskCount >= 1 && taskCount <= FACTORY_MAX_TASKS)) {
139
+ bad(`taskCount must be null or an integer from 1 to ${FACTORY_MAX_TASKS}`);
140
+ }
141
+ if (tasks !== null && !(plainObject(tasks) && SPEC_PATH.test(tasks.path) && Number.isInteger(tasks.count)
142
+ && tasks.count >= 1 && tasks.count <= (taskCount ?? 0) && Number.isInteger(tasks.index) && tasks.index >= 1
143
+ && tasks.index <= tasks.count && (tasks.stage === null || typeof tasks.stage === 'string'))) {
144
+ bad('tasks must be null or a spec path with 1 <= index <= count <= taskCount');
145
+ }
146
+ if (launched != null && !(plainObject(launched) && typeof launched.stage === 'string'
147
+ && typeof launched.template === 'string' && (launched.head === null || typeof launched.head === 'string')
148
+ && (launched.at == null || typeof launched.at === 'string'))) {
149
+ bad('launched must be null or a stage, a template, a head and a time');
150
+ }
151
+ if (!STATUSES.includes(state.status)) bad(`status must be one of ${STATUSES.join(', ')}`);
152
+ if (!Array.isArray(state.history)) bad('history must be a list');
153
+ if (!plainObject(state.gateAmends) || !Object.values(state.gateAmends).every((n) => count(n) && n <= GATE_MAX_AMENDS)) {
154
+ bad(`gateAmends must map each gate to an integer from 0 to ${GATE_MAX_AMENDS}`);
155
+ }
156
+ // `cycles` may be absent (`transition` reads it `?? []`), never another shape: `checkFactory`
157
+ // reads a non-list as no cycles, and `transition` would then throw iterating it.
158
+ if (plainObject(state.factory) && state.factory.cycles !== undefined && !Array.isArray(state.factory.cycles)) {
159
+ bad('factory.cycles must be a list');
160
+ }
161
+ const problems = checkFactory(state.factory, catalog);
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
+ }
180
+ // absent in a state written before lanes existed: that reads as none on record
181
+ if (state.lane != null && !laneTargets(state.factory, catalog.bricks).has(state.lane)) {
182
+ bad('lane must be null or a stage a fork of the factory leads to');
183
+ }
184
+ }
185
+
186
+ /** `<file>.tmp` then `renameWithRetry`, as `writeLoopFile`: a killed write never tears FACTORY.md. */
187
+ export function writeFactoryFile(file, state) {
188
+ const tmp = `${file}.tmp`;
189
+ writeText(tmp, renderFactoryFile(state));
190
+ renameWithRetry(tmp, file);
191
+ }
192
+
193
+ /**
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.
207
+ */
208
+ export function countSpecTasks(text) {
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
211
+ for (const line of String(text).replace(/\r\n/g, '\n').split('\n')) {
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;
215
+ continue;
216
+ }
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;
235
+ }
236
+ return count;
237
+ }
238
+
239
+ export function initFactory({ title, requirement, factory, input = null }) {
240
+ return {
241
+ v: 1, title, requirement, input, factory, stage: factory.start,
242
+ status: 'running', awaiting: null, reason: null,
243
+ counters: {}, transitions: 0, runTransitions: 0, runCeiling: FACTORY_MAX_TRANSITIONS, taskHigh: 0, taskCount: null,
244
+ lane: null, tasks: null, carry: null, launched: null,
245
+ history: [], gateAmends: {},
246
+ };
247
+ }
248
+
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);
254
+ // The task as `next` and a replay hand it out: the owning stage is the engine's bookkeeping.
255
+ const taskOut = ({ stage: _owner, ...task }) => task;
256
+
257
+ function stop(state, reason) {
258
+ state.status = 'stopped'; state.reason = reason;
259
+ return { stopped: reason };
260
+ }
261
+
262
+ const summary = (state) => ({ transitions: state.transitions, history: state.history });
263
+
264
+ function assertRunning(state) {
265
+ if (state.status !== 'running') throw new Error(`the factory is ${state.status}, not running`);
266
+ }
267
+
268
+ // R3: the child loop owns the worktree while its LOOP.md says neither `done` nor `stopped`.
269
+ // `loopStatus` is that status as the CLI read it, null when there is no LOOP.md; a LOOP.md that
270
+ // does not parse reaches here as running.
271
+ const ENDED = ['done', 'stopped'];
272
+ function assertNoLoop(loopStatus) {
273
+ if (loopStatus !== null && !ENDED.includes(loopStatus)) {
274
+ throw new Error('a loop is still running in this worktree (LOOP.md exists): finish it with '
275
+ + '`geneseed loop next` and its final commit before the factory moves on');
276
+ }
277
+ }
278
+
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
+ });
284
+
285
+ /**
286
+ * `loopStatus`: the status in the LOOP.md at the worktree root, or null (the CLI looks; this stays
287
+ * pure). A loop stage refuses ANY LOOP.md: `loop init` refuses to overwrite one, and a stopped
288
+ * loop leaves its own behind, tracked, so the error names the removal. On a loop stage it stores
289
+ * the launch with `head` (the HEAD commit, null when unreadable) and `at` (`now`, an ISO time the
290
+ * CLI passes; null leaves `pass` with no LOOP.md unprovable) — once per stage visit, so a second
291
+ * `next` after the loop committed does not move the baseline `record` compares with.
292
+ */
293
+ export function nextStage(state, { bricks }, { loopStatus = null, head = null, now = null } = {}) {
294
+ if (state.status === 'awaiting') return { awaiting: state.awaiting };
295
+ if (state.status === 'done') return { terminal: '$close', summary: summary(state) };
296
+ if (state.status === 'stopped') return { terminal: '$stop', reason: state.reason, summary: summary(state) };
297
+ assertNoLoop(loopStatus);
298
+ const { stage } = state;
299
+ const loop = loopOf(stage);
300
+ if (loop !== null) {
301
+ if (loopStatus !== null) {
302
+ throw new Error('the previous loop left its LOOP.md at the worktree root: run `git rm -f LOOP.md` and commit '
303
+ + `that removal before \`geneseed loop init\` starts ${stage}`);
304
+ }
305
+ const owned = state.tasks && (state.tasks.stage === null || state.tasks.stage === stage);
306
+ if (state.launched?.stage !== stage) state.launched = { stage, template: loop, head, at: now };
307
+ // J7: the owner, recorded since the spec, entered by an edge rather than its own replay, has
308
+ // passed its last task: this visit is one extra task, to fix what the stage before reported.
309
+ const last = state.history.at(-1);
310
+ const extra = owned && state.tasks.stage === stage && state.tasks.index === state.tasks.count && last?.stage !== stage
311
+ ? { extra: `${last.stage} reported ${last.outcome ?? last.verdict}` } : {};
312
+ return {
313
+ stage, loop, notes: state.carry ? [state.carry] : [],
314
+ ...(owned ? { task: { ...taskOut(state.tasks), ...extra } } : {}), ...rulesOf(state),
315
+ };
316
+ }
317
+ const brick = bricks.get(stage);
318
+ if (!brick) throw new Error(`no brick named ${stage} in the catalogue`);
319
+ return {
320
+ stage, effect: brick.effect, agent: brick.agent, skill: brick.skill, outcomes: brick.outcomes,
321
+ prompt: brick.body, requirement: state.requirement, input: state.input, carry: state.carry,
322
+ // D11: a fork picks from its own edges; the factory is their one writer, so the stage reads them here
323
+ ...(isFork(stage, bricks) ? { lanes: lanesOf(state.factory, stage) } : {}),
324
+ ...rulesOf(state),
325
+ };
326
+ }
327
+
328
+ // J5: the porcelain after a stage outside a loop, minus engine files and the run's spec — at the
329
+ // `spec` brick's own path only (one slug segment, never `.` or `..`).
330
+ const SPEC_PATH = /^specs\/(?!\.\.?\/)[^/]+\/spec\.md$/;
331
+ // R2: a loop init strictly after the launch; an absent or unparsable time on either side proves nothing.
332
+ const initedSince = (initAt, launchAt) => {
333
+ const a = Date.parse(initAt ?? ''); const b = Date.parse(launchAt ?? '');
334
+ return Number.isFinite(a) && Number.isFinite(b) && a > b;
335
+ };
336
+ function dirtyLines(porcelain, specPath) {
337
+ const exempt = specPath !== null && SPEC_PATH.test(specPath) ? specPath : null;
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');
356
+ }
357
+
358
+ /**
359
+ * Record the current stage's outcome and follow its edge. On a fork, the stage the outcome's edge
360
+ * reaches becomes the run's `lane`. `specPath`
361
+ * with `taskCount` (a stage that wrote a spec), `carry` (the reason the next stage — above all a
362
+ * re-entered loop — must hear). `loopTemplate` is the graph name in the LOOP.md the CLI read,
363
+ * `head` the HEAD commit now, `loopInitAt` the registry row's last `loop init` time for this
364
+ * worktree, or null (R2). Every refusal throws before the state changes.
365
+ */
366
+ export function recordStage(state, { bricks }, outcome, {
367
+ porcelain = null, specPath = null, taskCount = null, carry = null, loopStatus = null,
368
+ loopTemplate = null, head = null, loopInitAt = null,
369
+ } = {}) {
370
+ assertRunning(state);
371
+ assertNoLoop(loopStatus);
372
+ const from = state.stage;
373
+ const outcomes = stageOutcomes(from, bricks);
374
+ if (!outcomes) throw new Error(`no brick named ${from} in the catalogue`);
375
+ if (!outcomes.includes(outcome)) {
376
+ throw new Error(`${from} cannot report ${JSON.stringify(outcome)} — one of ${outcomes.join(', ')}`);
377
+ }
378
+ const isLoop = loopOf(from) !== null;
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
+ }
384
+ if (isLoop) {
385
+ // R2: the loop's evidence — its own LOOP.md, or the commit it closed with (docblock above).
386
+ const launch = state.launched;
387
+ if (launch?.stage !== from) throw new Error(`${from} was never launched: run \`geneseed factory next\` before its loop, then record`);
388
+ const said = { stopped: 'fail', done: 'pass' }[loopStatus];
389
+ if (said) {
390
+ if (loopTemplate !== launch.template) {
391
+ throw new Error(`the LOOP.md at the worktree root ran ${loopTemplate ?? 'an unnamed graph'}, not ${launch.template}: it is not ${from}'s loop`);
392
+ }
393
+ if (outcome !== said) {
394
+ throw new Error(`${from} cannot report ${outcome}: its LOOP.md says the loop ${loopStatus === 'done' ? 'is done' : 'stopped'} — report ${said}`);
395
+ }
396
+ } else if (head === null || head === launch.head) {
397
+ // shortcut: "moved" is "differs", not "descends from"; an fs-only reader cannot walk ancestry.
398
+ throw new Error(`${from} cannot report ${outcome}: no LOOP.md is left and HEAD has not moved since \`factory next\` — `
399
+ + 'record after the loop\'s close commit, or after the commit that removes a stopped loop\'s LOOP.md');
400
+ } else if (outcome === 'pass' && !initedSince(loopInitAt, launch.at)) {
401
+ throw new Error(`${from} cannot report pass on a HEAD move alone: no LOOP.md is left, and the loop registry `
402
+ + 'records no `geneseed loop init` in this worktree since `factory next` — report fail, or record pass '
403
+ + 'while the done LOOP.md is still at the root');
404
+ }
405
+ } else {
406
+ if (porcelain === null) {
407
+ throw new Error(`${from} is a stage outside a loop: pipe \`${PORCELAIN}\` into record, so the engine can see the tree is clean`);
408
+ }
409
+ const dirty = dirtyLines(porcelain, specPath ?? state.tasks?.path ?? null);
410
+ if (dirty.length) {
411
+ const folded = dirty.some((l) => /\/"?$/.test(l))
412
+ ? ` — a path ending in / is a whole untracked directory: pipe \`${PORCELAIN}\`, which lists each file` : '';
413
+ throw new Error(`${from} left the worktree dirty, and a stage outside a loop records only on a clean tree, so a brick `
414
+ + `that changes files commits them first: ${dirty.join('; ')}${folded}`);
415
+ }
416
+ }
417
+ const edge = edgeFor(state.factory, from, outcome);
418
+ if (specPath !== null) {
419
+ if (!Number.isInteger(taskCount) || taskCount < 1) throw new Error(`${specPath} has no ordered task list under a Tasks heading`);
420
+ if (taskCount > FACTORY_MAX_TASKS) {
421
+ throw new Error(`${specPath} lists ${taskCount} tasks; a factory runs ${FACTORY_MAX_TASKS} at most — split the requirement`);
422
+ }
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`);
425
+ }
426
+ }
427
+ if (!edge) throw new Error(`no edge from ${from} on ${outcome}`);
428
+ assertLane(state, edge);
429
+
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;
433
+ if (isLoop) state.launched = null;
434
+ if (specPath !== null) {
435
+ if (state.taskCount === null || !tasksFrozen(state)) { state.taskCount = taskCount; state.runCeiling = FACTORY_MAX_TRANSITIONS * taskCount; }
436
+ state.tasks = { path: specPath, count: taskCount, index: 1, stage: null };
437
+ state.taskHigh = Math.max(state.taskHigh, 1);
438
+ }
439
+ if (isLoop && state.tasks && state.tasks.stage === null) state.tasks.stage = from;
440
+ state.carry = carry || null;
441
+ state.history.push({
442
+ stage: from, outcome, task: taskNo(state), ...(carry ? { carry } : {}),
443
+ });
444
+ const brick = isLoop ? null : bricks.get(from);
445
+ if (brick?.gate === 'human' && (!brick.gateOn || brick.gateOn.includes(outcome))) {
446
+ state.status = 'awaiting';
447
+ state.awaiting = { kind: 'gate', stage: from, outcome, ...(carry ? { note: carry } : {}) };
448
+ return { awaiting: state.awaiting };
449
+ }
450
+ // D9: a passed task replays the same loop stage for the next one; only a task never reached
451
+ // before gets fresh budgets (J6), so a re-recorded spec cannot reset its way into a lap forever.
452
+ if (isLoop && outcome === 'pass' && state.tasks?.stage === from && state.tasks.index < state.tasks.count) {
453
+ state.tasks.index += 1; state.carry = null;
454
+ if (state.tasks.index > state.taskHigh) {
455
+ state.taskHigh = state.tasks.index; state.counters = {}; state.transitions = 0;
456
+ }
457
+ return { stage: from, task: taskOut(state.tasks) };
458
+ }
459
+ return transition(state, from, edge, bricks);
460
+ }
461
+
462
+ // D13: an edge to `$lane` needs a lane on record; checked before any state changes.
463
+ function assertLane(state, edge) {
464
+ if (edge.to === LANE && state.lane == null) {
465
+ throw new Error(`${edge.from} routes to ${LANE}, but no fork has chosen a lane in this run`);
466
+ }
467
+ }
468
+
469
+ function transition(state, from, edge, bricks) {
470
+ if (edge.to === '$stop') return stop(state, `${from} reported ${edge.on}`);
471
+ if (edge.to === '$close') { state.status = 'done'; state.stage = '$close'; return { done: true }; }
472
+ state.transitions += 1; state.runTransitions += 1;
473
+ if (state.transitions > FACTORY_MAX_TRANSITIONS) return stop(state, `transition ceiling of ${FACTORY_MAX_TRANSITIONS} reached`);
474
+ if (state.runTransitions > state.runCeiling) {
475
+ return stop(state, `run-wide transition ceiling of ${state.runCeiling} reached (${FACTORY_MAX_TRANSITIONS} per task)`);
476
+ }
477
+ const cycle = spentCycle(state.factory.cycles ?? [], from, edge.to, laneTargets(state.factory, bricks));
478
+ if (cycle) {
479
+ state.counters[cycle.name] = (state.counters[cycle.name] ?? 0) + 1;
480
+ if (state.counters[cycle.name] > cycle.max) return stop(state, `cycle ${cycle.name} exhausted its max of ${cycle.max}`);
481
+ }
482
+ const to = edge.to === LANE ? state.lane : edge.to;
483
+ state.stage = to;
484
+ return { stage: to };
485
+ }
486
+
487
+ /**
488
+ * The answer to a held `gate: human` stage (D14: the loop engine's gate and verdicts, reused).
489
+ * `ok` follows the held edge; `no` stops; `amend` re-runs the stage with the note as its `carry`,
490
+ * `GATE_MAX_AMENDS` times per stage per task.
491
+ */
492
+ export function decideFactory(state, { bricks }, verdict, note = '') {
493
+ if (state.status !== 'awaiting') throw new Error('nothing is awaiting a decision');
494
+ if (!['ok', 'no', 'amend'].includes(verdict)) throw new Error(`verdict must be ok, no or amend, not ${JSON.stringify(verdict)}`);
495
+ const { stage, outcome } = state.awaiting;
496
+ const edge = edgeFor(state.factory, stage, outcome) ?? { from: stage, on: outcome, to: '$stop' };
497
+ if (verdict === 'ok') assertLane(state, edge);
498
+ state.awaiting = null; state.status = 'running';
499
+ state.history.push({ stage, verdict, task: taskNo(state), ...(note ? { note } : {}) });
500
+ if (verdict === 'no') return stop(state, `gate rejected at ${stage}${note ? `: ${note}` : ''}`);
501
+ if (verdict === 'amend') {
502
+ const key = `${stage}@${taskNo(state)}`;
503
+ // Checked before the count moves, so a stored count never passes the cap R4 holds it to.
504
+ const spent = state.gateAmends?.[key] ?? 0;
505
+ if (spent >= GATE_MAX_AMENDS) return stop(state, `gate amended ${GATE_MAX_AMENDS} times at ${stage}`);
506
+ state.gateAmends = { ...state.gateAmends, [key]: spent + 1 };
507
+ state.stage = stage; state.carry = note || null;
508
+ return { resumed: true };
509
+ }
510
+ return transition(state, stage, edge, bricks);
511
+ }
@@ -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.
@@ -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). */
@@ -27,7 +27,7 @@ import { gitRootOf } from './gitref.mjs';
27
27
  * `!bricks/`. The same string lives in `adapters/opencode/plugins/geneseed-workflow.js`,
28
28
  * `adapters/opencode/workflows/_runtime.js` and `src/skills/_checkpoints.md`; tests pin them.
29
29
  */
30
- export const GENESEED_GITIGNORE = '/*\n!/.gitignore\n!/bricks/\n!/loops/\n!/protected-checks.txt\n!/done-checks.txt\n';
30
+ export const GENESEED_GITIGNORE = '/*\n!/.gitignore\n!/bricks/\n!/loops/\n!/factories/\n!/protected-checks.txt\n!/done-checks.txt\n';
31
31
 
32
32
  /**
33
33
  * Create-if-absent; a file holding only `*` is Geneseed's former output (it hid team bricks),
@@ -96,6 +96,27 @@ export function currentBranch(cwd) {
96
96
  }
97
97
  }
98
98
 
99
+ /**
100
+ * The commit HEAD names in `root`, read without spawning git: a detached sha as it stands, else
101
+ * the branch ref — loose in the SHARED gitdir (a linked worktree's private gitdir holds only its
102
+ * HEAD), then `packed-refs`. null on anything else: an unborn branch, a reftable repository, no
103
+ * repo. The factory engine compares it before and after a child loop (`js/factory/state.mjs`, R2).
104
+ */
105
+ export function headCommit(root) {
106
+ try {
107
+ const head = readFileSync(path.join(gitDirOf(root), 'HEAD'), 'utf8').trim();
108
+ if (/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(head)) return head;
109
+ const ref = /^ref:\s*(refs\/heads\/\S+)$/.exec(head)?.[1];
110
+ if (!ref) return null;
111
+ const common = gitCommonDirOf(root);
112
+ try { return readFileSync(path.join(common, ref), 'utf8').trim(); } catch { /* packed, or unborn */ }
113
+ const packed = readFileSync(path.join(common, 'packed-refs'), 'utf8');
114
+ return packed.split(/\r?\n/).map((l) => l.split(' ')).find(([, name]) => name === ref)?.[0] ?? null;
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+
99
120
  /**
100
121
  * The SHARED `.git` directory for `root`: the gitdir itself in a main worktree, the one its
101
122
  * `commondir` names in a linked worktree. Refs under `refs/remotes/`, `refs/stash` and