geneseed 5.2.0 → 5.3.1

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 (190) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +4 -4
  3. package/SHIPPED.md +1 -1
  4. package/adapters/bob/README.md +31 -18
  5. package/adapters/claude-code/README.md +27 -22
  6. package/adapters/openclaude/README.md +18 -8
  7. package/adapters/opencode/HOW-OPENCODE-LOADS.md +8 -3
  8. package/adapters/opencode/plugins/geneseed-activity.js +20 -21
  9. package/adapters/opencode/plugins/geneseed-context.js +224 -71
  10. package/adapters/opencode/plugins/geneseed-guard.js +420 -203
  11. package/adapters/opencode/plugins/geneseed-workflow.js +3 -2
  12. package/adapters/opencode/workflows/_runtime.js +3 -2
  13. package/bin/geneseed-cli.mjs +61 -16
  14. package/bin/geneseed-hook.mjs +94 -12
  15. package/docs/concepts/enforcement-table.md +1 -1
  16. package/docs/concepts/exclusions.md +2 -2
  17. package/docs/concepts/factories.md +40 -6
  18. package/docs/concepts/footprint.md +11 -1
  19. package/docs/concepts/foreman-mode.md +2 -2
  20. package/docs/concepts/hook-gates.md +3 -3
  21. package/docs/concepts/host-matrix.md +22 -4
  22. package/docs/concepts/loop-gates.md +1 -1
  23. package/docs/concepts/loops.md +2 -2
  24. package/docs/concepts/shared-tier.md +1 -1
  25. package/docs/design-history.md +148 -0
  26. package/docs/extending.md +97 -163
  27. package/docs/guides/install-bob.md +2 -2
  28. package/docs/guides/install-openclaude.md +1 -1
  29. package/docs/guides/run-a-factory.md +15 -2
  30. package/docs/guides/upgrade.md +2 -2
  31. package/docs/guides/verify.md +12 -0
  32. package/docs/reference/environment.md +1 -0
  33. package/docs/reference/factory-actions.md +6 -5
  34. package/docs/reference/troubleshoot-doctor.md +1 -1
  35. package/docs/reference/troubleshoot-update.md +1 -1
  36. package/docs/token-footprint.md +66 -2
  37. package/docs/understand/design-choices-hosts.md +1 -1
  38. package/docs/understand/design-choices-shape.md +1 -0
  39. package/docs/understand/enforced-vs-asked.md +1 -1
  40. package/docs/understand/machine-bob.md +1 -1
  41. package/docs/web-ui.md +21 -3
  42. package/harness.config.json +1 -1
  43. package/js/README.md +7 -5
  44. package/js/build/args.mjs +4 -4
  45. package/js/build/driver.mjs +1 -1
  46. package/js/build/emit-claude.mjs +1 -1
  47. package/js/build/generate.mjs +5 -14
  48. package/js/build/render.mjs +44 -24
  49. package/js/cli-table.json +135 -59
  50. package/js/factory/cli.mjs +24 -5
  51. package/js/factory/graph.mjs +13 -9
  52. package/js/factory/metrics.mjs +93 -0
  53. package/js/factory/registry.mjs +37 -12
  54. package/js/factory/state.mjs +25 -6
  55. package/js/hosts/done-checks.mjs +6 -0
  56. package/js/hosts/geneseed-dir.mjs +3 -2
  57. package/js/hosts/gitref.mjs +5 -3
  58. package/js/hosts/hook-tap.mjs +104 -0
  59. package/js/hosts/hooks-context.mjs +30 -3
  60. package/js/hosts/hooks-learn.mjs +47 -16
  61. package/js/hosts/hooks-prims.mjs +52 -3
  62. package/js/hosts/hooks.mjs +69 -42
  63. package/js/hosts/hosts.mjs +80 -12
  64. package/js/hosts/installs.mjs +7 -0
  65. package/js/hosts/loss.mjs +6 -1
  66. package/js/hosts/native.mjs +14 -5
  67. package/js/hosts/owned.mjs +7 -6
  68. package/js/hosts/ownership-gate.mjs +14 -1
  69. package/js/hosts/settings.mjs +245 -103
  70. package/js/hosts/shim.mjs +4 -4
  71. package/js/hosts/usage.mjs +9 -3
  72. package/js/inspect/checks-probe.mjs +66 -5
  73. package/js/inspect/checks-repo.mjs +196 -2
  74. package/js/inspect/cost.mjs +34 -2
  75. package/js/inspect/diff.mjs +16 -1
  76. package/js/inspect/doctor.mjs +13 -4
  77. package/js/inspect/excludes.mjs +18 -6
  78. package/js/inspect/status.mjs +35 -7
  79. package/js/inspect/validate.mjs +44 -21
  80. package/js/lib/machine-dir.mjs +1 -1
  81. package/js/lib/node-floor.mjs +46 -6
  82. package/js/maintain/uninstall.mjs +70 -17
  83. package/js/maintain/update.mjs +31 -7
  84. package/js/ui/cli.mjs +34 -4
  85. package/js/ui/menu.mjs +1 -1
  86. package/js/ui/tui.mjs +11 -14
  87. package/js/web/actions.mjs +3 -9
  88. package/js/web/api.mjs +28 -10
  89. package/js/web/daemon.mjs +0 -1
  90. package/js/web/server.mjs +1 -0
  91. package/js/web/state.mjs +37 -16
  92. package/package.json +1 -1
  93. package/src/AGENT.md.tmpl +23 -17
  94. package/src/agents/_template.md +1 -1
  95. package/src/agents/advocate.md +1 -1
  96. package/src/agents/developer.md +12 -3
  97. package/src/agents/empiricist.md +1 -1
  98. package/src/agents/framer.md +1 -1
  99. package/src/agents/historian.md +1 -1
  100. package/src/agents/operator.md +1 -1
  101. package/src/agents/pragmatist.md +1 -1
  102. package/src/agents/researcher.md +1 -1
  103. package/src/agents/skeptic.md +1 -1
  104. package/src/agents/steward.md +1 -1
  105. package/src/agents/user-advocate.md +1 -1
  106. package/src/agents/visionary.md +1 -1
  107. package/src/bricks/intake.md +10 -3
  108. package/src/bricks/retro.md +13 -3
  109. package/src/doctrines/comms.md +1 -1
  110. package/src/doctrines/ops.md +1 -1
  111. package/src/doctrines/process.md +7 -5
  112. package/src/factories/analysis-to-build.json +1 -0
  113. package/src/factories/bug-report-to-fix.json +1 -0
  114. package/src/factories/issue-to-pr.json +1 -0
  115. package/src/laws/universal.md +2 -2
  116. package/src/modes/foreman.md +8 -14
  117. package/src/skills/commit.md +7 -2
  118. package/src/skills/debug.md +1 -1
  119. package/src/skills/diagram-design/SKILL.md +1 -1
  120. package/src/skills/diagram-design/VENDOR.md +3 -1
  121. package/src/skills/factory-forge.md +5 -3
  122. package/src/skills/factory.md +22 -1
  123. package/src/skills/geneseed.md +1 -1
  124. package/src/skills/handoff.md +1 -1
  125. package/src/skills/parallel-agents.md +1 -1
  126. package/src/skills/pipeline.md +6 -6
  127. package/src/skills/plan.md +7 -3
  128. package/src/skills/spring-testing.md +1 -1
  129. package/themes/biker.json +78 -78
  130. package/themes/commentator.json +81 -81
  131. package/themes/cyberpunk.json +79 -79
  132. package/themes/gamer.json +77 -77
  133. package/themes/imperial.json +82 -82
  134. package/themes/joker.json +79 -79
  135. package/themes/marvin.json +82 -82
  136. package/themes/mean.json +82 -82
  137. package/themes/military.json +78 -78
  138. package/themes/neutral.json +78 -78
  139. package/themes/pirate.json +79 -79
  140. package/themes/sports.json +79 -79
  141. package/themes/verstappen.json +78 -78
  142. package/themes/wizard.json +79 -79
  143. package/web/dist/assets/ActiveLoops-BJJN3P-V.js +1 -0
  144. package/web/dist/assets/Activity-WQ3ykgxU.js +1 -0
  145. package/web/dist/assets/ActivityDetail-7rt04SkS.js +1 -0
  146. package/web/dist/assets/{Bonsai-DSwUbavu.js → Bonsai-BBl4XXqs.js} +1 -1
  147. package/web/dist/assets/{CopyButton-BzRQz7k2.js → CopyButton-Beven8yn.js} +1 -1
  148. package/web/dist/assets/Dashboard-BgLArtgu.js +2 -0
  149. package/web/dist/assets/Docs-B5aHp86J.js +5 -0
  150. package/web/dist/assets/Factories-BjqzXAw8.js +1 -0
  151. package/web/dist/assets/GreenhouseView-Bce212qd.js +1 -0
  152. package/web/dist/assets/Installs-B1OsrHXF.js +3 -0
  153. package/web/dist/assets/JournalView-CV4omyww.js +1 -0
  154. package/web/dist/assets/Kits-CW1e7xNa.js +1 -0
  155. package/web/dist/assets/Laws-1Ckf1lbs.js +4 -0
  156. package/web/dist/assets/LibRows-Dag1s0ZX.js +1 -0
  157. package/web/dist/assets/Library-B3FuFLel.js +3 -0
  158. package/web/dist/assets/Loops-CwqgnLNw.js +2 -0
  159. package/web/dist/assets/Markdown-CxkA7940.js +71 -0
  160. package/web/dist/assets/OperatorHudView-JmYY1pBR.js +1 -0
  161. package/web/dist/assets/Personal-DKLgLa7Z.js +2 -0
  162. package/web/dist/assets/Settings-BwErnh-R.js +1 -0
  163. package/web/dist/assets/Tabs-8zsyEPSK.js +1 -0
  164. package/web/dist/assets/index-CRWqKxfY.css +1 -0
  165. package/web/dist/assets/index-Ce6qF2nG.js +6 -0
  166. package/web/dist/assets/usePoll-D5c_qIFZ.js +1 -0
  167. package/web/dist/index.html +2 -2
  168. package/adapters/claude-code/settings.json +0 -52
  169. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +0 -1
  170. package/web/dist/assets/Activity-DlQ30znB.js +0 -1
  171. package/web/dist/assets/ActivityDetail-CG0mn5fW.js +0 -1
  172. package/web/dist/assets/Dashboard-Ce3UOsxJ.js +0 -2
  173. package/web/dist/assets/Docs-CisVnYqv.js +0 -5
  174. package/web/dist/assets/Factories-Dq5oW4CU.js +0 -1
  175. package/web/dist/assets/GreenhouseView-y9WAfcc_.js +0 -1
  176. package/web/dist/assets/Installs-m4GElwFW.js +0 -3
  177. package/web/dist/assets/JournalView-DeBLRNGc.js +0 -1
  178. package/web/dist/assets/Kits-DJYVAnyE.js +0 -1
  179. package/web/dist/assets/Laws-CNpc_8ZV.js +0 -4
  180. package/web/dist/assets/LibRows-RO5bvXth.js +0 -1
  181. package/web/dist/assets/Library-Dg0ScciC.js +0 -3
  182. package/web/dist/assets/Loops-CjEdo-NG.js +0 -2
  183. package/web/dist/assets/Markdown-0ORz7tAc.js +0 -69
  184. package/web/dist/assets/OperatorHudView-2ujVMjq1.js +0 -1
  185. package/web/dist/assets/Personal-D0yS7ahT.js +0 -2
  186. package/web/dist/assets/Settings-DEN0U8QI.js +0 -1
  187. package/web/dist/assets/Tabs-But5R6_r.js +0 -1
  188. package/web/dist/assets/index-Ck42AbRX.js +0 -6
  189. package/web/dist/assets/index-PG_ukkh6.css +0 -1
  190. package/web/dist/assets/usePoll-o8ul-Sog.js +0 -1
@@ -179,9 +179,13 @@ const VISIBLE =
179
179
  (process.env.GENESEED_CONTEXT_TRANSFORM || "").toLowerCase())
180
180
  const TRANSFORM = !VISIBLE
181
181
  // Fallback state (module-level — OpenCode keeps ONE copy of the plugin loaded):
182
- // `transformSeen` flips the first time the experimental hook fires; if a request
183
- // completes (session.idle) while it is still false, the build lacks the hook and
184
- // `fallbackVisible` switches delivery to the classic visible injection.
182
+ // `transformSeen` flips the first time the experimental hook fires; if a MODEL REQUEST
183
+ // completes (session.idle, with an assistant message in that session's transcript) while
184
+ // it is still false, the build lacks the hook and `fallbackVisible` switches delivery to
185
+ // the classic visible injection. The latch is not for life: the hook firing later clears
186
+ // it, because that is the proof the build has the hook after all. It once latched on any
187
+ // idle seen before the first transform call — an idle with no request behind it was
188
+ // enough — and stayed latched for the whole process, visible delivery in every session.
185
189
  let transformSeen = false
186
190
  let fallbackVisible = false
187
191
  function log(msg) { if (DEBUG) console.error(`[geneseed-context] ${msg}`) }
@@ -221,8 +225,8 @@ async function isDir(p) {
221
225
  // context.json is not here: it is a manifest, honoured by resolveSource. geneseed-wiki.jsonc
222
226
  // is not here either: the MACHINE WIKI block below already renders it in full.
223
227
  const SESSION_FILES = ["user-rules.md", "PROFILE.md", "memory/MEMORY.md", "notebook/NOTEBOOK.md"]
224
- // The wiki manifest's names, newest first: WIKI_NAMES in js/lib/machine-dir.mjs.
225
- const WIKI_NAMES = ["geneseed-wiki.jsonc", "wiki.jsonc", "wiki.json"]
228
+ // The wiki manifest's names, newest first: js/lib/machine-dir.mjs's line (node tests/twins.mjs).
229
+ const WIKI_NAMES = ['geneseed-wiki.jsonc', 'wiki.jsonc', 'wiki.json'];
226
230
  const SEED_SHA256 = new Set([
227
231
  "5c2e92fb1acde041e02d9ebf158460d8ff7a07cbc2b447859631604610130721", // user-rules.md
228
232
  "29e012c3c4349ea62a9082cbd04bb25599a0ec280d62c33f6e10742809471816", // PROFILE.md
@@ -284,12 +288,38 @@ async function draftLine() {
284
288
  } catch { return null }
285
289
  }
286
290
 
291
+ // ---- rules preamble twin: BEGIN — adapters/opencode/plugins/geneseed-context.js carries everything
292
+ // down to the END marker verbatim, with `export ` dropped (node tests/twins.mjs --write keeps it).
293
+
294
+ /**
295
+ * SHA-256 of the `user-rules.md` seed with its trailing newlines trimmed: the explanation every
296
+ * rules file starts with, until its owner edits it. Hashed, not imported, for `SEED_SHA256`'s
297
+ * reason; tests/unit/claude.test.mjs derives it from `SESSION_SEEDS`.
298
+ */
299
+ const RULES_PREAMBLE_SHA256 = 'd6973e837c9bf25b50ce068832ceef0a5e5ed2b5931c2c488428ad68aad758c3';
300
+ // A rule's heading, at column 0: the seed's own example (` ## R1 — …`) is indented.
301
+ const RULE_HEADING_RE = /^## R\d+\b/m;
302
+
303
+ /**
304
+ * `text` from its first rule on, when the text above that rule is still the seed's, byte for byte
305
+ * once CRLF is folded: the seed explains the file to its owner, and it cost 1 331 of 4 474
306
+ * characters at every session and sub-agent start. Any prose the owner wrote above the rules stays.
307
+ */
308
+ function withoutRulesPreamble(text) {
309
+ const rule = RULE_HEADING_RE.exec(text);
310
+ const head = rule ? text.slice(0, rule.index).replace(/\n+$/, '') : null;
311
+ return head !== null && createHash('sha256').update(head).digest('hex') === RULES_PREAMBLE_SHA256
312
+ ? text.slice(rule.index) : text;
313
+ }
314
+ // ---- rules preamble twin: END
315
+
287
316
  // A session file's text, CRLF-folded and trimmed; null when missing, unreadable or still its seed.
317
+ // A rules file's seed explanation above its first rule is dropped, as on the hook.
288
318
  async function sessionText(abs) {
289
319
  let text
290
320
  try { text = (await fs.readFile(abs, "utf8")).replace(/\r\n/g, "\n") } catch { return null }
291
321
  if (SEED_SHA256.has(createHash("sha256").update(text).digest("hex"))) return null
292
- return text.replace(/\n+$/, "")
322
+ return withoutRulesPreamble(text).replace(/\n+$/, "")
293
323
  }
294
324
 
295
325
  // Session files in force for the harness dir, changed from their seed: [{ rel, abs, text, label }],
@@ -430,23 +460,53 @@ function repoRoot(ctx) {
430
460
 
431
461
  // ---- model self-awareness (best-effort) --------------------------------------
432
462
  // Surface the model the session is actually using so the agent reasons within its
433
- // real limits (awesome-opencode "Model Announcer"). Sources, first hit wins: an
434
- // assistant message's info.providerID/modelID in the outgoing transcript — the same
435
- // fields the learn plugin reads — then $GENESEED_MODEL ("provider/model"). Unknown ->
436
- // no line (graceful: the first turn often has no assistant message yet). It is added
437
- // per request, OUTSIDE the cached block, so one cache serves every model.
463
+ // real limits (awesome-opencode "Model Announcer"). Sources, first hit wins: the outgoing
464
+ // transcript — an assistant message's info.providerID/modelID (the fields the learn plugin
465
+ // reads) or a user message's info.model.{providerID,modelID} — then $GENESEED_MODEL
466
+ // ("provider/model"). Unknown -> no line. It is added per request, OUTSIDE the cached
467
+ // block, so one cache serves every model.
468
+ //
469
+ // THE DECISION IS PINNED PER SESSION (`pinnedModel`), "no line" included. The block is the
470
+ // first message of every request, so it is the head of the provider's prompt-cache prefix:
471
+ // a line that appears on request 2 — the first with an assistant message — rewrites message
472
+ // 0 and re-bills the whole transcript once per session. The user message is read so that
473
+ // request 1 can already answer; where it cannot, the session gets no line rather than a
474
+ // late one. A model switched mid-session is therefore not announced, by design.
475
+ // UNVERIFIED ON A REAL HOST: that OpenCode 1 fills `info.model` on the user message of the
476
+ // first request. No run here has shown it set; where it is absent, a session with no
477
+ // $GENESEED_MODEL simply has no model line.
438
478
  function modelFromMessages(messages) {
439
479
  if (!Array.isArray(messages)) return null
440
480
  let found = null
441
481
  for (const m of messages) {
442
482
  const info = m?.info ?? {}
443
- if (info.role !== "assistant") continue
444
- const providerID = info.providerID ?? info.provider
445
- const modelID = info.modelID ?? info.model
446
- if (providerID && modelID) found = `${providerID}/${modelID}` // last wins (latest turn)
483
+ let providerID, modelID
484
+ if (info.role === "assistant") {
485
+ providerID = info.providerID ?? info.provider
486
+ modelID = info.modelID ?? info.model
487
+ } else if (info.role === "user" && info.model && typeof info.model === "object") {
488
+ providerID = info.model.providerID
489
+ modelID = info.model.modelID
490
+ }
491
+ if (typeof providerID === "string" && providerID && typeof modelID === "string" && modelID) {
492
+ found = `${providerID}/${modelID}` // last wins (latest turn)
493
+ }
447
494
  }
448
495
  return found
449
496
  }
497
+ // The model line for this session: decided once, then repeated. `pins` is the instance's own
498
+ // Map (session id -> "provider/model" or null); it drops a session on `session.deleted` and
499
+ // is capped, oldest first, so a long-lived process cannot grow it without bound — a session
500
+ // evicted and still running re-decides once, which costs one rewrite of the block.
501
+ const MODEL_PIN_CAP = 256
502
+ function pinnedModel(pins, sid, decide) {
503
+ if (!sid) return decide() || null
504
+ if (pins.has(sid)) return pins.get(sid)
505
+ const model = decide() || null
506
+ if (pins.size >= MODEL_PIN_CAP) pins.delete(pins.keys().next().value)
507
+ pins.set(sid, model)
508
+ return model
509
+ }
450
510
  function envModelStr() {
451
511
  const v = process.env.GENESEED_MODEL
452
512
  return v && v.includes("/") ? v : null
@@ -947,6 +1007,22 @@ async function cachedBlockText(root, cache) {
947
1007
  return text
948
1008
  }
949
1009
 
1010
+ // Per INSTANCE, as `cache` above, and keyed by directory: `sovereignBypass` (two JSON reads)
1011
+ // and `doneChecksOf` (manifest reads) ran on EVERY request while the block they gate is cached
1012
+ // for BLOCK_TTL_MS, so they get the same TTL. A rejection is not kept: the next call retries.
1013
+ function ttlMemo(fn) {
1014
+ const hits = new Map()
1015
+ return (key) => {
1016
+ const now = Date.now()
1017
+ const hit = hits.get(key)
1018
+ if (hit && now - hit.at < BLOCK_TTL_MS) return hit.p
1019
+ const p = Promise.resolve().then(() => fn(key))
1020
+ hits.set(key, { p, at: now })
1021
+ p.catch(() => { if (hits.get(key)?.p === p) hits.delete(key) })
1022
+ return p
1023
+ }
1024
+ }
1025
+
950
1026
  // ---- cross-instance idempotency ----------------------------------------------
951
1027
  async function alreadyInjected(client, sid) {
952
1028
  try {
@@ -1052,13 +1128,25 @@ function takeWeakened(sid) {
1052
1128
  }
1053
1129
 
1054
1130
  // ---- The done gate (#289): the OpenCode twin of js/hosts/hooks-done.mjs ----------------
1055
- // OpenCode has no turn-end event a plugin can block on, so its ceiling is a reminder: on the
1056
- // request AFTER a turn that edited files without the project's declared checks passing
1057
- // (`.geneseed/done-checks.txt`), one invisible user message says which checks are owed. Only V1
1131
+ // OpenCode has no turn-end event a plugin can block on, so its ceiling is a reminder: on
1132
+ // EVERY request — mid-turn, between two tool calls, as much as at the next prompt — whose
1133
+ // transcript holds an edit with the project's declared checks (`.geneseed/done-checks.txt`)
1134
+ // not passed since, one invisible user message says which checks are owed. It is judged over
1135
+ // the previous turn and the current one (`doneOwed`), so it starts on the request right after
1136
+ // the edit and stops when the checks pass or a second prompt has gone by.
1137
+ //
1138
+ // It is the LAST message of the request, never the first. It comes and goes from one request
1139
+ // to the next, and a message put at the front shifts every message behind it: the provider's
1140
+ // prompt cache, which matches on the prefix, is thrown away each time the reminder toggles.
1141
+ // At the end it changes nothing before it, and it is also where a model weighs an instruction
1142
+ // most. The same holds for the weakened-test reminder below, on both majors.
1143
+ // UNVERIFIED ON A REAL HOST: that every provider accepts a synthetic user message after the
1144
+ // tool results of an unfinished tool loop (the mid-turn case). Only V1
1058
1145
  // (`messages.transform`, whose tool parts carry `state.status` and the shell's
1059
1146
  // `metadata.exit`); OpenCode 2's message shape for tool calls is unverified, so V2 is not
1060
1147
  // judged and says so once. Fails open on every shape it does not recognise (ADR 0007).
1061
- // `runsUnpiped` is a hand-mirrored twin; tests/plugins/context_done.test.mjs runs both on one table.
1148
+ // `runsUnpiped` is js/hosts/hooks-done.mjs's, copied by `node tests/twins.mjs --write`;
1149
+ // tests/plugins/context_done.test.mjs runs both on one table.
1062
1150
  const DONE_LIST = ".geneseed/done-checks.txt"
1063
1151
  const DONE_EDIT_TOOLS = new Set(["edit", "write", "patch", "apply_patch", "multiedit"])
1064
1152
  const DONE_SHELL_TOOLS = new Set(["bash", "shell"])
@@ -1102,30 +1190,50 @@ async function readDoneChecks(root) {
1102
1190
  // The inference twin of js/hosts/done-checks.mjs (user decision 2026-10-29): with no list, the
1103
1191
  // root manifests imply the checks, each a GROUP of accepted forms. Here they only shape the
1104
1192
  // reminder's wording ("advisory"); OpenCode never blocks either way.
1105
- // tests/plugins/context_done.test.mjs runs both copies over the same fixtures.
1106
- const PM_LOCKS = [["bun.lockb", "bun"], ["bun.lock", "bun"], ["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"]]
1107
- const PM_SCRIPTS = ["test", "lint", "typecheck"]
1193
+ // tests/plugins/context_done.test.mjs runs both copies over the same fixtures. The tables are
1194
+ // the hook's own (the twin block); `inferDoneChecks` and `doneChecksOf` are by hand, because
1195
+ // they await where the hook reads synchronously.
1196
+ // ---- done-check tables twin: BEGIN — adapters/opencode/plugins/geneseed-context.js carries
1197
+ // everything down to the END marker verbatim, with `export ` dropped (node tests/twins.mjs --write
1198
+ // keeps it). Its `inferDoneChecks` is the async reading of the one below, kept by hand.
1199
+
1200
+ // The package manager a lockfile names; first hit wins, npm without one. Exported for the gate that
1201
+ // holds the factory `checks` brick's restatement of these rules to this list (factory_graph test).
1202
+ const PM_LOCKS = [['bun.lockb', 'bun'], ['bun.lock', 'bun'], ['pnpm-lock.yaml', 'pnpm'], ['yarn.lock', 'yarn']];
1203
+ const PM_SCRIPTS = ['test', 'lint', 'typecheck'];
1204
+
1205
+ /** One package.json script as a check: the lockfile's own spellings, plus npm's (npm runs any). */
1108
1206
  function scriptCheck(pm, s) {
1109
- const npm = s === "test" ? ["npm test", "npm run test", "npm t"] : [`npm run ${s}`]
1110
- const own = pm === "npm" ? [] : pm === "bun" ? [`bun run ${s}`] : [`${pm} ${s}`, `${pm} run ${s}`]
1111
- return { label: own[0] ?? npm[0], forms: [...own, ...npm] }
1207
+ const npm = s === 'test' ? ['npm test', 'npm run test', 'npm t'] : [`npm run ${s}`];
1208
+ // `bun test` is bun's own runner, not the `test` script: only `bun run` runs the script.
1209
+ const own = pm === 'npm' ? [] : pm === 'bun' ? [`bun run ${s}`] : [`${pm} ${s}`, `${pm} run ${s}`];
1210
+ return { label: own[0] ?? npm[0], forms: [...own, ...npm] };
1112
1211
  }
1212
+
1213
+ // Each wrapper spelling (POSIX and Windows) times each task that runs the tests, with and without
1214
+ // a leading `clean`. `refuse` names the flags that make the same command skip the tests: a
1215
+ // segment carrying one is no pass (`hooks-done.mjs`'s `groupPasses`).
1113
1216
  const wrapped = (label, bins, tasks, refuse) => ({
1114
1217
  label, refuse, forms: bins.flatMap((b) => tasks.flatMap((t) => [`${b} ${t}`, `${b} clean ${t}`])),
1115
- })
1116
- const MAVEN = wrapped("mvn test", ["mvn", "./mvnw", ".\\mvnw", "mvnw", "mvnw.cmd"], ["test", "verify", "install"],
1117
- /(?:^|\s)-D(?:skipTests|maven\.test\.skip)(?=[=\s]|$)/)
1118
- const GRADLE = wrapped("gradle test", ["gradle", "./gradlew", ".\\gradlew", "gradlew", "gradlew.bat"], ["test", "build", "check"],
1119
- /(?:^|\s)(?:-x|--exclude-task)[ =](?:\S*:)?test(?=\s|$)/)
1120
- const PYTEST = { label: "pytest", forms: ["pytest", "python -m pytest", "python3 -m pytest", "py -m pytest", "poetry run pytest"] }
1218
+ });
1219
+ const MAVEN = wrapped('mvn test', ['mvn', './mvnw', '.\\mvnw', 'mvnw', 'mvnw.cmd'], ['test', 'verify', 'install'],
1220
+ /(?:^|\s)-D(?:skipTests|maven\.test\.skip)(?=[=\s]|$)/);
1221
+ const GRADLE = wrapped('gradle test', ['gradle', './gradlew', '.\\gradlew', 'gradlew', 'gradlew.bat'], ['test', 'build', 'check'],
1222
+ /(?:^|\s)(?:-x|--exclude-task)[ =](?:\S*:)?test(?=\s|$)/);
1223
+ // shortcut: no `uv`-prefixed form — that spelling trips the no-Python gates in
1224
+ // tests/unit/package_manifest.test.mjs (user decision 2026-10-29: no exemption), so a uv user's
1225
+ // run reads as unproven, which is only an advisory.
1226
+ const PYTEST = { label: 'pytest', forms: ['pytest', 'python -m pytest', 'python3 -m pytest', 'py -m pytest', 'poetry run pytest'] };
1121
1227
  const MANIFEST_CHECKS = [
1122
- ["pom.xml", MAVEN],
1123
- ["build.gradle", GRADLE],
1124
- ["build.gradle.kts", GRADLE],
1125
- ["pyproject.toml", PYTEST],
1126
- ["Cargo.toml", { label: "cargo test", forms: ["cargo test"], refuse: /(?:^|\s)--no-run(?=\s|$)/ }],
1127
- ["go.mod", { label: "go test", forms: ["go test"] }],
1128
- ]
1228
+ ['pom.xml', MAVEN],
1229
+ ['build.gradle', GRADLE],
1230
+ ['build.gradle.kts', GRADLE],
1231
+ ['pyproject.toml', PYTEST],
1232
+ ['Cargo.toml', { label: 'cargo test', forms: ['cargo test'], refuse: /(?:^|\s)--no-run(?=\s|$)/ }],
1233
+ ['go.mod', { label: 'go test', forms: ['go test'] }],
1234
+ ];
1235
+
1236
+ // ---- done-check tables twin: END
1129
1237
  const exists = (p) => fs.access(p).then(() => true, () => false)
1130
1238
  // The Node hook's `gitRootOf`: the nearest ancestor holding `.git` (a dir, or a worktree's file).
1131
1239
  async function gitRootOf(dir) {
@@ -1187,15 +1295,26 @@ async function doneLine(dir, judged = true) {
1187
1295
  // In an application repo (a git root holding a build manifest) whose root AGENTS.md has no
1188
1296
  // `## Ownership` section outside the Geneseed block, the developer's `Setup: declined <date>`
1189
1297
  // line in `.geneseed/ownership.md` gets one context line, so the decline stays visible. Same
1190
- // manifests, strip, section and decline patterns as the hook (and geneseed-guard.js, whose gate
1191
- // defers on that line). `--no-ownership-gate` (`Ownership gate: off` in AGENT.md) prints nothing.
1192
- const OWN_MANIFESTS = new Set(["package.json", "pom.xml", "pyproject.toml", "go.mod", "Cargo.toml",
1193
- "composer.json", "Gemfile"])
1194
- const isOwnManifest = (n) => OWN_MANIFESTS.has(n) || n.startsWith("build.gradle") || n.endsWith(".csproj")
1298
+ // manifests, section and decline patterns as the hook (and geneseed-guard.js, whose gate defers
1299
+ // on that line): they are its own lines, kept by `node tests/twins.mjs --write`. `--no-ownership-gate` (`Ownership gate: off` in AGENT.md) prints nothing.
1300
+ // ---- ownership shape twin: BEGIN — adapters/opencode/plugins/geneseed-guard.js and
1301
+ // geneseed-context.js carry everything down to the END marker verbatim (node tests/twins.mjs
1302
+ // --write keeps it), and the one-line `WRITE_NAME_RE`, `safeStem` and `DECLINED_RE` below too.
1303
+
1304
+ // D5: the build manifests that make a git root an "application". Exact names, plus two families.
1305
+ const MANIFESTS = new Set(['package.json', 'pom.xml', 'pyproject.toml', 'go.mod', 'Cargo.toml',
1306
+ 'composer.json', 'Gemfile']);
1307
+ const isManifest = (n) => MANIFESTS.has(n) || n.startsWith('build.gradle') || n.endsWith('.csproj');
1308
+
1309
+ // On a Bob project install the managed block holds the whole carrier, `#### Ownership` included —
1310
+ // hence the strip (`withoutBlocks`) and the exact `##` heading match. `\r?`: a CRLF file's `$`
1311
+ // sits after the `\r`.
1312
+ const SECTION_RE = /^## Ownership[ \t]*\r?$/m;
1313
+
1314
+ // ---- ownership shape twin: END
1195
1315
  // Whole-line markers: js/lib/managed-block.mjs BLOCK_RE_SOURCE, by value (a plugin imports nothing).
1196
1316
  const OWN_BLOCK_RE = /^<!-- BEGIN GENESEED -->[ \t]*\r?\n[\s\S]*?^<!-- END GENESEED -->[ \t]*\r?$/gm
1197
- const OWN_SECTION_RE = /^## Ownership[ \t]*\r?$/m
1198
- const OWN_DECLINED_RE = /^Setup:[ \t]*declined[ \t]+(\d{4}-\d{2}-\d{2})[ \t]*\r?$/m
1317
+ const DECLINED_RE = /^Setup:[ \t]*declined[ \t]+(\d{4}-\d{2}-\d{2})[ \t]*\r?$/m;
1199
1318
  let ownershipGateOffOnce = null
1200
1319
  function ownershipGateOff() {
1201
1320
  ownershipGateOffOnce ??= (async () => {
@@ -1208,13 +1327,13 @@ function ownershipGateOff() {
1208
1327
  }
1209
1328
  async function ownershipLine(dir) {
1210
1329
  const root = await gitRootOf(dir)
1211
- if (!root || !(await fs.readdir(root)).some(isOwnManifest)) return null
1330
+ if (!root || !(await fs.readdir(root)).some(isManifest)) return null
1212
1331
  const agents = await fs.readFile(path.join(root, "AGENTS.md"), "utf8").catch(() => "")
1213
- if (OWN_SECTION_RE.test(agents.replace(OWN_BLOCK_RE, ""))) return null
1332
+ if (SECTION_RE.test(agents.replace(OWN_BLOCK_RE, ""))) return null
1214
1333
  // The decline lives in the MAIN worktree (a fresh linked worktree per session must not lose it).
1215
1334
  const home = (await mainWorktreeOf(root)) ?? root
1216
1335
  const personal = await fs.readFile(path.join(home, ".geneseed", "ownership.md"), "utf8").catch(() => "")
1217
- const since = OWN_DECLINED_RE.exec(personal.replace(/^\uFEFF/, ""))?.[1]
1336
+ const since = DECLINED_RE.exec(personal.replace(/^\uFEFF/, ""))?.[1]
1218
1337
  return since ? `Ownership: setup declined since ${since} — not set up; say "set up ownership" to run it` : null
1219
1338
  }
1220
1339
 
@@ -1372,6 +1491,21 @@ export const GeneseedContext = async (ctx) => {
1372
1491
  const done = new Set()
1373
1492
  const root = repoRoot(ctx)
1374
1493
  const blockCache = { text: null, at: 0 }
1494
+ const bypassed = ttlMemo(sovereignBypass)
1495
+ const doneChecks = ttlMemo(doneChecksOf)
1496
+ const modelPins = new Map()
1497
+
1498
+ // Did a model request really run in this session? An assistant message in its transcript
1499
+ // is the evidence; an unreadable transcript is not, and the next idle asks again.
1500
+ async function sawModelRequest(sid) {
1501
+ try {
1502
+ const msgs = await client.session.messages({ path: { id: sid } })
1503
+ const list = Array.isArray(msgs) ? msgs : (msgs?.data ?? [])
1504
+ return list.some((m) => m?.info?.role === "assistant")
1505
+ } catch {
1506
+ return false
1507
+ }
1508
+ }
1375
1509
 
1376
1510
  // Visible delivery — post the block as a noReply session message. Used when
1377
1511
  // GENESEED_CONTEXT_VISIBLE forces it, and by the transform fallback below.
@@ -1429,21 +1563,26 @@ export const GeneseedContext = async (ctx) => {
1429
1563
  },
1430
1564
 
1431
1565
  event: async ({ event }) => {
1432
- if (!event || INJECT_OFF) return
1433
- if (await sovereignBypass(root)) return
1566
+ if (!event) return
1434
1567
  const sid =
1435
1568
  event.properties?.sessionID ?? event.payload?.sessionID ??
1436
1569
  event.properties?.info?.id ?? event.payload?.info?.id
1570
+ if (event.type === "session.deleted") { modelPins.delete(sid); return }
1571
+ if (INJECT_OFF) return
1572
+ if (await bypassed(root)) return
1437
1573
  if (event.type === "session.created") {
1438
1574
  if (TRANSFORM && !fallbackVisible) return // invisible delivery handles it
1439
1575
  await injectVisible(sid)
1440
1576
  return
1441
1577
  }
1442
- // Transform fallback: the session went idle (a request completed) yet the
1443
- // experimental hook never fired in this process — this build lacks it. Engage
1444
- // the visible delivery so context still arrives, injecting into THIS session
1445
- // right away (one turn late) rather than waiting for the next session.
1578
+ // Transform fallback: the session went idle after a model request (its transcript
1579
+ // holds an assistant message) yet the experimental hook never fired in this
1580
+ // process — this build lacks it. Engage the visible delivery so context still
1581
+ // arrives, injecting into THIS session right away (one turn late) rather than
1582
+ // waiting for the next session. An idle with no request behind it proves nothing
1583
+ // about the hook and latches nothing.
1446
1584
  if (event.type === "session.idle" && TRANSFORM && !transformSeen && !fallbackVisible) {
1585
+ if (!(await sawModelRequest(sid)) || transformSeen) return
1447
1586
  fallbackVisible = true
1448
1587
  log("transform hook absent on this build — falling back to visible injection")
1449
1588
  await injectVisible(sid)
@@ -1459,7 +1598,7 @@ export const GeneseedContext = async (ctx) => {
1459
1598
  // OpenCode hook; if it is absent in a build this key is simply never called.
1460
1599
  "experimental.session.compacting": async (_input, output) => {
1461
1600
  if (INJECT_OFF || (TRANSFORM && !fallbackVisible)) return
1462
- if (await sovereignBypass(root)) return
1601
+ if (await bypassed(root)) return
1463
1602
  try {
1464
1603
  const { block } = await resolveBlock(root)
1465
1604
  if (block && output && Array.isArray(output.context)) {
@@ -1478,22 +1617,29 @@ export const GeneseedContext = async (ctx) => {
1478
1617
  // detects that and takes over with the visible delivery.
1479
1618
  "experimental.chat.messages.transform": async (_input, output) => {
1480
1619
  transformSeen = true // the hook exists on this build
1620
+ // …so a fallback latched before it first fired was a wrong guess: back to invisible.
1621
+ // A session that already got the visible block keeps it; the MARKER check below is
1622
+ // what stops a second one.
1623
+ fallbackVisible = false
1481
1624
  // One scope decision per request, shared by the done gate and the context block:
1482
1625
  // both end on an empty request, an excluded repo, or a skipped session.
1483
1626
  if (!output || !Array.isArray(output.messages) || !output.messages.length) return
1484
1627
  const sid = output.messages[0]?.info?.sessionID
1485
- if (await sovereignBypass(root) || await skipSession(sid)) return
1486
- // The done gate's reminder: FIRST, and independent of the context block:
1628
+ if (await bypassed(root) || await skipSession(sid)) return
1629
+ // The done gate's reminder: decided FIRST, and independent of the context block:
1487
1630
  // INJECT_OFF and the visible delivery leave it on, and no early return below can skip it.
1488
1631
  // Its own function, so its early returns end the reminder, never the context injection.
1632
+ // Both reminders are PUSHED — the last messages of the request — and the context block
1633
+ // alone is unshifted, so message 0 is the same on every request (see the done gate's
1634
+ // docblock for why).
1489
1635
  await (async () => {
1490
1636
  if (await doneGateOff()) return
1491
- const { root: gitRoot, source, blocking, checks } = await doneChecksOf(root)
1637
+ const { root: gitRoot, source, blocking, checks } = await doneChecks(root)
1492
1638
  if (!checks.length) return
1493
1639
  const owed = doneOwed(output.messages, checks, gitRoot)
1494
1640
  if (!owed.length) return
1495
1641
  const stamp = Date.now()
1496
- output.messages.unshift({
1642
+ output.messages.push({
1497
1643
  info: { id: `geneseed-done-${stamp}`, role: "user", sessionID: sid, time: { created: stamp } },
1498
1644
  parts: [{ id: `geneseed-done-part-${stamp}`, type: "text", text:
1499
1645
  `Geneseed (Verify Before Asserting) — files were edited, and these checks ${blocking ? "from" : "(advisory) inferred from"} `
@@ -1506,7 +1652,7 @@ export const GeneseedContext = async (ctx) => {
1506
1652
  const weakened = !(await doneGateOff()) && takeWeakened(sid)
1507
1653
  if (weakened) {
1508
1654
  const stamp = Date.now()
1509
- output.messages.unshift({
1655
+ output.messages.push({
1510
1656
  info: { id: `geneseed-weakened-${stamp}`, role: "user", sessionID: sid, time: { created: stamp } },
1511
1657
  parts: [{ id: `geneseed-weakened-part-${stamp}`, type: "text", text: weakened }],
1512
1658
  })
@@ -1520,9 +1666,11 @@ export const GeneseedContext = async (ctx) => {
1520
1666
  if (present) return
1521
1667
  const cached = await cachedBlockText(root, blockCache)
1522
1668
  if (!cached) return
1523
- // Model line is request-specific (kept out of the cache): prefer the live
1524
- // transcript on this request, fall back to $GENESEED_MODEL.
1525
- const text = withModel(cached, modelFromMessages(output.messages) || envModelStr())
1669
+ // The model line is kept out of the cache and decided ONCE per session — the live
1670
+ // transcript of the session's first request, else $GENESEED_MODEL, else no line —
1671
+ // so no later request rewrites the block.
1672
+ const text = withModel(cached,
1673
+ pinnedModel(modelPins, sid, () => modelFromMessages(output.messages) || envModelStr()))
1526
1674
  const stamp = Date.now()
1527
1675
  output.messages.unshift({
1528
1676
  info: { id: `geneseed-context-${stamp}`, role: "user", sessionID: sid, time: { created: stamp } },
@@ -1562,6 +1710,9 @@ async function setupV2(ctx) {
1562
1710
  const root = repoRoot({ worktree: ctx?.location?.project?.directory, directory: ctx?.location?.directory })
1563
1711
  // `judged: false`: OpenCode 2 never judges a turn, so the done line claims no verdict.
1564
1712
  const blockCache = { text: null, at: 0, judged: false }
1713
+ const bypassed = ttlMemo(sovereignBypass)
1714
+ const doneChecks = ttlMemo(doneChecksOf)
1715
+ const modelPins = new Map()
1565
1716
  // Same scope rule as V1's skipSession. V2's info names the parent `parentID` only, so only
1566
1717
  // that and the title are passed on.
1567
1718
  const skipSession = sessionSkipper(async (sid) => {
@@ -1571,21 +1722,22 @@ async function setupV2(ctx) {
1571
1722
 
1572
1723
  // The done gate is not judged on OpenCode 2 (see `doneOwed`): said once, where its log goes.
1573
1724
  // The listed gate only: an inferred one would log in every repo with a manifest.
1574
- if (!(await doneGateOff()) && await doneChecksOf(root).then((d) => d.blocking && d.checks.length, () => false)) {
1725
+ if (!(await doneGateOff()) && await doneChecks(root).then((d) => d.blocking && d.checks.length, () => false)) {
1575
1726
  console.error(`[geneseed-context] done gate: ${DONE_LIST} found, but OpenCode 2 turns are not judged.`)
1576
1727
  }
1577
1728
 
1578
- // The weakened-test reminder, which INJECT_OFF and visible delivery leave on, as on V1. A V2
1729
+ // The weakened-test reminder, which INJECT_OFF and visible delivery leave on, as on V1 —
1730
+ // and, as on V1, the LAST message of the request, so the context block stays message 0. A V2
1579
1731
  // callback that throws fails the agent step, so both swallow their errors.
1580
1732
  await ctx.tool?.hook?.("execute.before", async (event) => {
1581
1733
  await noteWeakened(root, event?.sessionID, event?.tool, event?.input)
1582
1734
  })
1583
1735
  const remindWeakened = async (event) => {
1584
1736
  try {
1585
- if (!Array.isArray(event?.messages) || await sovereignBypass(root) || await doneGateOff()) return
1737
+ if (!Array.isArray(event?.messages) || await bypassed(root) || await doneGateOff()) return
1586
1738
  if (await skipSession(event.sessionID)) return
1587
1739
  const weakened = takeWeakened(event.sessionID)
1588
- if (weakened) event.messages.unshift(v2UserMessage(event.messages, weakened))
1740
+ if (weakened) event.messages.push(v2UserMessage(event.messages, weakened))
1589
1741
  } catch (err) {
1590
1742
  log(`test-weakening error: ${err?.message ?? err}`)
1591
1743
  }
@@ -1598,12 +1750,13 @@ async function setupV2(ctx) {
1598
1750
  await remindWeakened(event)
1599
1751
  if (INJECT_OFF) return
1600
1752
  try {
1601
- if (await sovereignBypass(root)) return
1753
+ if (await bypassed(root)) return
1602
1754
  if (!Array.isArray(event?.messages) || v2HasMarker(event.messages)) return
1603
1755
  if (await skipSession(event.sessionID)) return
1604
1756
  const cached = await cachedBlockText(root, blockCache)
1605
1757
  if (!cached) return
1606
- event.messages.unshift(v2UserMessage(event.messages, withModel(cached, v2Model(event.model) || envModelStr())))
1758
+ const model = pinnedModel(modelPins, event.sessionID, () => v2Model(event.model) || envModelStr())
1759
+ event.messages.unshift(v2UserMessage(event.messages, withModel(cached, model)))
1607
1760
  log("context hook: injected context invisibly")
1608
1761
  } catch (err) {
1609
1762
  log(`context hook error: ${err?.message ?? err}`)
@@ -1617,7 +1770,7 @@ async function setupV2(ctx) {
1617
1770
  await ctx.session.hook("compaction", async (event) => {
1618
1771
  if (INJECT_OFF) return
1619
1772
  try {
1620
- if (await sovereignBypass(root)) return
1773
+ if (await bypassed(root)) return
1621
1774
  if (!Array.isArray(event?.messages) || await skipSession(event.sessionID)) return
1622
1775
  const { block } = await resolveBlock(root, false)
1623
1776
  if (block) event.messages.unshift(v2UserMessage(event.messages, block.text))
@@ -1632,7 +1785,7 @@ async function setupV2(ctx) {
1632
1785
  const d = ev.data ?? {}
1633
1786
  try {
1634
1787
  if (isSkippedSession({ parentID: d.parentID, title: d.title })) continue
1635
- if (await sovereignBypass(root)) continue
1788
+ if (await bypassed(root)) continue
1636
1789
  const { block } = await resolveBlock(root, false)
1637
1790
  if (!block) continue
1638
1791
  await ctx.session.synthetic({