geneseed 5.0.0 → 5.0.3

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 (138) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +1 -1
  3. package/SHIPPED.md +1 -1
  4. package/adapters/claude-code/README.md +6 -4
  5. package/adapters/opencode/HOW-OPENCODE-LOADS.md +3 -0
  6. package/adapters/opencode/plugins/geneseed-context.js +13 -2
  7. package/adapters/opencode/plugins/geneseed-guard.js +595 -74
  8. package/adapters/opencode/plugins/geneseed-learn.js +1 -1
  9. package/bin/geneseed-hook.mjs +21 -7
  10. package/docs/PRD.md +1 -1
  11. package/docs/concepts/enforcement-table.md +22 -3
  12. package/docs/concepts/exclusions.md +48 -2
  13. package/docs/concepts/foreman-mode.md +19 -4
  14. package/docs/concepts/hook-gates.md +1 -1
  15. package/docs/concepts/hooks.md +53 -12
  16. package/docs/concepts/host-matrix.md +4 -3
  17. package/docs/concepts/hosts.md +1 -1
  18. package/docs/concepts/kits.md +18 -0
  19. package/docs/concepts/shared-tier.md +5 -5
  20. package/docs/concepts/skills.md +1 -1
  21. package/docs/extending.md +3 -1
  22. package/docs/guides/autostart.md +27 -3
  23. package/docs/guides/choose-your-setup.md +1 -1
  24. package/docs/guides/migrate.md +5 -3
  25. package/docs/guides/uninstall.md +1 -1
  26. package/docs/guides/upgrade-to-5.md +6 -4
  27. package/docs/reference/plugin-context.md +1 -1
  28. package/docs/reference/plugin-guard.md +24 -5
  29. package/docs/reference/troubleshoot-doctor.md +2 -2
  30. package/docs/understand/a-day.md +9 -5
  31. package/docs/web-ui.md +78 -20
  32. package/harness.config.json +1 -1
  33. package/js/README.md +3 -2
  34. package/js/build/emit-claude.mjs +9 -1
  35. package/js/build/emit-opencode.mjs +2 -1
  36. package/js/build/fold.mjs +7 -7
  37. package/js/build/rule-decide.mjs +273 -0
  38. package/js/build/source.mjs +9 -3
  39. package/js/cli-table.json +122 -2
  40. package/js/hosts/geneseed-dir.mjs +1 -1
  41. package/js/hosts/hooks-context.mjs +9 -7
  42. package/js/hosts/hooks-done.mjs +3 -1
  43. package/js/hosts/hooks-learn.mjs +1 -1
  44. package/js/hosts/hooks-prims.mjs +270 -0
  45. package/js/hosts/hooks.mjs +409 -151
  46. package/js/hosts/hosts.mjs +22 -0
  47. package/js/hosts/installs.mjs +13 -9
  48. package/js/hosts/memory-files.mjs +2 -2
  49. package/js/hosts/settings.mjs +123 -23
  50. package/js/hosts/shim.mjs +155 -7
  51. package/js/hosts/store-watch.mjs +41 -14
  52. package/js/inspect/diff.mjs +2 -1
  53. package/js/inspect/inventory.mjs +1 -0
  54. package/js/inspect/registry.mjs +4 -2
  55. package/js/inspect/validate.mjs +1 -1
  56. package/js/lib/paths.mjs +13 -0
  57. package/js/maintain/migrate.mjs +60 -22
  58. package/js/maintain/uninstall.mjs +5 -1
  59. package/js/web/actions.mjs +17 -1
  60. package/js/web/api.mjs +22 -16
  61. package/js/web/handler.mjs +2 -0
  62. package/js/web/routes.mjs +9 -4
  63. package/js/web/update-check.mjs +2 -2
  64. package/js/web/user-files.mjs +38 -11
  65. package/package.json +1 -1
  66. package/registry.json +21 -0
  67. package/src/AGENT.md.tmpl +17 -21
  68. package/src/agents/_self-improvement.md +7 -6
  69. package/src/agents/developer.md +3 -2
  70. package/src/agents/docker-expert.md +1 -0
  71. package/src/agents/memory-curator.md +3 -2
  72. package/src/doctrines/process.md +24 -19
  73. package/src/kits/ci-pipelines/rules.md +10 -0
  74. package/src/kits/ci-pipelines.json +14 -0
  75. package/src/kits/docker/rules.md +11 -0
  76. package/src/kits/docker.json +12 -0
  77. package/src/memory/README.md +5 -4
  78. package/src/modes/foreman.md +23 -10
  79. package/src/notebook/README.md +1 -1
  80. package/src/skills/_self-improvement.md +12 -9
  81. package/src/skills/compose-ops.md +58 -0
  82. package/src/skills/gitlab-ci.md +51 -0
  83. package/src/skills/jenkins-pipeline.md +56 -0
  84. package/src/skills/pipeline.md +2 -2
  85. package/src/skills/rule/approve.md +11 -5
  86. package/src/skills/rule.md +26 -19
  87. package/src/skills/skill-forge.md +24 -6
  88. package/themes/_TEMPLATE.json +5 -2
  89. package/themes/biker.json +5 -2
  90. package/themes/commentator.json +5 -2
  91. package/themes/cyberpunk.json +5 -2
  92. package/themes/gamer.json +5 -2
  93. package/themes/imperial.json +5 -2
  94. package/themes/joker.json +5 -2
  95. package/themes/marvin.json +5 -2
  96. package/themes/mean.json +5 -2
  97. package/themes/military.json +5 -2
  98. package/themes/neutral.json +5 -2
  99. package/themes/pirate.json +5 -2
  100. package/themes/sports.json +5 -2
  101. package/themes/verstappen.json +5 -2
  102. package/themes/wizard.json +5 -2
  103. package/web/dist/assets/Activity-Ck_Xffpo.js +1 -0
  104. package/web/dist/assets/ActivityDetail-CBxVS4mU.js +1 -0
  105. package/web/dist/assets/{Bonsai-B_y20b3i.js → Bonsai-BlOwsvW6.js} +1 -1
  106. package/web/dist/assets/{CopyButton-CHQte7Ap.js → CopyButton-DFMOIGbe.js} +1 -1
  107. package/web/dist/assets/Dashboard-BUdUTjbB.js +2 -0
  108. package/web/dist/assets/{Docs-Dgv_MWfT.js → Docs-D_2Jt6gU.js} +3 -3
  109. package/web/dist/assets/{GreenhouseView-CSzTMSl_.js → GreenhouseView-WalcX5bp.js} +1 -1
  110. package/web/dist/assets/Installs-UGiPDMDt.js +3 -0
  111. package/web/dist/assets/{JournalView-CvRk1-m5.js → JournalView-CZtXQz-v.js} +1 -1
  112. package/web/dist/assets/Kits-XQHsazCN.js +1 -0
  113. package/web/dist/assets/Laws-B6A55S-2.js +4 -0
  114. package/web/dist/assets/Library-D7L0Wdbh.js +3 -0
  115. package/web/dist/assets/Loops-C0loS73u.js +2 -0
  116. package/web/dist/assets/{OperatorHudView-DuGz_sTk.js → OperatorHudView-CeDw5qMB.js} +1 -1
  117. package/web/dist/assets/Personal-PVmGA2-M.js +2 -0
  118. package/web/dist/assets/{RailCats-AW92uhsX.js → RailCats-BGZnJ6fa.js} +1 -1
  119. package/web/dist/assets/Settings-DWuxwh4i.js +1 -0
  120. package/web/dist/assets/Tabs-d2RIRAKT.js +1 -0
  121. package/web/dist/assets/api-BMFDSXoB.js +1 -0
  122. package/web/dist/assets/index-BEI5ugYQ.css +1 -0
  123. package/web/dist/assets/index-BNttaGQb.js +6 -0
  124. package/web/dist/index.html +3 -3
  125. package/web/dist/assets/Activity-D8G4eClY.js +0 -1
  126. package/web/dist/assets/ActivityDetail-BtOBYk3M.js +0 -1
  127. package/web/dist/assets/Dashboard-B8uXeJZ_.js +0 -2
  128. package/web/dist/assets/Installs-BDk9lqBI.js +0 -3
  129. package/web/dist/assets/Kits-CoITzxWM.js +0 -1
  130. package/web/dist/assets/Laws-Ctf5r9rE.js +0 -3
  131. package/web/dist/assets/Library-DNwHYVXt.js +0 -3
  132. package/web/dist/assets/Loops-S85PMQ8m.js +0 -2
  133. package/web/dist/assets/Personal-afJNwvRS.js +0 -2
  134. package/web/dist/assets/Settings-CGDFz-6j.js +0 -1
  135. package/web/dist/assets/Tabs-1qLrnqmn.js +0 -1
  136. package/web/dist/assets/api-C46vAuqp.js +0 -1
  137. package/web/dist/assets/index-COTd4TRZ.js +0 -3
  138. package/web/dist/assets/index-CtorA7uK.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);
@@ -617,9 +621,9 @@ export function openclaudeDualHarnessRoots() {
617
621
  }
618
622
 
619
623
  /** (host, scope, root) for every registered root. */
620
- export function registeredTargets() {
624
+ export function registeredTargets(opts) {
621
625
  const out = [];
622
- for (const root of registryRoots()) {
626
+ for (const root of registryRoots(opts)) {
623
627
  const hs = emitHostScopeOf(root);
624
628
  if (hs) out.push([hs[0], hs[1], root]);
625
629
  }
@@ -637,7 +641,7 @@ export function registeredTargets() {
637
641
  * `Path.resolve()` returns the filesystem's own casing — on Windows two spellings of the same
638
642
  * directory differ as strings and not as installs, and this Set is keyed by string.
639
643
  */
640
- export function installTargets() {
644
+ export function installTargets(opts) {
641
645
  const out = [];
642
646
  const seen = new Set();
643
647
 
@@ -664,7 +668,7 @@ export function installTargets() {
664
668
  for (const { host, configDir } of HOSTS) {
665
669
  try { add(host, 'global', configDir()); } catch { /* a missing host dir is not fatal */ }
666
670
  }
667
- for (const [host, scope, root] of registeredTargets()) add(host, scope, root);
671
+ for (const [host, scope, root] of registeredTargets(opts)) add(host, scope, root);
668
672
  return out;
669
673
  }
670
674
 
@@ -564,8 +564,8 @@ export function parseRules(text) {
564
564
  return [rules, warnings];
565
565
  }
566
566
 
567
- // The draft's block headings: the fold writes them, `parseDraft` reads them, and the rule Rite's
568
- // approval flow (src/skills/rule/approve.md) names them, so a change here changes that file too.
567
+ // The draft's block headings: the fold writes them, `parseDraft` reads them, and the approval flow
568
+ // (src/skills/rule/approve.md, js/build/rule-decide.mjs) names them, so a change here changes both.
569
569
  export const draftRuleHead = (host, title) => `## Rule from ${host}: ${title}`;
570
570
  export const draftChoiceHead = (file) => `## Choose: ${file}`;
571
571
  const DRAFT_RULE_RE = /^## Rule from ([^:]+): (.+)$/;
@@ -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
@@ -1125,6 +1164,67 @@ export function wireClaudeExcludes(p, excludes) {
1125
1164
  return added;
1126
1165
  }
1127
1166
 
1167
+ /**
1168
+ * The `env` keys a Claude Code install arms. Foreman mode allows main → worker → sub-worker and
1169
+ * no deeper; Claude Code's own default is three layers, so the cap is written, not assumed.
1170
+ * Claude only: OpenClaude has no such cap in its source (checked on 0.31) and Bob documents none.
1171
+ */
1172
+ export const CLAUDE_ENV = Object.freeze({ CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH: '2' });
1173
+
1174
+ /**
1175
+ * Add-if-absent into `env`, the `wireClaudeExcludes` shape: a key the user already set, to any
1176
+ * value, is theirs and stays. Returns the `{key: value}` pairs actually written, which the
1177
+ * manifest records so uninstall removes only those.
1178
+ */
1179
+ export function wireClaudeEnv(p, want = CLAUDE_ENV) {
1180
+ const loaded = readSettingsForMerge(p, 'Its "env" keys were not wired.');
1181
+ if (!loaded) return {};
1182
+ const [config, hadComments] = loaded;
1183
+ // An `env` that is there but is not an object is the user's, however wrong: never replaced.
1184
+ if (has(config, 'env') && !isDict(config.env)) {
1185
+ process.stderr.write(`[geneseed] WARN: "env" in ${path.basename(p)} is not an object — `
1186
+ + `NOT rewriting it. Add to it by hand once it is one: ${jsonDumpsCompact(want)}\n`);
1187
+ return {};
1188
+ }
1189
+ const env = has(config, 'env') ? config.env : {};
1190
+ const added = Object.fromEntries(Object.entries(want || {}).filter(([k]) => !has(env, k)));
1191
+ if (!Object.keys(added).length) return {};
1192
+ if (hadComments) {
1193
+ process.stderr.write(`[geneseed] ${path.basename(p)} has comments — not rewriting it `
1194
+ + '(your edits are kept). Add to its "env" object by hand: '
1195
+ + `${jsonDumpsCompact(added)}\n`);
1196
+ return {};
1197
+ }
1198
+ config.env = { ...env, ...added };
1199
+ try {
1200
+ atomicWriteJson(p, config);
1201
+ } catch (e) {
1202
+ if (!isOsError(e)) throw e;
1203
+ process.stderr.write(`[geneseed] WARN: could not write ${p} (${e.message}) — `
1204
+ + `its "env" keys were not wired. Add to its "env" object by hand: ${jsonDumpsCompact(added)}\n`);
1205
+ return {};
1206
+ }
1207
+ return added;
1208
+ }
1209
+
1210
+ /** Remove each recorded `env` key while it still holds the recorded value; drop an empty `env`. */
1211
+ export function unwireClaudeEnv(p, recorded) {
1212
+ if (!isDict(recorded) || !Object.keys(recorded).length) return;
1213
+ const { state, data: loaded, hadComments } = loadJsonObject(p);
1214
+ if (state !== 'ok' || hadComments) return;
1215
+ const env = get(loaded, 'env');
1216
+ if (!isDict(env)) return;
1217
+ const gone = Object.keys(recorded).filter((k) => has(env, k) && env[k] === recorded[k]);
1218
+ if (!gone.length) return;
1219
+ for (const k of gone) delete env[k];
1220
+ if (!Object.keys(env).length) delete loaded.env;
1221
+ try {
1222
+ atomicWriteJson(p, loaded);
1223
+ } catch (e) {
1224
+ if (!isOsError(e)) throw e;
1225
+ }
1226
+ }
1227
+
1128
1228
  /** `_build_settings._unwire_claude_excludes`. */
1129
1229
  export function unwireClaudeExcludes(p, excludes) {
1130
1230
  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
+ }