geneseed 5.1.1 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/SHIPPED.md +1 -1
  3. package/adapters/opencode/README.md +4 -3
  4. package/adapters/opencode/plugins/geneseed-context.js +26 -19
  5. package/adapters/opencode/plugins/geneseed-guard.js +112 -7
  6. package/bin/geneseed-cli.mjs +3 -0
  7. package/docs/concepts/exclusions.md +1 -1
  8. package/docs/concepts/host-matrix.md +1 -1
  9. package/docs/guides/setup-doctrines.md +1 -1
  10. package/docs/understand/enforced-vs-asked.md +1 -1
  11. package/harness.config.json +1 -1
  12. package/js/README.md +6 -4
  13. package/js/build/args.mjs +7 -1
  14. package/js/build/bundle.mjs +122 -23
  15. package/js/build/driver.mjs +32 -12
  16. package/js/build/emit-claude.mjs +2 -1
  17. package/js/build/emit-common.mjs +2 -2
  18. package/js/build/emit-opencode.mjs +22 -10
  19. package/js/build/export.mjs +431 -0
  20. package/js/build/generate.mjs +3 -0
  21. package/js/build/source.mjs +6 -1
  22. package/js/cli-table.json +99 -0
  23. package/js/hosts/hooks-done.mjs +8 -2
  24. package/js/hosts/hooks.mjs +105 -4
  25. package/js/hosts/hosts.mjs +2 -4
  26. package/js/hosts/installs.mjs +28 -0
  27. package/js/hosts/loss.mjs +19 -2
  28. package/js/hosts/native.mjs +30 -2
  29. package/js/hosts/owned.mjs +55 -1
  30. package/js/hosts/ownership-gate.mjs +5 -5
  31. package/js/hosts/settings.mjs +83 -33
  32. package/js/lib/managed-block.mjs +74 -0
  33. package/js/maintain/uninstall.mjs +57 -14
  34. package/js/web/actions.mjs +3 -0
  35. package/js/web/api.mjs +4 -1
  36. package/package.json +1 -1
  37. package/web/dist/assets/{Activity-CpkBwpu7.js → Activity-DlQ30znB.js} +1 -1
  38. package/web/dist/assets/{ActivityDetail-DTPziZWM.js → ActivityDetail-CG0mn5fW.js} +1 -1
  39. package/web/dist/assets/{Bonsai-hiG_gGNU.js → Bonsai-DSwUbavu.js} +1 -1
  40. package/web/dist/assets/{CopyButton-DUIUfNp6.js → CopyButton-BzRQz7k2.js} +1 -1
  41. package/web/dist/assets/{Dashboard-Dnw6EyX7.js → Dashboard-Ce3UOsxJ.js} +2 -2
  42. package/web/dist/assets/{Docs-BEET_l16.js → Docs-CisVnYqv.js} +1 -1
  43. package/web/dist/assets/{Factories-D6KXkfWw.js → Factories-Dq5oW4CU.js} +1 -1
  44. package/web/dist/assets/{GreenhouseView-BKxy5apE.js → GreenhouseView-y9WAfcc_.js} +1 -1
  45. package/web/dist/assets/Installs-m4GElwFW.js +3 -0
  46. package/web/dist/assets/{JournalView-ChFitHjo.js → JournalView-DeBLRNGc.js} +1 -1
  47. package/web/dist/assets/{Kits-CcR-OlwQ.js → Kits-DJYVAnyE.js} +1 -1
  48. package/web/dist/assets/{Laws-B1s5idOg.js → Laws-CNpc_8ZV.js} +1 -1
  49. package/web/dist/assets/{LibRows-BZgdbI1l.js → LibRows-RO5bvXth.js} +1 -1
  50. package/web/dist/assets/{Library-x6TkkEVF.js → Library-Dg0ScciC.js} +1 -1
  51. package/web/dist/assets/{Loops-BH93KKxn.js → Loops-CjEdo-NG.js} +1 -1
  52. package/web/dist/assets/{OperatorHudView-BO0aIKPL.js → OperatorHudView-2ujVMjq1.js} +1 -1
  53. package/web/dist/assets/{Personal-CE_0Vhh0.js → Personal-D0yS7ahT.js} +1 -1
  54. package/web/dist/assets/{Settings-CbpZvVN_.js → Settings-DEN0U8QI.js} +1 -1
  55. package/web/dist/assets/{Tabs-C2oW7oEj.js → Tabs-But5R6_r.js} +1 -1
  56. package/web/dist/assets/{index-BQwOmbor.js → index-Ck42AbRX.js} +2 -2
  57. package/web/dist/assets/{index-CuIop_pO.css → index-PG_ukkh6.css} +1 -1
  58. package/web/dist/index.html +2 -2
  59. package/web/dist/assets/Installs-CnFVlVD0.js +0 -3
@@ -56,6 +56,7 @@ import path from 'node:path';
56
56
  import { printOut as out, printErr as err, withDiscardableStderr } from '../lib/fs.mjs';
57
57
  import { normcase } from '../lib/paths.mjs';
58
58
  import { machineDir } from '../lib/machine-dir.mjs';
59
+ import { markerLines } from '../lib/managed-block.mjs';
59
60
  import { isDict, isTruthy, parseJson, readJsonc } from '../lib/json.mjs';
60
61
  import {
61
62
  GATE_LEDGER, carrierBlock, carrierName, globalHookStandingDown, hookProjectDir, isSharedCarrier,
@@ -763,6 +764,68 @@ export function shellWriteTargets(command, cwd, ps = false) {
763
764
  }
764
765
  return [...found];
765
766
  }
767
+ /**
768
+ * THE ONE READING OF A COMMAND every gate below is handed. The lexers here are non-POSIX on
769
+ * purpose (`SCAN_TOKEN_RE`: a backslash is never an escape, so PowerShell's `"C:\"` closes), and
770
+ * that is wrong for the shell most commands run in. In bash:
771
+ * - a backslash-newline joins two lines, so `rm -rf \⏎ /` is one command. Read as two, the
772
+ * operand landed in a segment with no program and every gate passed it;
773
+ * - `\'` and `\"` outside single quotes are a literal quote, not a delimiter. Read as one, the
774
+ * everyday `'it'\''s'` left the quote state inverted and hid the rest of the line as data,
775
+ * `&& rm -rf /` included.
776
+ * So for a bash-like shell the continuation is joined and an escaped quote or separator is
777
+ * replaced by `_`, which is inert to every lexer and keeps every other character where it was.
778
+ * For PowerShell only its own continuation, a backtick-newline, is joined, and nothing else
779
+ * changes: there the backslash is a path separator.
780
+ *
781
+ * `shell` is what the caller knows: `'bash'` (Claude's `Bash` tool, Git Bash on Windows too),
782
+ * `'powershell'`, or null. Unknown is read as bash unless the platform is Windows or a
783
+ * `Verb-Noun` word says PowerShell.
784
+ */
785
+ export function shellReading(command, shell = null) {
786
+ const bashLike = shell === 'bash'
787
+ || (shell !== 'powershell' && process.platform !== 'win32' && !PS_CUE_RE.test(command));
788
+ if (!bashLike) return command.replace(/`\r?\n/g, '');
789
+ if (!command.includes('\\')) return command;
790
+ let out = '';
791
+ let quote = '';
792
+ const tags = []; // heredocs opened on this line: `[stripTabs, tag]`
793
+ for (let i = 0; i < command.length; i += 1) {
794
+ const ch = command[i];
795
+ const next = command[i + 1];
796
+ // A heredoc body is copied as it is: under a quoted tag a backslash is literal, and the
797
+ // gates read a body as data or, for `bash <<EOF`, as the command it is.
798
+ if (!quote && ch === '<' && next === '<' && command[i + 2] !== '<' && command[i - 1] !== '<') {
799
+ const m = /^<<(-?)[ \t]*(["']?)([A-Za-z_]\w*)\2/.exec(command.slice(i));
800
+ if (m) { tags.push([m[1], m[3]]); out += m[0]; i += m[0].length - 1; continue; }
801
+ }
802
+ if (!quote && ch === '\n' && tags.length) {
803
+ out += ch;
804
+ while (tags.length) {
805
+ const end = command.indexOf('\n', i + 1);
806
+ const line = command.slice(i + 1, end < 0 ? command.length : end);
807
+ out += line + (end < 0 ? '' : '\n');
808
+ i = end < 0 ? command.length : end;
809
+ const bare = line.replace(/\r$/, '');
810
+ if ((tags[0][0] ? bare.replace(/^\t+/, '') : bare) === tags[0][1]) tags.shift();
811
+ if (end < 0) break;
812
+ }
813
+ continue;
814
+ }
815
+ if (ch === '\\' && quote !== "'" && next !== undefined) {
816
+ const eol = next === '\n' ? 1 : (next === '\r' && command[i + 2] === '\n' ? 2 : 0);
817
+ if (eol) { i += eol; continue; }
818
+ // In double quotes only `\"` matters to a lexer; outside, a quote or a separator does.
819
+ out += ch + ((quote ? next === '"' : /["';|&]/.test(next)) ? '_' : next);
820
+ i += 1;
821
+ continue;
822
+ }
823
+ if (quote) { if (ch === quote) quote = ''; } else if (ch === '"' || ch === "'") quote = ch;
824
+ out += ch;
825
+ }
826
+ return out;
827
+ }
828
+
766
829
  // ---- shell-write twin: END
767
830
 
768
831
  /**
@@ -802,10 +865,47 @@ function shellStoreReason(args, command, payload) {
802
865
  return null;
803
866
  }
804
867
 
868
+ // The git verbs that neither commit nor push nor run a command of the caller's choosing, and the
869
+ // programs that only read. `consentBenign` is the only reader.
870
+ const GIT_READ_VERBS = new Set(['log', 'diff', 'show', 'status', 'stash', 'blame', 'grep', 'ls-files',
871
+ 'rev-parse', 'reflog', 'shortlog', 'describe', 'branch', 'fetch', 'help', 'ls-remote', 'cat-file']);
872
+ const READ_PROGS = new Set(['cat', 'head', 'tail', 'less', 'more', 'grep', 'egrep', 'rg', 'ls', 'wc',
873
+ 'sort', 'uniq', 'cut', 'file', 'stat', 'true', 'cd']);
874
+
875
+ /**
876
+ * True when a command that trips `GIT_GATE_RE` provably neither commits nor pushes: the regex
877
+ * reads words, so `git log | grep push`, `cat .git/hooks/pre-commit.sample`, `git stash push`
878
+ * and `git diff -- docs/commit-style.md` all asked, and a gate that asks when nothing is at
879
+ * stake trains the click-through it exists to prevent.
880
+ *
881
+ * FAIL-CLOSED: the ask stands unless EVERY segment is one of two known shapes, a program that
882
+ * only reads, or `git` with a read verb reached past `-C <dir>`/`--no-pager` alone. Anything
883
+ * else keeps the ask: another program (`sh`, `xargs`, `sudo`: it may run the words), another
884
+ * git option (`-c alias.x=…`), a verb outside the list (an alias may be a commit), a
885
+ * substitution, or a redirection into a file.
886
+ */
887
+ function consentBenign(command) {
888
+ if (/\$\(|`|[<>]/.test(command)) return false;
889
+ for (const seg of scanSegments(command)) {
890
+ const toks = stripStructure(seg.match(SCAN_TOKEN_RE) || []).map(unquote);
891
+ if (!toks.length) continue;
892
+ const prog = toks[0].toLowerCase();
893
+ if (READ_PROGS.has(prog)) continue;
894
+ if (prog !== 'git') return false;
895
+ let i = 1;
896
+ while (i < toks.length && (toks[i] === '--no-pager' || toks[i] === '-C')) i += toks[i] === '-C' ? 2 : 1;
897
+ if (!GIT_READ_VERBS.has(toks[i])) return false;
898
+ // `git stash push` and `git branch` take no option that runs a command; `--exec`/`-c` do.
899
+ if (toks.slice(i + 1).some((t) => /^(?:--exec|--upload-pack|--receive-pack|-c$|--ext)/.test(t))) return false;
900
+ }
901
+ return true;
902
+ }
903
+
805
904
  function gitDecide(args, payload) {
806
905
  const ti = (payload && payload.tool_input) || {};
807
- const { command } = ti;
808
- if (typeof command !== 'string') return 0;
906
+ if (typeof ti.command !== 'string') return 0;
907
+ const tool = payload && payload.tool_name;
908
+ const command = shellReading(ti.command, tool === 'Bash' ? 'bash' : tool === 'PowerShell' ? 'powershell' : null);
809
909
  // The agent's own words, for the asks where they are no conflict of interest (`gateText`'s `quote`).
810
910
  const says = typeof ti.description === 'string' ? ti.description : '';
811
911
  // Law IV's catastrophic class (a root, a drive, the home dir, a disk): no state makes it safe,
@@ -842,7 +942,7 @@ function gitDecide(args, payload) {
842
942
  // `--no-consent`: the process pack (or process 5 alone) is off, so the commit/push ask has
843
943
  // no rule behind it — but Law IV above is universal and has already run. Checked before
844
944
  // `loopExempt` so a non-git command, or one with consent off, never pays for the whitelist.
845
- if (args.noConsent || !GIT_GATE_RE.test(command)) return 0;
945
+ if (args.noConsent || !GIT_GATE_RE.test(command) || consentBenign(command)) return 0;
846
946
  // Consent Before Push: a loop launched on its own `loop/*` branch is a named batch for a
847
947
  // fixed set of commit/push forms on that branch only — never a merge into anything shared.
848
948
  if (loopExempt(command, (payload && payload.cwd) || process.cwd())) return 0;
@@ -1182,7 +1282,8 @@ function carrierBlockChange(p, payload) {
1182
1282
  if (e?.code !== 'ENOENT') return true;
1183
1283
  }
1184
1284
  const after = carrierAfter(before, payload);
1185
- return after === null || after.length > CARRIER_REPLAY_CAP || carrierBlock(after) !== carrierBlock(before);
1285
+ return after === null || after.length > CARRIER_REPLAY_CAP || carrierBlock(after) !== carrierBlock(before)
1286
+ || markerLines(after) !== markerLines(before);
1186
1287
  }
1187
1288
 
1188
1289
  /**
@@ -20,6 +20,7 @@ import os from 'node:os';
20
20
  import { printErr, withDiscardableStderr, isDir, isFile, readText } from '../lib/fs.mjs';
21
21
  import { toPlatformPath, normcase } from '../lib/paths.mjs';
22
22
  import { sharedPaths, machineDir } from '../lib/machine-dir.mjs';
23
+ import { blockOf } from '../lib/managed-block.mjs';
23
24
  import { mainWorktreeOf } from './gitref.mjs';
24
25
 
25
26
  /** The marker a project built `--shared-tier on` carries, and its one reader. The OpenCode context plugin holds a copy. */
@@ -517,12 +518,9 @@ export const CARRIERS = [
517
518
  path.join('rules', 'geneseed.md'), 'AGENTS.md',
518
519
  ];
519
520
 
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
521
  const SHARED_CARRIER_RE = /(?:^|[\\/])(?:CLAUDE|AGENTS)\.md$/i;
524
522
  /** The managed block as a reader sees it, `''` with none. */
525
- export const carrierBlock = (text) => CARRIER_BLOCK_RE.exec(text)?.[0] ?? '';
523
+ export const carrierBlock = (text) => blockOf(text);
526
524
  /** The file a Windows write lands on: `CLAUDE.md::$DATA` and `CLAUDE.md.` both write `CLAUDE.md`. */
527
525
  export function carrierName(file) {
528
526
  const s = String(file);
@@ -45,6 +45,7 @@ import { registryRoots } from '../inspect/registry.mjs';
45
45
  import { printErr, readText, isFile, isDir } from '../lib/fs.mjs';
46
46
  import { formatRepr, isDict } from '../lib/json.mjs';
47
47
  import { comparePaths } from '../lib/paths.mjs';
48
+ import { bundleLeftovers, ownedWithin } from './owned.mjs';
48
49
  import { claudeHookShell, hookShimPath } from './shim.mjs';
49
50
 
50
51
  export { carriersFor };
@@ -586,6 +587,33 @@ export function installKind(root) {
586
587
  return null;
587
588
  }
588
589
 
590
+ /**
591
+ * What the last emit left at `root` that is not Geneseed's copy, for the console: `kept`, the
592
+ * files that are the user's at a path Geneseed ships (an edit to a shipped skill, or a file of
593
+ * theirs under a shipped name), and `stale`, the retired skills an older build left in a bundle.
594
+ * Rels are spelled from `root`, the way the user would find them.
595
+ *
596
+ * Read off what the emit recorded (the manifest's `kept`, and for an OpenCode project the
597
+ * bundle marker at the root), never by rendering, so a page poll can afford it. Each entry
598
+ * only while its file still exists: a file the user removed since is no leftover. A build
599
+ * with `--force` replaces the first kind and removes the second.
600
+ */
601
+ export function leftoversOf(root, host = 'opencode', scope = 'global') {
602
+ const cfg = scope === 'project' ? claudeCfg(root, 'project', host) : root;
603
+ const prefix = scope === 'project' ? `${path.basename(cfg)}/` : '';
604
+ const man = claudeReadManifest(cfg);
605
+ const recorded = isDict(man) && Array.isArray(man.kept) ? man.kept : [];
606
+ const kept = ownedWithin(cfg, recorded.filter((r) => typeof r === 'string'))
607
+ .filter((r) => isFile(path.join(cfg, r))).map((r) => `${prefix}${r}`);
608
+ let stale = [];
609
+ if (host === 'opencode' && scope === 'project') {
610
+ const bundle = bundleLeftovers(root);
611
+ kept.push(...bundle.kept);
612
+ stale = bundle.stale;
613
+ }
614
+ return { kept: kept.sort(), stale };
615
+ }
616
+
589
617
  /** 'active' | 'disabled' | 'absent'. */
590
618
  export function installState(root, host = 'opencode', scope = 'global') {
591
619
  if (CLAUDE_STYLE.includes(host)) return claudeState(root, scope, host);
package/js/hosts/loss.mjs CHANGED
@@ -600,7 +600,16 @@ export function lossReason(segments, cwd, { always = true, split } = {}) {
600
600
  /** The first loss among `segs`, run from `start`; a substitution body is judged as a command. */
601
601
  const judge = (segs, start, depth = 0) => {
602
602
  let dir = start;
603
- for (const raw of segs.map(stripStructure)) {
603
+ // A `cd` inside `( … )` ends with the subshell, and `popd` goes back somewhere this reader
604
+ // never recorded. Both used to leave `dir` where the `cd` put it, so a removal after them
605
+ // was looked for in the wrong folder, found absent, and passed. Now the directory is
606
+ // unknown from there on, which asks for a relative path.
607
+ let nest = 0;
608
+ let cdInside = false;
609
+ for (const [n, raw] of segs.map(stripStructure).entries()) {
610
+ const bare = segs[n].filter((t) => !/^["']/.test(t));
611
+ const opens = bare.filter((t) => /^\(/.test(t)).length;
612
+ const closes = bare.filter((t) => /\)$/.test(t) && !/\$\(/.test(t)).length;
604
613
  const text = raw.join(' ');
605
614
  const named = LOSS_CANDIDATE_RE.test(text);
606
615
  for (const body of named ? substitutions(text) : []) {
@@ -616,12 +625,19 @@ export function lossReason(segments, cwd, { always = true, split } = {}) {
616
625
  w = /^\w+=/.test(w[0]) ? w.slice(1) : pastWrapper(wrapper, w.slice(1));
617
626
  if (!w && named) unverified(`\`${wrapper}\` takes a flag the gate does not know`);
618
627
  }
619
- if (!w || !w.length) continue;
628
+ const leave = () => {
629
+ nest = Math.max(0, nest + opens - closes);
630
+ if (nest === 0 && cdInside) { dir = null; cdInside = false; }
631
+ };
632
+ if (!w || !w.length) { leave(); continue; }
620
633
  const prog = progOf(w[0]);
621
634
  const args = w.slice(1);
635
+ if (prog === 'popd' || prog === 'pop-location') { dir = null; leave(); continue; }
622
636
  if (CD_PROGS.has(prog)) {
623
637
  const target = args.find((a) => !a.startsWith('-') && !/^\/d$/i.test(a));
624
638
  try { dir = target && target !== '-' ? resolveIn(dir, target) : null; } catch { dir = null; }
639
+ if (nest + opens > 0) cdInside = true;
640
+ leave();
625
641
  continue;
626
642
  }
627
643
  let verdict = null;
@@ -636,6 +652,7 @@ export function lossReason(segments, cwd, { always = true, split } = {}) {
636
652
  unverified(`\`${w[0].replace(OPAQUE, '')}\` is not a program the gate reads, and a removal follows it`);
637
653
  }
638
654
  if (verdict) return verdict;
655
+ leave();
639
656
  }
640
657
  return null;
641
658
  };
@@ -524,11 +524,21 @@ function warnBobIgnored(overrides) {
524
524
  * Geneseed's copy back" — two warnings about one rel that is in fact still shipped. The caller
525
525
  * reads this set back off the closure and hands it to `pruneOwned` so that rel is excluded from
526
526
  * the stale set entirely, silently, rather than re-evaluated.
527
+ *
528
+ * `claim.kept`: every rel this closure refused, edited or pre-existing. The emit writes it into
529
+ * the manifest (`kept`), which is how the console knows an install holds files that are the
530
+ * user's where Geneseed ships one, without rendering anything.
531
+ *
532
+ * `force` (`--force`): both refusals become overwrites, each named on stderr. It reaches only
533
+ * what `claim` is asked about, and `claim` is asked only about a path Geneseed ships, so a
534
+ * skill or agent under the user's own name is never in question. The leaf guard still runs: a
535
+ * forced write goes through a link no more than an ordinary one does.
527
536
  */
528
- export function claimer(oldOwned, cfg, manifestExisted = true, oldHashes = {}) {
537
+ export function claimer(oldOwned, cfg, manifestExisted = true, oldHashes = {}, force = false) {
529
538
  const oldSet = oldOwned !== null && oldOwned !== undefined ? new Set(oldOwned) : null;
530
539
  let headerPrinted = false;
531
540
  const editRefused = new Set();
541
+ const kept = new Set();
532
542
  const rroot = cfg != null ? resolvePath(cfg) : undefined; // once per emit, not per leaf
533
543
  const claim = (dest) => {
534
544
  if (cfg != null && !claimLeaf(cfg, dest, relPosix(cfg, dest), rroot)) return false;
@@ -540,12 +550,21 @@ export function claimer(oldOwned, cfg, manifestExisted = true, oldHashes = {}) {
540
550
  // constraint that a manifest without `hashes` keeps today's behaviour exactly is this
541
551
  // branch doing nothing extra, not a special case.
542
552
  if (ownedState(cfg, rel, oldHashes) === 'modified') {
553
+ if (force) {
554
+ warn(`[geneseed] --force: replaced your edited ${rel}`);
555
+ return true;
556
+ }
543
557
  warn(`[geneseed] kept your edited ${rel} — delete it to get Geneseed's copy back`);
544
558
  editRefused.add(rel);
559
+ kept.add(rel);
545
560
  return false;
546
561
  }
547
562
  return true;
548
563
  }
564
+ if (force) {
565
+ warn(`[geneseed] --force: replaced your existing ${rel}`);
566
+ return true;
567
+ }
549
568
  if (!manifestExisted && !headerPrinted) {
550
569
  warn('[geneseed] first emit over a pre-manifest install — existing files '
551
570
  + 'are treated as yours');
@@ -553,9 +572,13 @@ export function claimer(oldOwned, cfg, manifestExisted = true, oldHashes = {}) {
553
572
  }
554
573
  warn(`[geneseed] kept your existing ${rel} — skipped Geneseed's copy to avoid `
555
574
  + 'clobbering it');
575
+ kept.add(rel);
556
576
  return false;
557
577
  };
558
578
  claim.editRefused = editRefused;
579
+ claim.kept = kept;
580
+ // Did the previous emit write `dest`? Read by `writeNativeLayer` for a skill's side files.
581
+ claim.owned = (dest) => oldSet !== null && cfg != null && oldSet.has(relPosix(cfg, dest));
559
582
  return claim;
560
583
  }
561
584
 
@@ -745,8 +768,13 @@ export function writeNativeLayer(items, agentsDir, skillsDir, overrides = null,
745
768
  if (kind === 'agent') nAgents += 1;
746
769
  else nSkills += 1;
747
770
  }
771
+ // A side file follows its skill's claim, with one exception: a side file the previous emit
772
+ // wrote stays maintained when the claim on SKILL.md no longer holds. That is a shipped skill
773
+ // whose SKILL.md the user edited. The edit takes SKILL.md out of `owned` for good, and
774
+ // skipping its side files here dropped them out too, so the prune deleted them: the kept
775
+ // SKILL.md pointed at a file that was gone, and credited text lost its licence.
748
776
  for (const [stem, dest, text, source] of sideFiles) {
749
- if (!claimedSkills.has(stem) || !claim(dest)) continue;
777
+ if (!(claimedSkills.has(stem) || claim.owned?.(dest)) || !claim(dest)) continue;
750
778
  if (text !== null) { write(dest, stripSkillBodyLinks(text)); continue; }
751
779
  mkdirSync(path.dirname(dest), { recursive: true });
752
780
  copyFile(source, dest);
@@ -27,6 +27,7 @@ import path from 'node:path';
27
27
  import { resolvePath } from './hosts.mjs';
28
28
  import { within } from '../lib/paths.mjs';
29
29
  import { isFile, statOrNull, textWrites } from '../lib/fs.mjs';
30
+ import { isDict, parseJson } from '../lib/json.mjs';
30
31
 
31
32
  /**
32
33
  * The manifest rels that resolve INSIDE `base` — the one security boundary every walk over
@@ -175,7 +176,7 @@ export function hashesOf(doc) {
175
176
  * An OpenCode manifest's `skill_denies` — the `permission.skill` denies Geneseed itself added
176
177
  * (`opencodeLayer` records them; a deny the user wrote, even on a Geneseed skill, is never in
177
178
  * it) — or `[]` when the manifest, or the key, is absent or malformed, which sweeps nothing.
178
- * Unlike the Law IV `permission.bash` gates (permanent, never taken back — see
179
+ * Unlike the `permission.bash` gates (left in place at uninstall, which fails closed — see
179
180
  * `reconcileOpencodePermission`), a skill-visibility deny is reversible: once uninstalled there
180
181
  * is no skill left to hide, and the name is the user's to reuse. One home because rebuild's
181
182
  * deny sweep and uninstall must agree on what Geneseed owns.
@@ -199,6 +200,17 @@ export function recordedEdit(doc) {
199
200
  };
200
201
  }
201
202
 
203
+ /**
204
+ * An OpenCode manifest's `bash_gates` — the `permission.bash` keys Geneseed itself added, which
205
+ * a later build may take back once their rule is off (`reconcileOpencodePermission`). Absent or
206
+ * malformed reads as nothing owned, like `recordedDenies`: a manifest from before 5.2.0 has no
207
+ * such key, so its gates stay until `--prune-gates` or a hand edit.
208
+ */
209
+ export function recordedGates(doc) {
210
+ const g = doc && doc.bash_gates;
211
+ return Array.isArray(g) ? g.filter((k) => typeof k === 'string') : [];
212
+ }
213
+
202
214
  /** The manifest keys for an edit record; none when Geneseed owns nothing there. */
203
215
  export function editRecordKeys(rec) {
204
216
  return rec.asks.length ? { edit_asks: rec.asks, ...(rec.shorthand ? { edit_shorthand: rec.shorthand } : {}) } : {};
@@ -218,3 +230,45 @@ export function ownedState(root, rel, hashes) {
218
230
  if (!isFile(p)) return 'missing';
219
231
  return fileHash(p) === expected ? 'unmodified' : 'modified';
220
232
  }
233
+
234
+ /**
235
+ * THE BUNDLE'S OWN FILE LIST, and why it exists. A bundle is rendered straight into `out`, and
236
+ * for the OpenCode project emit `out` is the user's repository root, where `agents/`, `skills/`
237
+ * and `laws/` are ordinary names for the user's own folders. The build used to decide ownership
238
+ * by DIRECTORY: the first render merged into such a folder and overwrote any file of the same
239
+ * name, and wrote the markers; from the second render on, those markers made it delete the
240
+ * folders whole before writing, and uninstall deleted them whole too. A user's
241
+ * `agents/support_bot.py` did not survive two emits, or one emit and an uninstall.
242
+ *
243
+ * Ownership is now per FILE, claim-on-create, the rule `claimer` (`js/hosts/native.mjs`) holds
244
+ * for a host's config dir: a file this build finds at its destination and did not write before
245
+ * is the user's and is kept; a recorded file this build no longer ships is removed; nothing
246
+ * else under `out` is touched. `bundleFiles` is the reader, here rather than in
247
+ * `js/build/bundle.mjs` because the uninstall shares it and imports nothing from the generator.
248
+ * The list rides in the bundle's `.geneseed-srcdirs.json` marker, which the build already wrote.
249
+ *
250
+ * null when the marker carries no list: a bundle an older build rendered. `build` then
251
+ * overwrites what it ships, as that build did, and removes nothing, and its own marker starts
252
+ * the record.
253
+ */
254
+ export const SRC_DIRS_MARKER = '.geneseed-srcdirs.json';
255
+ export const BUNDLE_FILES_KEY = 'files';
256
+ export function bundleFiles(out) {
257
+ let data;
258
+ try { data = parseJson(readFileSync(path.join(out, SRC_DIRS_MARKER), 'utf8')); } catch { return null; }
259
+ const files = isDict(data) ? data[BUNDLE_FILES_KEY] : null;
260
+ return Array.isArray(files) ? files.filter((f) => typeof f === 'string') : null;
261
+ }
262
+
263
+ /**
264
+ * What the last build left in a bundle that is not Geneseed's copy: `kept`, the files that are
265
+ * the user's at a path the bundle ships, and `stale`, the retired skills an older build left
266
+ * behind. Each only while the file still exists. `--force` on the next build clears both.
267
+ */
268
+ export function bundleLeftovers(out) {
269
+ let data;
270
+ try { data = parseJson(readFileSync(path.join(out, SRC_DIRS_MARKER), 'utf8')); } catch { data = null; }
271
+ const list = (key) => (isDict(data) && Array.isArray(data[key]) ? data[key] : [])
272
+ .filter((r) => typeof r === 'string' && isFile(path.join(out, r)));
273
+ return { kept: ownedWithin(out, list('kept')), stale: ownedWithin(out, list('stale')) };
274
+ }
@@ -22,6 +22,7 @@
22
22
  import { appendFileSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
23
23
  import os from 'node:os';
24
24
  import path from 'node:path';
25
+ import { withoutBlocks } from '../lib/managed-block.mjs';
25
26
  import { normcase } from '../lib/paths.mjs';
26
27
  import { gitRootOf, mainWorktreeOf } from './gitref.mjs';
27
28
 
@@ -30,10 +31,9 @@ const MANIFESTS = new Set(['package.json', 'pom.xml', 'pyproject.toml', 'go.mod'
30
31
  'composer.json', 'Gemfile']);
31
32
  const isManifest = (n) => MANIFESTS.has(n) || n.startsWith('build.gradle') || n.endsWith('.csproj');
32
33
 
33
- // `managedBlockWrite`'s delimiters (js/hosts/settings.mjs `delimiters('GENESEED')`). On a Bob
34
- // project install the block holds the whole carrier, `#### Ownership` included — hence the strip
35
- // and the exact `##` heading match. `\r?`: a CRLF file's `$` sits after the `\r`.
36
- const MANAGED_BLOCK_RE = /<!-- BEGIN GENESEED -->[\s\S]*?<!-- END GENESEED -->/g;
34
+ // On a Bob project install the managed block holds the whole carrier, `#### Ownership` included —
35
+ // hence the strip (`withoutBlocks`) and the exact `##` heading match. `\r?`: a CRLF file's `$`
36
+ // sits after the `\r`.
37
37
  const SECTION_RE = /^## Ownership[ \t]*\r?$/m;
38
38
 
39
39
  // Write-shaped tool names (Bob's `tool-gate` also routes reads here: `read_file` carries a path).
@@ -97,7 +97,7 @@ function declinedSince(root) {
97
97
  function ownAgentsText(root) {
98
98
  let text = null;
99
99
  try { text = readFileSync(path.join(root, 'AGENTS.md'), 'utf8'); } catch { /* none */ }
100
- return text === null ? '' : text.replace(MANAGED_BLOCK_RE, '');
100
+ return text === null ? '' : withoutBlocks(text);
101
101
  }
102
102
 
103
103
  /**