geneseed 5.0.1 → 5.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +4 -4
  3. package/SHIPPED.md +2 -2
  4. package/adapters/claude-code/README.md +11 -5
  5. package/adapters/openclaude/README.md +3 -1
  6. package/adapters/opencode/HOW-OPENCODE-LOADS.md +3 -0
  7. package/adapters/opencode/plugins/geneseed-context.js +12 -1
  8. package/adapters/opencode/plugins/geneseed-guard.js +594 -73
  9. package/adapters/opencode/plugins/geneseed-learn.js +1 -1
  10. package/adapters/opencode/plugins/geneseed-workflow.js +1 -1
  11. package/adapters/opencode/workflows/_runtime.js +1 -1
  12. package/bin/geneseed-cli.mjs +3 -0
  13. package/bin/geneseed-hook.mjs +31 -9
  14. package/docs/PRD.md +1 -1
  15. package/docs/README.md +4 -1
  16. package/docs/concepts/enforcement-table.md +23 -4
  17. package/docs/concepts/exclusions.md +48 -2
  18. package/docs/concepts/factories.md +151 -0
  19. package/docs/concepts/foreman-mode.md +19 -4
  20. package/docs/concepts/hook-gates.md +1 -1
  21. package/docs/concepts/hooks.md +53 -12
  22. package/docs/concepts/host-matrix.md +5 -3
  23. package/docs/concepts/hosts.md +1 -1
  24. package/docs/concepts/kits.md +18 -0
  25. package/docs/concepts/loop-gates.md +3 -0
  26. package/docs/concepts/loops.md +1 -0
  27. package/docs/concepts/rules.md +1 -1
  28. package/docs/concepts/shared-tier.md +1 -1
  29. package/docs/concepts/skills.md +1 -1
  30. package/docs/extending.md +8 -2
  31. package/docs/guides/autostart.md +29 -3
  32. package/docs/guides/choose-your-setup.md +1 -1
  33. package/docs/guides/migrate.md +1 -1
  34. package/docs/guides/run-a-factory.md +88 -0
  35. package/docs/guides/set-up-ownership.md +1 -0
  36. package/docs/guides/uninstall.md +1 -1
  37. package/docs/reference/factory-actions.md +22 -0
  38. package/docs/reference/loop-actions.md +1 -1
  39. package/docs/reference/plugin-activity.md +1 -1
  40. package/docs/reference/plugin-context.md +1 -1
  41. package/docs/reference/plugin-guard.md +24 -5
  42. package/docs/reference/troubleshoot-doctor.md +2 -2
  43. package/docs/understand/a-day.md +9 -5
  44. package/docs/web-ui.md +101 -17
  45. package/harness.config.json +1 -1
  46. package/js/README.md +21 -3
  47. package/js/build/args.mjs +14 -2
  48. package/js/build/emit-claude.mjs +9 -1
  49. package/js/build/emit-opencode.mjs +2 -1
  50. package/js/build/source.mjs +28 -3
  51. package/js/cli-table.json +287 -3
  52. package/js/factory/cli.mjs +153 -0
  53. package/js/factory/graph.mjs +245 -0
  54. package/js/factory/registry.mjs +71 -0
  55. package/js/factory/state.mjs +429 -0
  56. package/js/hosts/activity.mjs +3 -3
  57. package/js/hosts/geneseed-dir.mjs +2 -2
  58. package/js/hosts/gitref.mjs +21 -0
  59. package/js/hosts/hooks-context.mjs +71 -15
  60. package/js/hosts/hooks-done.mjs +3 -1
  61. package/js/hosts/hooks-learn.mjs +1 -1
  62. package/js/hosts/hooks-prims.mjs +271 -1
  63. package/js/hosts/hooks.mjs +409 -151
  64. package/js/hosts/hosts.mjs +22 -0
  65. package/js/hosts/installs.mjs +9 -5
  66. package/js/hosts/settings.mjs +128 -27
  67. package/js/hosts/shim.mjs +155 -7
  68. package/js/hosts/store-watch.mjs +36 -11
  69. package/js/inspect/checks-authoring.mjs +11 -1
  70. package/js/inspect/cost.mjs +91 -5
  71. package/js/inspect/diff.mjs +2 -1
  72. package/js/inspect/doctor.mjs +2 -1
  73. package/js/inspect/inventory.mjs +2 -1
  74. package/js/inspect/validate.mjs +1 -1
  75. package/js/loop/catalog.mjs +24 -12
  76. package/js/loop/cli.mjs +21 -15
  77. package/js/loop/graph.mjs +13 -4
  78. package/js/loop/registry.mjs +65 -28
  79. package/js/loop/state.mjs +18 -8
  80. package/js/maintain/migrate.mjs +2 -2
  81. package/js/maintain/uninstall.mjs +5 -1
  82. package/js/web/actions.mjs +17 -1
  83. package/js/web/api.mjs +52 -11
  84. package/js/web/catalog.mjs +38 -2
  85. package/js/web/daemon.mjs +136 -6
  86. package/js/web/handler.mjs +14 -5
  87. package/js/web/routes.mjs +12 -4
  88. package/js/web/server.mjs +4 -1
  89. package/package.json +1 -1
  90. package/registry.json +35 -0
  91. package/src/AGENT.md.tmpl +18 -24
  92. package/src/agents/_self-improvement.md +7 -6
  93. package/src/agents/developer.md +3 -2
  94. package/src/agents/docker-expert.md +1 -0
  95. package/src/agents/memory-curator.md +3 -2
  96. package/src/bricks/docs-update.md +5 -0
  97. package/src/bricks/holdout-write.md +23 -0
  98. package/src/bricks/holdout.md +25 -0
  99. package/src/bricks/intake.md +18 -0
  100. package/src/bricks/merge-gate.md +22 -0
  101. package/src/bricks/pr-open.md +21 -0
  102. package/src/bricks/retro.md +17 -0
  103. package/src/bricks/test.md +4 -1
  104. package/src/bricks/triage.md +19 -0
  105. package/src/doctrines/comms.md +29 -41
  106. package/src/doctrines/craft.md +3 -10
  107. package/src/doctrines/ops.md +4 -15
  108. package/src/doctrines/process.md +24 -19
  109. package/src/doctrines/rigor.md +1 -5
  110. package/src/factories/analysis-to-build.json +34 -0
  111. package/src/factories/bug-report-to-fix.json +32 -0
  112. package/src/factories/issue-to-pr.json +49 -0
  113. package/src/kits/ci-pipelines/rules.md +10 -0
  114. package/src/kits/ci-pipelines.json +14 -0
  115. package/src/kits/docker/rules.md +11 -0
  116. package/src/kits/docker.json +12 -0
  117. package/src/memory/README.md +5 -4
  118. package/src/modes/foreman.md +23 -10
  119. package/src/notebook/README.md +1 -1
  120. package/src/skills/_checkpoints.md +1 -0
  121. package/src/skills/_self-improvement.md +12 -9
  122. package/src/skills/adhd.md +1 -1
  123. package/src/skills/compose-ops.md +58 -0
  124. package/src/skills/factory-forge.md +97 -0
  125. package/src/skills/factory.md +126 -0
  126. package/src/skills/gitlab-ci.md +51 -0
  127. package/src/skills/jenkins-pipeline.md +56 -0
  128. package/src/skills/parallel-agents.md +1 -1
  129. package/src/skills/pipeline.md +2 -2
  130. package/src/skills/rule.md +24 -18
  131. package/src/skills/skill-forge.md +24 -6
  132. package/src/skills/workflow.md +2 -1
  133. package/themes/_TEMPLATE.json +9 -4
  134. package/themes/biker.json +9 -4
  135. package/themes/commentator.json +9 -4
  136. package/themes/cyberpunk.json +9 -4
  137. package/themes/gamer.json +9 -4
  138. package/themes/imperial.json +9 -4
  139. package/themes/joker.json +9 -4
  140. package/themes/marvin.json +9 -4
  141. package/themes/mean.json +9 -4
  142. package/themes/military.json +9 -4
  143. package/themes/neutral.json +9 -4
  144. package/themes/pirate.json +9 -4
  145. package/themes/sports.json +9 -4
  146. package/themes/verstappen.json +9 -4
  147. package/themes/wizard.json +9 -4
  148. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +1 -0
  149. package/web/dist/assets/Activity-BaoxwVFH.js +1 -0
  150. package/web/dist/assets/ActivityDetail-C_bFD0rW.js +1 -0
  151. package/web/dist/assets/{Bonsai-C1iBAt4v.js → Bonsai-B01lLf0m.js} +1 -1
  152. package/web/dist/assets/{CopyButton-DJ3a4N88.js → CopyButton-Bc66KPyA.js} +1 -1
  153. package/web/dist/assets/Dashboard-X7GZzGJp.js +2 -0
  154. package/web/dist/assets/{Docs-Kffdg5uV.js → Docs-LRYVnGLG.js} +3 -3
  155. package/web/dist/assets/Factories-ARenKBiP.js +1 -0
  156. package/web/dist/assets/{GreenhouseView-k56_cBSF.js → GreenhouseView-CfWR2-sX.js} +1 -1
  157. package/web/dist/assets/{Installs-DtEKLC9h.js → Installs-nfFHnovH.js} +3 -3
  158. package/web/dist/assets/{JournalView-RQnk5l7I.js → JournalView-lpOHcHKK.js} +1 -1
  159. package/web/dist/assets/Kits-Bw5EQl_i.js +1 -0
  160. package/web/dist/assets/Laws-CnZJ0wjZ.js +4 -0
  161. package/web/dist/assets/LibRows-Hqvf1beK.js +1 -0
  162. package/web/dist/assets/Library-JaSsp6Yr.js +3 -0
  163. package/web/dist/assets/Loops-ZaHC5MVl.js +2 -0
  164. package/web/dist/assets/{OperatorHudView-CM5jNPwL.js → OperatorHudView-CggG0_sK.js} +1 -1
  165. package/web/dist/assets/Personal-BObvlb70.js +2 -0
  166. package/web/dist/assets/Settings-BFfPMPc9.js +1 -0
  167. package/web/dist/assets/Tabs-B594Pad_.js +1 -0
  168. package/web/dist/assets/api-DLDVY3K-.js +1 -0
  169. package/web/dist/assets/index-DsLmKHw0.js +6 -0
  170. package/web/dist/assets/index-DvPjphz0.css +1 -0
  171. package/web/dist/index.html +3 -3
  172. package/web/dist/assets/Activity-Ci4PZco3.js +0 -1
  173. package/web/dist/assets/ActivityDetail-C8hroCND.js +0 -1
  174. package/web/dist/assets/Dashboard-C_On4KXw.js +0 -2
  175. package/web/dist/assets/Kits-CXkEBpnf.js +0 -1
  176. package/web/dist/assets/Laws-DhhIVqmh.js +0 -3
  177. package/web/dist/assets/Library-CAUiEoJo.js +0 -3
  178. package/web/dist/assets/Loops-LKD8mF4E.js +0 -2
  179. package/web/dist/assets/Personal-B6Uoly3C.js +0 -2
  180. package/web/dist/assets/RailCats-DQxxYBEP.js +0 -1
  181. package/web/dist/assets/Settings-BTe6-wda.js +0 -1
  182. package/web/dist/assets/Tabs-CbdDWTp_.js +0 -1
  183. package/web/dist/assets/api-D_r0Jtla.js +0 -1
  184. package/web/dist/assets/index-HfGmYXab.js +0 -3
  185. package/web/dist/assets/index-ao3M-Fhm.css +0 -1
@@ -517,6 +517,28 @@ export const CARRIERS = [
517
517
  path.join('rules', 'geneseed.md'), 'AGENTS.md',
518
518
  ];
519
519
 
520
+ // `managedBlockWrite`'s delimiters (./settings.mjs, which this module may not import). First block
521
+ // only, as that writer reads it.
522
+ const CARRIER_BLOCK_RE = /<!-- BEGIN GENESEED -->[\s\S]*?<!-- END GENESEED -->/;
523
+ const SHARED_CARRIER_RE = /(?:^|[\\/])(?:CLAUDE|AGENTS)\.md$/i;
524
+ /** The managed block as a reader sees it, `''` with none. */
525
+ export const carrierBlock = (text) => CARRIER_BLOCK_RE.exec(text)?.[0] ?? '';
526
+ /** The file a Windows write lands on: `CLAUDE.md::$DATA` and `CLAUDE.md.` both write `CLAUDE.md`. */
527
+ export function carrierName(file) {
528
+ const s = String(file);
529
+ const at = Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\')) + 1;
530
+ return s.slice(0, at) + s.slice(at).split(':')[0].replace(/[. ]+$/, '');
531
+ }
532
+ /** `file` is a carrier the user shares with Geneseed: only its managed block is Geneseed's. */
533
+ export const isSharedCarrier = (file) => SHARED_CARRIER_RE.test(file);
534
+
535
+ /**
536
+ * The part of a carrier a gate switch may be read from. `CLAUDE.md` and `AGENTS.md` are the user's
537
+ * files and no gate-config name, so a line there outside the block is prose and can disarm nothing:
538
+ * with no block, nothing counts. A generated `AGENT.md` or `rules/geneseed.md` stays whole.
539
+ */
540
+ export const gateCarrierText = (file, text) => (isSharedCarrier(file) ? carrierBlock(text) : text);
541
+
520
542
  /**
521
543
  * `host`'s own carrier path(s), narrowed off the single `HOSTS` table — `carrierInLayer` and
522
544
  * `projectMarker`/`agentFile` — rather than a second hand-rolled host→carrier map.
@@ -38,7 +38,7 @@ import {
38
38
  CONFIG, GATE_SWITCHES, PACK_ORDER, RETIRED_KIT_IDS, THEMES, discoverNames, loadKits, resolveSkillNames,
39
39
  } from '../build/source.mjs';
40
40
  import {
41
- CARRIERS, CLAUDE_STYLE, DISABLED_STASH, GLOBAL_MANIFEST, HOSTS, SHARED_TIER_RE, carriersFor, isHostGlobalDir,
41
+ CARRIERS, CLAUDE_STYLE, DISABLED_STASH, GLOBAL_MANIFEST, HOSTS, SHARED_TIER_RE, carriersFor, gateCarrierText, isHostGlobalDir,
42
42
  liveRecordedHooks, resolvePath,
43
43
  } from './hosts.mjs';
44
44
  import { registryRoots } from '../inspect/registry.mjs';
@@ -345,7 +345,9 @@ export function doctrinesOfDir(d, host = null) {
345
345
  return firstCarrier(d, (carrierPath) => {
346
346
  const text = readMaybe(carrierPath);
347
347
  if (text === null) return undefined;
348
- const m = ACTIVE_PACKS_RE.exec(text);
348
+ // Only the managed block of a shared CLAUDE.md/AGENTS.md, as `gateOfDir` reads: a line the agent
349
+ // appended outside it would otherwise drop packs, and their hooks, at the next rebuild.
350
+ const m = ACTIVE_PACKS_RE.exec(gateCarrierText(carrierPath, text));
349
351
  if (!m) return undefined;
350
352
  if (m[1] === 'none') return [];
351
353
  const named = m[1].split(',').map((s) => s.trim());
@@ -401,7 +403,8 @@ export function excludedRulesOfDir(d, host = null) {
401
403
  return firstCarrier(d, (carrierPath) => {
402
404
  const text = readMaybe(carrierPath);
403
405
  if (text === null) return undefined;
404
- const m = EXCLUDED_RULES_RE.exec(text);
406
+ // The managed block only, as above: an exclusion drops a rule's hook too.
407
+ const m = EXCLUDED_RULES_RE.exec(gateCarrierText(carrierPath, text));
405
408
  if (!m) return undefined;
406
409
  if (m[1] === 'none') return [];
407
410
  const named = m[1].split(',').map((s) => s.trim());
@@ -493,14 +496,15 @@ export function sharedTierOfDir(d, host = null) {
493
496
  * Read back so `upgrade`, `rebuild-all`, `diff` and the console re-render the same switch.
494
497
  * FAILS CLOSED: a missing line, a missing carrier, or any value but exactly `off` reads as
495
498
  * armed, because the line is only ever written when the gate is off and a gate is the thing a
496
- * misread must never take away.
499
+ * misread must never take away. Read through `gateCarrierText`: in a `CLAUDE.md` or `AGENTS.md`,
500
+ * only the managed block counts, or an unasked append to the user's file would disarm the next rebuild.
497
501
  */
498
502
  function gateOfDir(d, marker, host = null) {
499
503
  const re = new RegExp(`^${marker}:[ \\t]*(.+?)[ \\t]*$`, 'm');
500
504
  return firstCarrier(d, (carrierPath) => {
501
505
  const text = readMaybe(carrierPath);
502
506
  if (text === null) return undefined;
503
- const m = re.exec(text);
507
+ const m = re.exec(gateCarrierText(carrierPath, text));
504
508
  if (!m) return undefined;
505
509
  return m[1] !== 'off';
506
510
  }, true, host);
@@ -79,6 +79,24 @@ const CONSENT_RULE = 'process.5';
79
79
  const consentRuleOn = (d, excluded = []) =>
80
80
  processPackOn(d) && !(Array.isArray(excluded) && excluded.includes(CONSENT_RULE));
81
81
 
82
+ /**
83
+ * The same test for any rule whose hook goes with its text (owner decision, 2026-11-08): the rule's
84
+ * pack is on (unknown counts as on, like `processPackOn`) and the rule is not excluded. So excluding
85
+ * the rule, or its whole pack, drops its hook, as it drops process 5's. Process 1 (Persist Insight)
86
+ * is the rule-store ask; ops 2 (Commands Must Return) the root-scan check. Each flag is emitted only
87
+ * when its rule is off, so a build that keeps both is byte-identical to one from before.
88
+ */
89
+ const STORE_RULE = 'process.1';
90
+ const ROOT_SCAN_RULE = 'ops.2';
91
+ const ruleOn = (id, d, excluded = []) => (!Array.isArray(d) || d.includes(id.split('.')[0]))
92
+ && !(Array.isArray(excluded) && excluded.includes(id));
93
+ /** The derived hook flags of `ruleOn`, in emit order. `verb` keeps each flag to the verbs that read it. */
94
+ function ruleFlags(verb, d, excluded) {
95
+ const store = ['git-gate', 'rule-gate', 'tool-gate', 'learn'].includes(verb) && !ruleOn(STORE_RULE, d, excluded);
96
+ const scan = ['git-gate', 'tool-gate'].includes(verb) && !ruleOn(ROOT_SCAN_RULE, d, excluded);
97
+ return `${store ? ' --no-rule-store' : ''}${scan ? ' --no-root-scan' : ''}`;
98
+ }
99
+
82
100
  /**
83
101
  * `_build_settings._default_permission`.
84
102
  *
@@ -401,17 +419,20 @@ function reconcileOpencodeSkillPermission(perm, names, staleNames = [], added =
401
419
  * inside the project is relative to the session dir there, `file-access.ts` `resolve`). Never the
402
420
  * absolute path: a project opencode.json is often committed, and teammates do not share it.
403
421
  */
404
- export function opencodeEditAsks(cfgDir, global, agentRel = null) {
422
+ export function opencodeEditAsks(cfgDir, global, agentRel = null, doctrines = null, excluded = []) {
405
423
  const cfg = path.basename(cfgDir);
406
424
  const tails = ['opencode.json', 'opencode.jsonc', ...['excludes.json', GLOBAL_MANIFEST, '.geneseed-emit',
407
425
  'plugins/*', 'plugin/*', 'agents/*.md', 'agent/*.md', 'mode/*.md', 'modes/*.md', 'tool/*', 'tools/*',
408
- ...(global ? ['AGENT.md', 'config.json'] : [])].map((f) => `${cfg}/${f}`),
426
+ // `<cfg>/AGENT.md` in a project install too: the guard reads it BEFORE the project's own carrier
427
+ // (`CARRIER_DIRS`), so a file planted there would set its gate markers and rule exclusions.
428
+ 'AGENT.md', ...(global ? ['config.json'] : [])].map((f) => `${cfg}/${f}`),
409
429
  ...['.claude', '.openclaude', '.bob'].flatMap((m) => [`${m}/settings.json`, `${m}/settings.local.json`]),
410
430
  '.bob/settings/settings.json',
411
- // Persist Insight: the rule and memory stores, which the guard no longer releases on a re-issue.
412
- // The coined names match anywhere, as the guard and Claude's rule gate match them; the memory
413
- // folders by their last segments, so a project's unrelated `memory/` is never asked about.
414
- 'user-rules.md', 'user-rules.draft.md', 'MEMORY.md', `${cfg}/memory/*.md`, 'geneseed/memory/*.md'];
431
+ // Persist Insight: the rule stores, which the guard no longer releases on a re-issue. The coined
432
+ // names match anywhere, as the guard and Claude's rule gate match them. Memory is written freely
433
+ // (owner decision, 2026-11-08), so its keys are gone; a re-emit sweeps the ones an install recorded.
434
+ // With process 1 excluded (or its pack off) the rule files lose their ask too, and a re-emit sweeps it.
435
+ ...(ruleOn(STORE_RULE, doctrines, excluded) ? ['user-rules.md', 'user-rules.draft.md'] : [])];
415
436
  const keys = [];
416
437
  if (agentRel) {
417
438
  const abs = path.resolve(path.dirname(cfgDir), agentRel);
@@ -419,10 +440,6 @@ export function opencodeEditAsks(cfgDir, global, agentRel = null) {
419
440
  const gitRel = git ? path.relative(git, abs).split(path.sep).join('/') : agentRel;
420
441
  keys.push(...new Set([agentRel, gitRel, `*../${agentRel}`,
421
442
  ...(agentRel.includes('/') ? [`*/${agentRel}`] : [])]));
422
- // The store sits beside the carrier (`<out>/memory`, js/build/bundle.mjs), the same four shapes.
423
- const beside = (rel) => path.posix.join(path.posix.dirname(rel), 'memory/*.md');
424
- keys.push(...new Set([beside(agentRel), beside(gitRel), `*../${beside(agentRel)}`,
425
- ...(agentRel.includes('/') ? [`*/${beside(agentRel)}`] : [])]));
426
443
  }
427
444
  try {
428
445
  const home = shimHome();
@@ -533,7 +550,7 @@ export function loadJsonObject(p, { strict = false } = {}) {
533
550
  */
534
551
  function warnCommentedJsonc(target, agentPath, permission,
535
552
  includeLsp = false, prefix = 'geneseed', doctrines = null, excluded = [], skillNames = [],
536
- deletionGate = true, editAsks = []) {
553
+ deletionGate = true, editAsks = [], includeDepth = false) {
537
554
  process.stdout.write(`[${prefix}] ${path.basename(target)} has comments — not rewriting `
538
555
  + 'it (your edits are kept). Add this to its "instructions" array by hand:\n');
539
556
  process.stdout.write(`[${prefix}] ${jsonDumps(agentPath)}\n`);
@@ -564,6 +581,10 @@ function warnCommentedJsonc(target, agentPath, permission,
564
581
  process.stdout.write(`[${prefix}] and, to enable code intelligence, a top-level `
565
582
  + '"lsp": true\n');
566
583
  }
584
+ if (includeDepth) {
585
+ process.stdout.write(`[${prefix}] and, to cap subagent nesting at two levels, a top-level `
586
+ + '"subagent_depth": 2\n');
587
+ }
567
588
  }
568
589
 
569
590
  /**
@@ -702,7 +723,11 @@ export function mergeOpencodeJson(p, agentPath, doctrines = null, excluded = [],
702
723
  }
703
724
  const addLsp = !has(config, 'lsp');
704
725
  if (addLsp) config.lsp = true;
705
- if (!addInstr && !permChanged && !addLsp) {
726
+ // Foreman's depth, main → worker → sub-worker, as OpenCode's own cap: absent ⇒ written,
727
+ // present ⇒ the user's. Left at uninstall, as `lsp` is.
728
+ const addDepth = !has(config, 'subagent_depth');
729
+ if (addDepth) config.subagent_depth = 2;
730
+ if (!addInstr && !permChanged && !addLsp && !addDepth) {
706
731
  result.skillsAdded = added;
707
732
  result.editRecord = edit;
708
733
  return target;
@@ -720,7 +745,7 @@ export function mergeOpencodeJson(p, agentPath, doctrines = null, excluded = [],
720
745
  // block to paste, split by which of the two situations the reader is actually in. It is
721
746
  // stdout, not stderr, because on this path the paste-in IS the output.
722
747
  warnCommentedJsonc(target, agentPath, addPerm ? 'add' : (permChanged && 'reconcile'),
723
- addLsp, 'geneseed', doctrines, excluded, skillNames, deletionGate, editAsks);
748
+ addLsp, 'geneseed', doctrines, excluded, skillNames, deletionGate, editAsks, addDepth);
724
749
  return target;
725
750
  }
726
751
  try {
@@ -770,14 +795,18 @@ export function mergeOpencodeJson(p, agentPath, doctrines = null, excluded = [],
770
795
  * prose layer for no gain in safety. Asymmetric risk, asymmetric answer — the BOUNDARY follows
771
796
  * the pack, the ASKING does not have to.
772
797
  *
773
- * The `rule-gate` group stays in every build. Its subject is which durable store a write
774
- * belongs in — the user's call — not how work is run, so it is not the process pack's to
775
- * remove. `default` here means unknown, and unknown keeps the gate (see `processPackOn`).
798
+ * The `rule-gate` group stays in every build: it carries Law I, External Gate and the ownership
799
+ * gate, none of them the process pack's. Its process-1 branch (the rule-store ask) follows that
800
+ * rule like process 5 follows its own (owner decision, 2026-11-08): `--no-rule-store` when process 1
801
+ * or its pack is off, on `rule-gate`, `git-gate` (the shell path) and `learn` (the change report);
802
+ * ops 2's root-scan check gets `--no-root-scan` on `git-gate` the same way (`ruleFlags`).
803
+ * `default` here means unknown, and unknown keeps the gate (see `processPackOn`).
776
804
  */
777
805
  export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [], host = 'claude',
778
806
  gates = {}) {
779
807
  // One object keyed as `GATE_SWITCHES` keys it; only an explicit `false` disarms a gate.
780
- const { secretsGate = true, doneGate = true, deletionGate = true, ownershipGate = true } = gates ?? {};
808
+ const { secretsGate = true, doneGate = true, deletionGate = true, ownershipGate = true,
809
+ externalGate = true, testNote = true } = gates ?? {};
781
810
  const run = hookPrefix(hookOpts);
782
811
  const mem = `--memory "${path.join(cfg, 'memory')}"`;
783
812
  // --root carries the install's own dir so a GLOBAL hook can stand down when a live, wired
@@ -818,6 +847,9 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
818
847
  const dn = doneGate === false ? ' --no-done-gate' : '';
819
848
  // The ownership first-write gate (js/hosts/ownership-gate.mjs), the same contract.
820
849
  const og = ownershipGate === false ? ' --no-ownership-gate' : '';
850
+ // External Gate's hook and the weakened-test note, the same contract.
851
+ const eg = externalGate === false ? ' --no-external-gate' : '';
852
+ const tn = testNote === false ? ' --no-test-note' : '';
821
853
  return {
822
854
  SessionStart: [{ hooks: [{ type: 'command', command: `${run} context --root "${cfg}"${b} || exit 0` }] }],
823
855
  // One group, both gates: process 5's consent is a stderr line here (Bob has no ask
@@ -826,13 +858,13 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
826
858
  // `--no-deletion-gate`), and for a
827
859
  // write under a project's own `.geneseed/protected-checks.txt` — the project opted in —
828
860
  // and for a recursive scan rooted at a whole filesystem (ops 2, the root-scan check).
829
- PreToolUse: [{ hooks: [{ type: 'command', command: `${run} tool-gate --root "${cfg}"${b}${sg}${dg}${og}` }] }],
861
+ PreToolUse: [{ hooks: [{ type: 'command', command: `${run} tool-gate --root "${cfg}"${b}${sg}${dg}${og}${eg}${tn}${ruleFlags('tool-gate', doctrines, excluded)}` }] }],
830
862
  // Bob's Stop payload never carries `transcript_path` (I2) — `learn` reads `--host bob`
831
863
  // and returns immediately rather than wasting a model call on the bare envelope. KEPT
832
864
  // rather than DROPPED: the stand-down costs nothing (no transcript read, no spawn), and
833
865
  // if Bob ever starts sending one, learning on Bob starts working with no emit change —
834
866
  // dropping the group would need a second one re-added later for the same reason.
835
- Stop: [{ hooks: [{ type: 'command', command: `${run} learn ${mem}${b}${dn} || exit 0` }] }],
867
+ Stop: [{ hooks: [{ type: 'command', command: `${run} learn ${mem}${b}${dn}${tn} || exit 0` }] }],
836
868
  // The activity view's turn start (js/hosts/activity.mjs). Bob has no SessionEnd, so a Bob
837
869
  // session leaves the live list by staleness alone.
838
870
  UserPromptSubmit: [{ hooks: [{ type: 'command', command: `${run} activity --root "${cfg}"${b} || exit 0` }] }],
@@ -847,15 +879,22 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
847
879
  const h = host === 'openclaude' ? ' --host openclaude' : '';
848
880
  const context = `${run} context --root "${cfg}"${h} || exit 0`;
849
881
  const gate = `${run} git-gate --root "${cfg}"${h}${consentRuleOn(doctrines, excluded) ? '' : ' --no-consent'}`
850
- + (deletionGate === false ? ' --no-deletion-gate' : '');
882
+ + (deletionGate === false ? ' --no-deletion-gate' : '')
883
+ + (externalGate === false ? ' --no-external-gate' : '') + ruleFlags('git-gate', doctrines, excluded);
851
884
  // `--no-secrets-gate` skips only rule-gate's credential scan (rigor 5 and process 1 still
852
885
  // run); `--no-done-gate` only learn's done check, never the distillation. One `learn` string
853
886
  // feeds Stop, SubagentStop and PreCompact, and the flag sits before `|| exit 0`.
854
887
  // `--no-ownership-gate` (the ownership first-write gate) rides rule-gate only, never the
855
- // `Skill|Agent|Task` tool-gate below, which judges no write.
888
+ // `Skill|Agent|Task` tool-gate below, which judges no write. `--no-external-gate` rides git-gate
889
+ // and rule-gate, its two paths; `--no-test-note` rule-gate (edit time) and learn (turn end).
856
890
  const ruleGate = `${run} rule-gate --root "${cfg}"${secretsGate === false ? ' --no-secrets-gate' : ''}`
857
- + (ownershipGate === false ? ' --no-ownership-gate' : '');
858
- const learn = `${run} learn ${mem}${h}${doneGate === false ? ' --no-done-gate' : ''} || exit 0`;
891
+ + (ownershipGate === false ? ' --no-ownership-gate' : '')
892
+ + (externalGate === false ? ' --no-external-gate' : '')
893
+ + (testNote === false ? ' --no-test-note' : '') + ruleFlags('rule-gate', doctrines, excluded);
894
+ // `--no-rule-store` on learn: with process 1 off a rule write runs with no prompt, so the change
895
+ // report must not count it as approved (`storeReport`). Bob's learn reports every change already.
896
+ const learn = `${run} learn ${mem}${h}${doneGate === false ? ' --no-done-gate' : ''}`
897
+ + `${testNote === false ? ' --no-test-note' : ''}${ruleFlags('learn', doctrines, excluded)} || exit 0`;
859
898
  const activity = `${run} activity --root "${cfg}"${h} || exit 0`;
860
899
  // Claude Code only (hooks.md, v2.1.295+; Task 1): a `command` hook that can't start, times
861
900
  // out, or exits anything but 0 or 2 — even one whose stdout happens to be valid JSON — now
@@ -913,10 +952,11 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
913
952
  // user's prompt, and the `activity` verb decides nothing.
914
953
  UserPromptSubmit: [{ hooks: [{ type: 'command', command: activity }] }],
915
954
  SessionEnd: [{ hooks: [{ type: 'command', command: activity }] }],
916
- // A sub-agent's branch at launch (the Activity garden): a read-only sub-agent fires no gated
917
- // hook, so without this it would never appear. Never on Bob (the early return above): Bob's
918
- // hook schema is strict, and one unknown event key drops its whole hooks block.
919
- SubagentStart: [{ hooks: [{ type: 'command', command: activity }] }],
955
+ // A sub-agent's start: `context` reads the event name and injects the user's rules, which no
956
+ // sub-agent gets from SessionStart (spec 2026-11-08, agent loadout). The Activity garden's
957
+ // branch at launch still records, since `trackActivity` runs after every verb. Never on Bob
958
+ // (the early return above): its schema is strict, one unknown event key drops the whole block.
959
+ SubagentStart: [{ hooks: [{ type: 'command', command: context }] }],
920
960
  };
921
961
  // Claude Code only: OpenClaude always runs Git Bash on Windows (its `findGitBashPath` exits
922
962
  // without one), and Bob takes the early return above.
@@ -1125,6 +1165,67 @@ export function wireClaudeExcludes(p, excludes) {
1125
1165
  return added;
1126
1166
  }
1127
1167
 
1168
+ /**
1169
+ * The `env` keys a Claude Code install arms. Foreman mode allows main → worker → sub-worker and
1170
+ * no deeper; Claude Code's own default is three layers, so the cap is written, not assumed.
1171
+ * Claude only: OpenClaude has no such cap in its source (checked on 0.31) and Bob documents none.
1172
+ */
1173
+ export const CLAUDE_ENV = Object.freeze({ CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH: '2' });
1174
+
1175
+ /**
1176
+ * Add-if-absent into `env`, the `wireClaudeExcludes` shape: a key the user already set, to any
1177
+ * value, is theirs and stays. Returns the `{key: value}` pairs actually written, which the
1178
+ * manifest records so uninstall removes only those.
1179
+ */
1180
+ export function wireClaudeEnv(p, want = CLAUDE_ENV) {
1181
+ const loaded = readSettingsForMerge(p, 'Its "env" keys were not wired.');
1182
+ if (!loaded) return {};
1183
+ const [config, hadComments] = loaded;
1184
+ // An `env` that is there but is not an object is the user's, however wrong: never replaced.
1185
+ if (has(config, 'env') && !isDict(config.env)) {
1186
+ process.stderr.write(`[geneseed] WARN: "env" in ${path.basename(p)} is not an object — `
1187
+ + `NOT rewriting it. Add to it by hand once it is one: ${jsonDumpsCompact(want)}\n`);
1188
+ return {};
1189
+ }
1190
+ const env = has(config, 'env') ? config.env : {};
1191
+ const added = Object.fromEntries(Object.entries(want || {}).filter(([k]) => !has(env, k)));
1192
+ if (!Object.keys(added).length) return {};
1193
+ if (hadComments) {
1194
+ process.stderr.write(`[geneseed] ${path.basename(p)} has comments — not rewriting it `
1195
+ + '(your edits are kept). Add to its "env" object by hand: '
1196
+ + `${jsonDumpsCompact(added)}\n`);
1197
+ return {};
1198
+ }
1199
+ config.env = { ...env, ...added };
1200
+ try {
1201
+ atomicWriteJson(p, config);
1202
+ } catch (e) {
1203
+ if (!isOsError(e)) throw e;
1204
+ process.stderr.write(`[geneseed] WARN: could not write ${p} (${e.message}) — `
1205
+ + `its "env" keys were not wired. Add to its "env" object by hand: ${jsonDumpsCompact(added)}\n`);
1206
+ return {};
1207
+ }
1208
+ return added;
1209
+ }
1210
+
1211
+ /** Remove each recorded `env` key while it still holds the recorded value; drop an empty `env`. */
1212
+ export function unwireClaudeEnv(p, recorded) {
1213
+ if (!isDict(recorded) || !Object.keys(recorded).length) return;
1214
+ const { state, data: loaded, hadComments } = loadJsonObject(p);
1215
+ if (state !== 'ok' || hadComments) return;
1216
+ const env = get(loaded, 'env');
1217
+ if (!isDict(env)) return;
1218
+ const gone = Object.keys(recorded).filter((k) => has(env, k) && env[k] === recorded[k]);
1219
+ if (!gone.length) return;
1220
+ for (const k of gone) delete env[k];
1221
+ if (!Object.keys(env).length) delete loaded.env;
1222
+ try {
1223
+ atomicWriteJson(p, loaded);
1224
+ } catch (e) {
1225
+ if (!isOsError(e)) throw e;
1226
+ }
1227
+ }
1228
+
1128
1229
  /** `_build_settings._unwire_claude_excludes`. */
1129
1230
  export function unwireClaudeExcludes(p, excludes) {
1130
1231
  if (!excludes || !excludes.length) return;
package/js/hosts/shim.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The machine-wide HOOK SHIM — where it lives, what it says, whether it still resolves — and
3
- * the shim-shaped reader `migrate` needs (the autostart scan).
3
+ * the web console's login launcher (read by `migrate`, written by Settings).
4
4
  *
5
5
  * SPLIT OUT OF `js/hosts/settings.mjs` (2026-10) for its cheapest caller. Every CLI run asks
6
6
  * `shimDead()` (the dead-shim warning in `bin/geneseed-cli.mjs`), and that used to load the
@@ -14,7 +14,8 @@
14
14
  * being cheap to load is its whole reason to exist.
15
15
  */
16
16
  import {
17
- chmodSync, existsSync, mkdirSync, realpathSync, renameSync, statSync, writeFileSync,
17
+ chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync,
18
+ unlinkSync, writeFileSync,
18
19
  } from 'node:fs';
19
20
  import path from 'node:path';
20
21
  import os from 'node:os';
@@ -362,12 +363,12 @@ export function hookRunnerEntry() {
362
363
  }
363
364
 
364
365
  /**
365
- * `_build_settings._autostart_paths` — where a hand-written web-daemon autostart entry lives.
366
+ * `_build_settings._autostart_paths` — where the web-daemon login launcher lives.
366
367
  *
367
- * NOTHING IN THIS REPOSITORY HAS EVER WRITTEN ONE — the install guide tells the user to create them
368
- * by hand, and no .py/.mjs/.sh/.cmd in the tree contains `vbs`, `LaunchAgents` or `plist`. So
369
- * `migrate` REPORTS a stale one and never rewrites it, on the rule `settingsIntegrityCheck`
370
- * already states: an entry the manifest does not claim is "possibly user-authored; left alone".
368
+ * Two writers, told apart by `AUTOSTART_MARKER`: the Settings page writes one (decided
369
+ * 2026-11-08, `autostartInstall` below), and the install guide still shows how to write one by
370
+ * hand. `migrate` only REPORTS a stale one and never rewrites it, on the rule
371
+ * `settingsIntegrityCheck` already states: a file the tool may not own is left alone.
371
372
  *
372
373
  * Both platforms' paths on both platforms, deliberately — the scan is a read that misses
373
374
  * harmlessly, and returning only the host platform's would make the macOS arm unreachable
@@ -396,3 +397,150 @@ export function autostartStale(text, root) {
396
397
  if (!text.toLowerCase().includes('geneseed')) return false;
397
398
  return !text.includes(root) && !text.includes(root.replaceAll('\\', '/'));
398
399
  }
400
+
401
+ /**
402
+ * The line that names Geneseed as the writer of a login launcher. Only a file that carries it is
403
+ * rewritten or deleted. The guide's hand-written templates leave it out on purpose, so a copied
404
+ * template stays the user's.
405
+ */
406
+ export const AUTOSTART_MARKER = 'GENESEED_AUTOSTART';
407
+ const MARKER_NOTE = 'written by Geneseed (Settings, Start at login), which may update or remove it.';
408
+
409
+ /**
410
+ * The marker line and the line it must sit on: line 2 of the VBS, line 3 of the plist (after
411
+ * the XML declaration and the DOCTYPE). The marker anywhere else does not make a file ours.
412
+ */
413
+ const MARKER_LINE = { win32: `' ${AUTOSTART_MARKER}: ${MARKER_NOTE}`, darwin: `<!-- ${AUTOSTART_MARKER}: ${MARKER_NOTE} -->` };
414
+ const MARKER_INDEX = { win32: 1, darwin: 2 };
415
+ const CLI_ENTRY = path.join(ROOT, 'bin', 'geneseed-cli.mjs');
416
+
417
+ /**
418
+ * Is `root` a copy that may soon disappear: an agent worktree (`.claude/worktrees/…`) or the npx
419
+ * cache (`_npx/…`)? A login item pointing there stops working when the folder goes.
420
+ */
421
+ export function transientRoot(root) {
422
+ return /[\\/]\.claude[\\/]worktrees[\\/]|[\\/]_npx[\\/]/i.test(root);
423
+ }
424
+
425
+ /** This platform's launcher path from `autostartPaths`, or null where there is none. */
426
+ export function autostartFile(platform = process.platform) {
427
+ const [vbs, plist] = autostartPaths();
428
+ return { win32: vbs, darwin: plist }[platform] ?? null;
429
+ }
430
+
431
+ /**
432
+ * The exact text `autostartInstall` writes for `platform`, or null where there is none.
433
+ *
434
+ * It runs what the daemon launcher runs (`spawnDetached`, `js/web/daemon.mjs`): the running Node
435
+ * by absolute path and this checkout's `bin/geneseed-cli.mjs`, then `web start --no-browser`. A
436
+ * login item does not see the shell's PATH, so the `geneseed` front doors, which call a bare
437
+ * `node`, could fail there. The VBS calls Node directly, with no `cmd /c`, so a `&` in a path
438
+ * stays literal. `WshShell.Run` still expands `%VAR%`, so `autostartInstall` refuses a path with
439
+ * a `%`. No date or other varying part: the same install writes the same bytes, which is what
440
+ * makes "differs from this text" the stale test.
441
+ */
442
+ export function autostartText(platform = process.platform, exe = process.execPath, entry = CLI_ENTRY) {
443
+ if (platform === 'win32') {
444
+ const q = (s) => s.replaceAll('"', '""');
445
+ return ["' geneseed-web.vbs: start the Geneseed web console at login (hidden, no browser).",
446
+ MARKER_LINE.win32,
447
+ `CreateObject("WScript.Shell").Run """${q(exe)}"" ""${q(entry)}"" web start --no-browser", 0, False`,
448
+ ''].join('\r\n');
449
+ }
450
+ if (platform === 'darwin') {
451
+ const x = (s) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
452
+ return ['<?xml version="1.0" encoding="UTF-8"?>',
453
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
454
+ MARKER_LINE.darwin,
455
+ '<plist version="1.0">', '<dict>',
456
+ ' <key>Label</key>', ' <string>dev.geneseed.web</string>',
457
+ ' <key>ProgramArguments</key>', ' <array>',
458
+ ...[exe, entry, 'web', 'start', '--no-browser'].map((a) => ` <string>${x(a)}</string>`),
459
+ ' </array>', ' <key>RunAtLoad</key>', ' <true/>', '</dict>', '</plist>', ''].join('\n');
460
+ }
461
+ return null;
462
+ }
463
+
464
+ /**
465
+ * The launcher's state for the Settings row, or null where this platform has none.
466
+ *
467
+ * `absent`; `ours` (the marker line in its place, and exactly what an install would write now);
468
+ * `stale` (the marker line in its place, and different: another checkout, which `autostartStale`
469
+ * names, or another Node, which it does not); `hand` (anything else, the marker elsewhere and a
470
+ * symlink included: never written through, never deleted). `root` is the checkout the launcher
471
+ * runs, and `transient` says it may soon disappear (`transientRoot`), so the confirm can say both.
472
+ */
473
+ export function autostartState(platform = process.platform) {
474
+ const file = autostartFile(platform);
475
+ if (!file) return null;
476
+ const at = (state) => ({ file, state, root: ROOT, transient: transientRoot(ROOT) });
477
+ let st;
478
+ try { st = lstatSync(file); } catch { return at('absent'); }
479
+ let text = '';
480
+ try { text = st.isFile() ? readFileSync(file, 'utf8') : ''; } catch { /* unreadable: not ours */ }
481
+ if (text.split(/\r?\n/)[MARKER_INDEX[platform]] !== MARKER_LINE[platform]) return at('hand');
482
+ return at(text === autostartText(platform) ? 'ours' : 'stale');
483
+ }
484
+
485
+ const osText = (e) => (e && e.code ? `${e.code}: ${e.message}` : String(e));
486
+ const notOurs = (cur) => ({ ok: false, autostart: cur,
487
+ error: `${cur.file} was not written by Geneseed, so it is left alone` });
488
+ const NO_LAUNCHER = { ok: false, error: 'this platform has no login launcher Geneseed can write' };
489
+
490
+ /**
491
+ * Why `exe` or `entry` cannot go into the launcher, or null. Checked on the two paths, not on the
492
+ * whole text. A control character (CR, LF and the rest) would end a line or a string early. On
493
+ * Windows, a `%` would be expanded by `WshShell.Run`, and a character outside ASCII would be
494
+ * misread: WSH reads a `.vbs` with no BOM in the ANSI code page.
495
+ */
496
+ export function autostartPathProblem(platform, exe, entry) {
497
+ for (const p of [exe, entry]) {
498
+ if (/[\x00-\x1f\x7f]/.test(p)) return `the path ${JSON.stringify(p)} has a control character`;
499
+ if (platform !== 'win32') continue;
500
+ if (p.includes('%')) return `the path ${p} has a %, which the login script would expand`;
501
+ if (/[^ -~]/.test(p)) return `the path ${p} has non-ASCII characters, which a .vbs cannot hold`;
502
+ }
503
+ return null;
504
+ }
505
+
506
+ /**
507
+ * Write the launcher. Rewrites our own file (`ours`, `stale`), refuses a hand-written one and a
508
+ * path `autostartPathProblem` names. The text goes to a temp file in the same folder first and is
509
+ * renamed over the target, so the file is never half-written, and a symlink planted after the
510
+ * state check is replaced, not written through. `exe` and `entry` are parameters only so a test can
511
+ * reach the refusals; the route never passes them.
512
+ */
513
+ export function autostartInstall(platform = process.platform, exe = process.execPath, entry = CLI_ENTRY) {
514
+ const cur = autostartState(platform);
515
+ if (!cur) return NO_LAUNCHER;
516
+ if (cur.state === 'hand') return notOurs(cur);
517
+ const problem = autostartPathProblem(platform, exe, entry);
518
+ if (problem) {
519
+ return { ok: false, autostart: cur,
520
+ error: `${problem}: set it up by hand (see Start the web console at login)` };
521
+ }
522
+ const tmp = `${cur.file}.${process.pid}.tmp`;
523
+ try {
524
+ mkdirSync(path.dirname(cur.file), { recursive: true });
525
+ writeFileSync(tmp, autostartText(platform, exe, entry), { flag: 'wx' });
526
+ renameSync(tmp, cur.file);
527
+ } catch (e) {
528
+ try { unlinkSync(tmp); } catch { /* never created, or already renamed */ }
529
+ return { ok: false, autostart: autostartState(platform),
530
+ error: `could not write ${cur.file} (${osText(e)})` };
531
+ }
532
+ return { ok: true, autostart: autostartState(platform) };
533
+ }
534
+
535
+ /** Delete the launcher, only when its marker line is in place. A hand-written file is refused. */
536
+ export function autostartRemove(platform = process.platform) {
537
+ const cur = autostartState(platform);
538
+ if (!cur) return NO_LAUNCHER;
539
+ if (cur.state === 'absent') return { ok: false, autostart: cur, error: `no login launcher at ${cur.file}` };
540
+ if (cur.state === 'hand') return notOurs(cur);
541
+ try { unlinkSync(cur.file); } catch (e) {
542
+ return { ok: false, autostart: autostartState(platform),
543
+ error: `could not delete ${cur.file} (${osText(e)})` };
544
+ }
545
+ return { ok: true, autostart: autostartState(platform) };
546
+ }
@@ -7,10 +7,14 @@
7
7
  * `context` has answered, once per session, and `learn` compares on Stop. Both are stats, no reads.
8
8
  *
9
9
  * WHAT COUNTS AS APPROVED, per host. Claude and OpenClaude: a Write, Edit or NotebookEdit the
10
- * transcript shows ran, because a gated tool runs only past the host's prompt. The transcript is read
11
- * only when a file changed, which keeps the common Stop to the stats. Bob has no transcript and no
12
- * file-tool write passes its gate, so every change there is reported. OpenCode has this logic in
13
- * the guard plugin, with the baseline in memory and approval from `tool.execute.after`.
10
+ * transcript shows ran: a rule write runs only past the host's prompt, and a memory write is the
11
+ * agent's own to make (owner decision, 2026-11-08). The transcript is read only when a file changed,
12
+ * which keeps the common Stop to the stats. Bob has no transcript, so every change there is
13
+ * reported, a free memory write included. With process 1 excluded (`ruleStore: false`, the hook's
14
+ * `--no-rule-store`) a rule write runs with no prompt, so a rule file is never counted as approved and
15
+ * the report still shows it; memory keeps its excuse. OpenCode has this logic in the guard plugin, with the
16
+ * baseline in memory and approval from `tool.execute.after`. A memory write by shell is reported on
17
+ * every host: that, and the web console, is how the user sees what the agent chose to remember.
14
18
  *
15
19
  * GENESEED'S OWN WRITES. `learn`, a memory removal and the fold run inside `recordOwnWrites`, which
16
20
  * snapshots the store around the run and logs what moved to `memory/.own-writes.json`, as an exact
@@ -36,6 +40,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync,
36
40
  import path from 'node:path';
37
41
 
38
42
  import { machineDir } from '../lib/machine-dir.mjs';
43
+ import { gitRootOf } from './gitref.mjs';
39
44
  import { normcase } from '../lib/paths.mjs';
40
45
  import { sovereignBypass } from './hosts.mjs';
41
46
 
@@ -44,13 +49,15 @@ const OWN_LOG = '.own-writes.json';
44
49
  const OWN_LOG_CAP = 2000;
45
50
  const STALE_MS = 7 * 24 * 60 * 60 * 1000;
46
51
  const NAMES_SHOWN = 5;
52
+ // The coined rule-file names, at the end of a `normcase`d path (lower case on Windows).
53
+ const RULE_FILE_RE = /[\\/]user-rules(?:\.draft)?\.md$/i;
47
54
 
48
55
  /** The store files under one home, as `path -> "size:mtime"`. The guard's `storeScan` is its twin. */
49
56
  export function storeScan(home, found = {}) {
50
57
  const stamp = (f) => {
51
58
  try { const s = statSync(f); if (s.isFile()) found[f] = `${s.size}:${Math.trunc(s.mtimeMs)}`; } catch { /* absent */ }
52
59
  };
53
- for (const n of ['user-rules.md', 'PROFILE.md', 'geneseed-wiki.jsonc', 'wiki.jsonc', 'wiki.json']) stamp(path.join(home, n));
60
+ for (const n of ['user-rules.md', 'user-rules.draft.md', 'PROFILE.md', 'geneseed-wiki.jsonc', 'wiki.jsonc', 'wiki.json']) stamp(path.join(home, n));
54
61
  const walk = (dir) => {
55
62
  let items = [];
56
63
  try { items = readdirSync(dir, { withFileTypes: true }); } catch { return; }
@@ -64,7 +71,21 @@ export function storeScan(home, found = {}) {
64
71
  }
65
72
 
66
73
  const homesOf = (root) => [...new Set([root, machineDir()])];
67
- const scanAll = (root) => homesOf(root).reduce((found, h) => storeScan(h, found), {});
74
+ const stampOf = (f, found) => {
75
+ try { const s = statSync(f); if (s.isFile()) found[f] = `${s.size}:${Math.trunc(s.mtimeMs)}`; } catch { /* absent */ }
76
+ return found;
77
+ };
78
+ /**
79
+ * The project layer's rule files, which the context hook loads from the session's repository: its git
80
+ * root, else `cwd`. Only the two rule names: a repo's own `memory/` folder is not a store.
81
+ */
82
+ function projectRules(cwd, found) {
83
+ if (typeof cwd !== 'string' || !cwd) return found;
84
+ const top = gitRootOf(cwd) ?? path.resolve(cwd);
85
+ for (const n of ['user-rules.md', 'user-rules.draft.md']) stampOf(path.join(top, n), found);
86
+ return found;
87
+ }
88
+ const scanAll = (root, cwd = null) => projectRules(cwd, homesOf(root).reduce((found, h) => storeScan(h, found), {}));
68
89
  const stateFile = (root, sid) => path.join(root, STATE_DIR, `${String(sid).replace(/[^\w.-]/g, '_').slice(0, 120)}.json`);
69
90
  const readJson = (f) => { try { return JSON.parse(readFileSync(f, 'utf8')); } catch { return null; } };
70
91
 
@@ -78,12 +99,12 @@ function saveBaseline(root, sid, stamps) {
78
99
  * The session's baseline, written once. SessionStart fires again on resume and compact: keeping the
79
100
  * first one means those cannot launder a change made before them. Old sessions' files are dropped.
80
101
  */
81
- export function writeBaseline(root, sid) {
102
+ export function writeBaseline(root, sid, cwd = null) {
82
103
  try {
83
104
  if (typeof sid !== 'string' || !sid || sovereignBypass(root)) return;
84
105
  const f = stateFile(root, sid);
85
106
  if (existsSync(f)) return;
86
- saveBaseline(root, sid, scanAll(root));
107
+ saveBaseline(root, sid, scanAll(root, cwd));
87
108
  const dir = path.dirname(f);
88
109
  for (const n of readdirSync(dir)) {
89
110
  const old = path.join(dir, n);
@@ -171,18 +192,22 @@ export function lastStoreReport() {
171
192
  /**
172
193
  * Compare at a turn's end: the line to show, or null. Rolls the baseline, so a change is said once,
173
194
  * and a session with no baseline (installed mid-session) starts one here. `transcript` is null on Bob.
195
+ * `ruleStore: false`: process 1 is off, so no rule write passed a prompt (the header says why).
174
196
  */
175
- export function storeReport(root, sid, { transcript = null, cwd = null, host = 'claude' } = {}) {
197
+ export function storeReport(root, sid, { transcript = null, cwd = null, host = 'claude', ruleStore = true } = {}) {
176
198
  try {
177
199
  if (typeof sid !== 'string' || !sid) return null;
178
200
  const before = readJson(stateFile(root, sid));
179
- if (!before) { writeBaseline(root, sid); return null; }
180
- const now = scanAll(root);
201
+ if (!before) { writeBaseline(root, sid, cwd); return null; }
202
+ // Every file the baseline names is stamped again, so a session whose cwd moved still compares
203
+ // the project files it started with.
204
+ const now = Object.keys(before).reduce((found, p) => stampOf(p, found), scanAll(root, cwd));
181
205
  const changed = changedFiles(before, now);
182
206
  if (!changed.length) return null;
183
207
  saveBaseline(root, sid, now);
184
208
  const own = homesOf(root).reduce((log, h) => ({ ...log, ...readJson(path.join(h, 'memory', OWN_LOG)) }), {});
185
209
  const approved = typeof transcript === 'string' ? approvedInTranscript(transcript, cwd) : new Set();
210
+ if (!ruleStore) for (const f of approved) if (RULE_FILE_RE.test(f)) approved.delete(f);
186
211
  const files = changed.filter((f) => own[f] !== (now[f] ?? 'gone') && !approved.has(normcase(f)));
187
212
  if (!files.length) return null;
188
213
  noteForStatus(files, host);