Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(hosts): graft uninstall, and init retracts the agents it isn't writing (#247)
anirudhkumar-nanonets48304ea97599
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 141a7165..6a556daf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,41 @@### Added+- **`graft init` converges instead of accumulating, and `graft uninstall` removes+ graft entirely.** `init` wrote the files the selected agents needed and never+ looked at the rest, so a repo wired by an older version — or by the same version+ with different `--agents` — kept that run's files forever, and the session-start+ refresh then kept them *up to date*. `init` now retracts every agent it isn't+ about to write, and `graft uninstall` retracts the lot.++ Only graft's own contribution is touched: inside a shared file just the+ marker-fenced block, inside a config just the `graft` key — foreign MCP servers,+ hooks, statuslines and ignore entries survive byte for byte. A file left holding+ nothing is deleted rather than truncated to an empty shell, and the directories+ that empties are pruned. An unparseable config is reported and left alone.+ `uninstall` is dry-run until `-y`.++ The target list is derived from the same registries `init` writes through, so a+ host added later is retractable for free; only a host *removed* from the registry+ needs a hand-written entry, and `LEGACY_TARGETS` says so. Exclusion is by path as+ well as by host id: three hosts write `AGENTS.md`, and keeping any one of them has+ to spare that block.++### Fixed++- **A stale `[mcp_servers.graft]` is now replaced instead of skipped.** The TOML+ writer returned early the moment the header existed, which froze the launch+ command at whatever the first `init` wrote — a repo wired when graft wasn't on+ `PATH` kept the slow `npx` form forever, and no upgrade could correct it. Codex+ and Grok both went through that path. Foreign tables are untouched either way.++- **`.claude/settings.json` no longer accumulates graft's own entries.** The+ allowlist and `footerLinksRegexes` were append-only, so a renamed invocation form+ stayed in the user's settings beside its replacement with nothing able to remove+ it. Both now drop graft's prior entries before adding the current set, the same+ way the hooks merge already did. Scoped to the forms graft is actually invoked as,+ so a hand-written `Bash(graft-mytool:*)` survives.+- **`graft blast` suggests who to tag.** The comment already named the areas adiff changes and the areas it can affect; it now names the people behind them,read from git history with no API call and no config file. One `git log` perdiff --git a/README.md b/README.mdindex 3d60265e..2242cf79 100644--- a/README.md+++ b/README.md@@ -382,6 +382,11 @@ graft init --no-build # wire the files only; don't build the grapgraft init --all-agents # wire every known agent, detected or notgraft init --list-agents # list known agent ids and exit+graft uninstall [dir] # remove every file and config entry graft wrote here (the inverse of init)+graft uninstall -y # actually remove (without -y it prints what it would remove and exits)+graft uninstall --keep-cache # wiring only; leave graft/ and the .gitignore entry+graft uninstall --no-global # leave out-of-repo files alone (~/.codex, ~/.gemini)+graft version # print the installed + latest published npm versiongraft upgrade # npm install -g the latest published version# a new version is announced automatically (checked once a day);diff --git a/src/claude/settings-merge.ts b/src/claude/settings-merge.tsindex 66f53bdc..36685a8a 100644--- a/src/claude/settings-merge.ts+++ b/src/claude/settings-merge.ts@@ -43,6 +43,23 @@ function isGraftHookEntry(entry: Json): boolean {return JSON.stringify(entry ?? '').includes('graft-hooks.cjs');}+/**+ * Is this allowlist entry one graft wrote?+ *+ * Scoped to the forms graft is actually invoked as — NOT any rule mentioning+ * "graft". A user who allowlists their own `Bash(graft-mytool:*)` keeps it; only+ * graft's own set is replaced, which is what lets a renamed entry disappear on+ * upgrade instead of accumulating beside its replacement.+ */+export function isGraftAllowEntry(entry: unknown): boolean {+ return /^Bash\((?:graft|npx graft|graft-dev|node dist\/cli\.js)(?::|\))/.test(String(entry));+}++/** Is this footer regex graft's? It points at the card tree, which is graft's alone. */+export function isGraftFooterRegex(re: unknown): boolean {+ return String(re).includes('graft/');+}+export function mergeGraftSettings(existing: Json): { merged: Json; warnings: string[] } {const merged: Json = { ...(existing ?? {}) };const warnings: string[] = [];@@ -62,18 +79,19 @@ export function mergeGraftSettings(existing: Json): { merged: Json; warnings: stmerged.hooks[event] = [...foreign, ...blocks];}- const footer = Array.isArray(merged.footerLinksRegexes) ? [...merged.footerLinksRegexes] : [];- if (!footer.includes(FOOTER)) footer.push(FOOTER);- merged.footerLinksRegexes = footer;+ // Drop graft's own prior regex before re-adding, so a change to FOOTER replaces+ // the old pattern instead of stacking beside it. The user's regexes are kept.+ const priorFooter = Array.isArray(merged.footerLinksRegexes) ? merged.footerLinksRegexes : [];+ merged.footerLinksRegexes = [...priorFooter.filter((r: unknown) => !isGraftFooterRegex(r)), FOOTER];// headless/subagent runs hard-deny Bash by default; without an allowlist entry// `graft ask`'s own Bash calls (and the skill it installs) can't run out-of-box.+ // Same shape as the hooks merge above: drop graft's prior entries, then add the+ // current set. Append-only left a renamed invocation form in the user's settings+ // forever, with nothing able to remove it.merged.permissions = { ...(merged.permissions ?? {}) };- const allow = Array.isArray(merged.permissions.allow) ? [...merged.permissions.allow] : [];- for (const entry of ALLOW_ENTRIES) {- if (!allow.includes(entry)) allow.push(entry);- }- merged.permissions.allow = allow;+ const priorAllow = Array.isArray(merged.permissions.allow) ? merged.permissions.allow : [];+ merged.permissions.allow = [...priorAllow.filter((e: unknown) => !isGraftAllowEntry(e)), ...ALLOW_ENTRIES];return { merged, warnings };}diff --git a/src/cli.ts b/src/cli.tsindex 27f925c1..3f0e8f03 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -33,6 +33,7 @@ import {} from "./graph/workspace-cli.js";import { formatInitEpilogue } from "./cli-epilogue.js";import { planInit, selectedWrites } from "./hosts/plan.js";+import { planRetract, runRetract, changed, type Retraction } from "./hosts/retract.js";import { formatNonInteractiveHelp, formatPlan, runPicker } from "./cli-picker.js";import { homedir } from "node:os";import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, runUpgrade } from "./cli-meta.js";@@ -973,6 +974,17 @@ function wireTarget(): void {const { home, cliPath, plan, wantClaude, opts } = ctx;+ // Converge, don't just add. init writes the selected hosts; without this it+ // never touches the rest, so a repo wired by an older version (or by the same+ // version with different --agents) keeps that run's files forever — and+ // `reconcileWiring` then keeps them *up to date*, which is worse than stale.+ // Retract every host NOT being written now; `exclude` spares the ones about to+ // be rewritten, and the graph cache is kept (init is one step from using it).+ const retracted = changed(+ runRetract(repo, { home, apply: true, global: opts.global, cache: false, exclude: ids }),+ ).filter((r) => r.action !== "skipped-unparseable");+ for (const r of retracted) console.error(`- removed ${r.path} (${r.what}) — agent not selected`);+if (wantClaude) {const res = runInit(repo, { build: opts.build, cliPath });console.error(`✓ wrote ${res.settingsPath}`);@@ -1030,6 +1042,69 @@ function wireTarget(}+/** Group a retraction report by host, so the output reads as "what leaves each agent". */+function formatRetractions(rs: Retraction[], apply: boolean): string {+ const hit = changed(rs);+ if (hit.length === 0) return "· nothing to remove — no graft wiring found here";+ const verb = apply ? "removed" : "would remove";+ const lines: string[] = [];+ const byHost = new Map<string, Retraction[]>();+ for (const r of hit) {+ const k = byHost.get(r.hostId) ?? [];+ k.push(r);+ byHost.set(r.hostId, k);+ }+ for (const [host, items] of byHost) {+ lines.push(`\n${host}:`);+ for (const r of items) {+ const mark =+ r.action === "skipped-unparseable"+ ? "⚠"+ : r.action === "deleted"+ ? "-"+ : "~";+ const note =+ r.action === "skipped-unparseable"+ ? " — not valid JSON, left untouched (remove the graft entry by hand)"+ : r.action === "deleted"+ ? ` (${r.what} — deleted)`+ : ` (${r.what})`;+ const scope = r.scope === "global" ? " [machine-wide]" : "";+ lines.push(` ${mark} ${verb}: ${r.path}${scope}${note}`);+ }+ }+ return lines.join("\n").replace(/^\n/, "");+}++program+ .command("uninstall")+ .description("Remove every file and config entry graft has written to this repo (the inverse of init)")+ .argument("[dir]", "target repo directory", ".")+ .option("-y, --yes", "actually remove (without this, prints what it would remove and exits)")+ .option("--keep-cache", "keep graft/ and the .gitignore entries — wiring only")+ .option("--no-global", "leave out-of-repo files alone (~/.codex, ~/.gemini)")+ .action((dir: string, opts: { yes?: boolean; keepCache?: boolean; global?: boolean }) => {+ const repo = resolve(dir);+ const home = homedir();+ const common = { home, global: opts.global, cache: opts.keepCache ? false : true };++ if (!opts.yes) {+ console.error(formatRetractions(planRetract(repo, common), false));+ console.error("\nDry run — nothing was touched. Re-run with -y to remove.");+ if (opts.global !== false)+ console.error("Entries marked [machine-wide] affect every project; --no-global skips them.");+ return;+ }+ const done = runRetract(repo, { ...common, apply: true });+ console.error(formatRetractions(done, true));+ const bad = changed(done).filter((r) => r.action === "skipped-unparseable");+ console.error(+ bad.length+ ? `\n⚠ ${bad.length} file(s) could not be parsed and were left as-is — see above.`+ : "\n✓ graft fully removed. `graft init` re-wires from scratch.",+ );+ });+program.parseAsync().catch((err) => {console.error(err instanceof Error ? err.message : err);process.exit(1);diff --git a/src/hosts/mcp-config.ts b/src/hosts/mcp-config.tsindex 878ce0c8..cabe60ed 100644--- a/src/hosts/mcp-config.ts+++ b/src/hosts/mcp-config.ts@@ -99,19 +99,62 @@ export function mergeJsonKey(id: string, path: string, topKey: string, entry: obreturn { id, path, action };}+/** The `[mcp_servers.graft]` table header, as written and as matched. */+const TOML_HEADER = '[mcp_servers.graft]';++/**+ * Remove the `[mcp_servers.graft]` table from a TOML config, returning the rest.+ *+ * Line-based on purpose: a real parse-and-reserialize would reformat the user's+ * whole file. The table runs from its header to the next `[`-header or EOF, which+ * is exactly the shape {@link upsertCodexToml} appends. Exported so the writer and+ * `retract.ts` can never disagree about what "graft's section" means.+ */+export function stripTomlSection(text: string): { rest: string; found: boolean } {+ const lines = text.split('\n');+ const start = lines.findIndex((l) => l.trim() === TOML_HEADER);+ if (start === -1) return { rest: text, found: false };+ let end = start + 1;+ while (end < lines.length && !lines[end].trimStart().startsWith('[')) end++;+ const rest = [...lines.slice(0, start), ...lines.slice(end)]+ .join('\n')+ .replace(/\n{3,}/g, '\n\n')+ .replace(/^\n+/, '');+ return { rest, found: true };+}++/**+ * Register graft in a TOML config, replacing any section a previous version left.+ *+ * The old behaviour was to skip entirely once the header existed, which froze the+ * launch command at whatever the first init wrote: a repo wired when graft wasn't+ * on PATH kept the slow `npx` form forever, and no upgrade could correct it. Strip+ * and re-append instead, so this converges like every other writer — foreign+ * tables are untouched either way.+ */function upsertCodexToml(id: string, path: string): McpWrite {const existed = existsSync(path);const text = existed ? readFileSync(path, 'utf8') : '';- if (/^\[mcp_servers\.graft\]$/m.test(text)) return { id, path, action: 'unchanged' };const { command, args } = serverEntry();const argList = args.map((a) => JSON.stringify(a)).join(", ");- const section = `[mcp_servers.graft]\ncommand = \"${command}\"\nargs = [${argList}]\n`;- const sep = text.length === 0 ? '' : text.endsWith('\n') ? '\n' : '\n\n';+ const section = `${TOML_HEADER}\ncommand = \"${command}\"\nargs = [${argList}]\n`;++ const { rest, found } = stripTomlSection(text);+ // Byte-identical already: don't rewrite the file just to reorder it.+ if (found && text === appendSection(rest, section)) return { id, path, action: 'unchanged' };+mkdirSync(dirname(path), { recursive: true });- writeFileSync(path, `${text}${sep}${section}`);+ writeFileSync(path, appendSection(rest, section));return { id, path, action: existed ? 'updated' : 'created' };}+/** Append a section after exactly one blank line, or at the top of an empty file. */+function appendSection(text: string, section: string): string {+ if (text.trim() === '') return section;+ const sep = text.endsWith('\n\n') ? '' : text.endsWith('\n') ? '\n' : '\n\n';+ return `${text}${sep}${section}`;+}+function jsonTarget(hostId: string,id: string,diff --git a/src/hosts/retract.ts b/src/hosts/retract.tsnew file mode 100644index 00000000..b8fddbd3--- /dev/null+++ b/src/hosts/retract.ts@@ -0,0 +1,478 @@+/**+ * Retraction: undo every edit graft has ever made to a repo.+ *+ * `init` is additive — it writes the files the *currently selected* hosts need+ * and never looks at the rest. So a repo wired by an older version (or by the+ * same version with different `--agents`) keeps the files that run produced,+ * and the two sets accumulate. Retraction is the missing half: it walks every+ * target graft could ever have written and removes graft's contribution, so+ * `retract` + `init` converges the repo on exactly this version's intent.+ *+ * The target list is derived from the same registries `init` writes through+ * (`HOSTS`, `mcpTargets`, `hookTargets`, `claudeTargets`), so a host added+ * later is retractable for free — there is no second list to keep in sync.+ * Only {@link LEGACY_TARGETS} is hand-maintained, and only for paths that have+ * been *removed* from those registries: once a host is gone, nothing else+ * remembers the file it used to write.+ *+ * Two invariants, both load-bearing:+ * 1. Never delete what graft did not write. Inside a file the user owns, only+ * the marker-fenced region and graft-named keys are touched; foreign MCP+ * servers, hooks, and settings are preserved byte for byte.+ * 2. Never leave an empty shell. A file that held nothing but graft's+ * contribution is deleted, not truncated to `{}` or a blank document —+ * an orphan file is the very residue this exists to remove.+ */+import { readFileSync, writeFileSync, existsSync, rmSync, rmdirSync, statSync, readdirSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { homedir } from 'node:os';+import { HOSTS } from './registry.js';+import { START, END } from './sections.js';+import { mcpTargets, stripTomlSection } from './mcp-config.js';+import { hookTargets } from './codex-hooks.js';+import { antigravitySkillTargets } from './antigravity.js';+import { claudeTargets } from '../claude/init.js';+import { isGraftAllowEntry, isGraftFooterRegex } from '../claude/settings-merge.js';+import type { WriteScope } from './plan.js';++/** What a retraction did to one target. */+export type RetractAction =+ /** graft's contribution was there and is now gone. */+ | 'removed'+ /** the whole file was graft's, so the file itself is gone. */+ | 'deleted'+ /** nothing of graft's here. */+ | 'absent'+ /** file exists but can't be parsed — left untouched rather than risk it. */+ | 'skipped-unparseable';++export interface Retraction {+ /** The host this target belongs to, for grouping the report. */+ hostId: string;+ path: string;+ /** Short human label for what was removed from that file. */+ what: string;+ scope: WriteScope;+ action: RetractAction;+}++export interface RetractOpts {+ home?: string;+ /** false → report only, touch nothing. Defaults to false: a destructive+ * operation must be asked for, never assumed. */+ apply?: boolean;+ /** false → skip targets outside the repo (the ~/.codex and ~/.gemini writes). */+ global?: boolean;+ /** false → keep `graft/` and the ignore entries. `init` sets this: the cache is+ * regenerable but re-parsing a large repo costs minutes, and init is about to+ * use it. */+ cache?: boolean;+ /** Host ids about to be re-written, so their targets are left alone. `init`+ * passes its selection: retracting a file it is one step from rewriting is+ * pure churn (and would report every write as `created`). */+ exclude?: string[];+}++/**+ * Paths that older versions wrote and the live registries no longer mention.+ * Empty today — every host in `HOSTS` since the multi-host layer landed is+ * still there, and the marker string and the `graft` name have never changed,+ * so the derived list covers every version to date.+ *+ * This is where a *removed* host's file goes. Deleting an entry from `HOSTS`+ * without adding it here is what strands a file in every existing repo.+ */+const LEGACY_TARGETS: { relPath: string; kind: 'owned' | 'section'; what: string }[] = [];++// ---------------------------------------------------------------------------+// primitive operations+// ---------------------------------------------------------------------------++/** True when a file has no non-whitespace content left. */+function isBlank(text: string): boolean {+ return text.trim() === '';+}++function removeFile(path: string, apply: boolean): RetractAction {+ if (!existsSync(path)) return 'absent';+ if (apply) {+ rmSync(path, { force: true });+ pruneEmptyDirs(dirname(path));+ }+ return 'deleted';+}++/**+ * Walk up from a just-emptied directory removing empty ancestors, so retracting+ * `.claude/skills/graft/SKILL.md` doesn't leave a hollow `skills/graft/` behind.+ * Stops at the first non-empty directory — never climbs out of the repo, because+ * any ancestor that far up has other content in it.+ */+function pruneEmptyDirs(dir: string): void {+ for (let d = dir, i = 0; i < 6; i++) {+ try {+ if (readdirSync(d).length > 0) return;+ rmdirSync(d); // throws on a non-empty dir — exactly the guard we want+ } catch {+ return; // not a dir, not empty, or not ours to remove+ }+ const parent = dirname(d);+ if (parent === d) return;+ d = parent;+ }+}++/**+ * Strip the marker-fenced graft block from a file the user owns.+ *+ * Paragraph spacing around the removed block is collapsed back to a single+ * blank line, so a file that had prose either side of the block reads exactly+ * as it did before graft appended to it.+ */+function stripSection(path: string, apply: boolean): RetractAction {+ if (!existsSync(path)) return 'absent';+ const text = readFileSync(path, 'utf8');+ if (!text.includes(START)) return 'absent';+ const eol = text.includes('\r\n') ? '\r\n' : '\n';+ const lines = text.split(/\r\n|\n/);+ const out: string[] = [];+ let inside = false;+ let found = false;+ for (const line of lines) {+ const t = line.trim();+ if (!inside && t === START) { inside = true; found = true; continue; }+ if (inside) { if (t === END) inside = false; continue; }+ out.push(line);+ }+ if (!found) return 'absent';+ // Collapse the run of blank lines the block left behind, and trim the edges.+ const collapsed = out+ .join('\n')+ .replace(/\n{3,}/g, '\n\n')+ .replace(/^\n+/, '')+ .replace(/\n+$/, '\n');+ if (!apply) return isBlank(collapsed) ? 'deleted' : 'removed';+ if (isBlank(collapsed)) return removeFile(path, true);+ writeFileSync(path, eol === '\n' ? collapsed : collapsed.replace(/\n/g, '\r\n'));+ return 'removed';+}++/**+ * Delete `<topKey>.graft` from a JSON config, preserving every other server.+ * An unparseable file is reported and left alone — the user may have comments or+ * a half-finished edit in there, and rewriting it would lose more than it fixes.+ */+function removeJsonKey(path: string, topKey: string, apply: boolean): RetractAction {+ if (!existsSync(path)) return 'absent';+ let root: Record<string, unknown>;+ try {+ root = JSON.parse(readFileSync(path, 'utf8'));+ } catch {+ return 'skipped-unparseable';+ }+ if (typeof root !== 'object' || root === null || Array.isArray(root)) return 'skipped-unparseable';+ const bucket = root[topKey];+ if (typeof bucket !== 'object' || bucket === null || Array.isArray(bucket)) return 'absent';+ const map = bucket as Record<string, unknown>;+ if (!('graft' in map)) return 'absent';+ if (!apply) {+ return Object.keys(map).length === 1 && Object.keys(root).length === 1 ? 'deleted' : 'removed';+ }+ delete map.graft;+ if (Object.keys(map).length === 0) delete root[topKey];+ if (Object.keys(root).length === 0) return removeFile(path, true);+ writeFileSync(path, `${JSON.stringify(root, null, 2)}\n`);+ return 'removed';+}++/**+ * Delete the `[mcp_servers.graft]` table from a TOML config.+ *+ * Line-based on purpose: a real TOML parse-and-reserialize would reformat the+ * user's whole file. The table runs from its header to the next `[`-header or+ * EOF, which is exactly what `upsertCodexToml` appends.+ */+function removeTomlSection(path: string, apply: boolean): RetractAction {+ if (!existsSync(path)) return 'absent';+ const { rest: kept, found } = stripTomlSection(readFileSync(path, 'utf8'));+ if (!found) return 'absent';+ if (!apply) return isBlank(kept) ? 'deleted' : 'removed';+ if (isBlank(kept)) return removeFile(path, true);+ writeFileSync(path, kept.endsWith('\n') ? kept : `${kept}\n`);+ return 'removed';+}++/**+ * Remove graft's fragments from `.claude/settings.json`, keeping the user's.+ *+ * The statusline check is by *shim path*, not exact string equality: an older+ * version's command differed in shape, and `mergeGraftSettings` would read that+ * as a hand-written statusline and refuse to touch it forever. Matching the+ * helper path recognizes graft's own output across every version that wrote it.+ */+function stripClaudeSettings(path: string, apply: boolean): RetractAction {+ if (!existsSync(path)) return 'absent';+ let root: Record<string, any>;+ try {+ root = JSON.parse(readFileSync(path, 'utf8'));+ } catch {+ return 'skipped-unparseable';+ }+ if (typeof root !== 'object' || root === null || Array.isArray(root)) return 'skipped-unparseable';+ const before = JSON.stringify(root);+ const isGraftCmd = (v: unknown) => JSON.stringify(v ?? '').includes('graft-statusline.cjs');++ for (const key of ['statusLine', 'subagentStatusLine']) {+ if (root[key] !== undefined && isGraftCmd(root[key])) delete root[key];+ }++ if (root.hooks && typeof root.hooks === 'object' && !Array.isArray(root.hooks)) {+ for (const event of Object.keys(root.hooks)) {+ const prior = root.hooks[event];+ if (!Array.isArray(prior)) continue;+ const kept = prior.filter((e: unknown) => !JSON.stringify(e ?? '').includes('graft-hooks.cjs'));+ if (kept.length === 0) delete root.hooks[event];+ else root.hooks[event] = kept;+ }+ if (Object.keys(root.hooks).length === 0) delete root.hooks;+ }++ if (Array.isArray(root.footerLinksRegexes)) {+ const kept = root.footerLinksRegexes.filter((r: unknown) => !isGraftFooterRegex(r));+ if (kept.length === 0) delete root.footerLinksRegexes;+ else root.footerLinksRegexes = kept;+ }++ if (root.permissions && Array.isArray(root.permissions.allow)) {+ const kept = root.permissions.allow.filter((a: unknown) => !isGraftAllowEntry(a));+ if (kept.length === 0) delete root.permissions.allow;+ else root.permissions.allow = kept;+ if (Object.keys(root.permissions).length === 0) delete root.permissions;+ }++ const after = JSON.stringify(root);+ if (after === before) return 'absent';+ if (!apply) return Object.keys(root).length === 0 ? 'deleted' : 'removed';+ if (Object.keys(root).length === 0) return removeFile(path, true);+ writeFileSync(path, `${JSON.stringify(root, null, 2)}\n`);+ return 'removed';+}++/** Remove graft's PostToolUse/SessionStart/etc. entries from Codex's hooks.json. */+function stripCodexHooks(path: string, apply: boolean): RetractAction {+ if (!existsSync(path)) return 'absent';+ let root: Record<string, any>;+ try {+ root = JSON.parse(readFileSync(path, 'utf8'));+ } catch {+ return 'skipped-unparseable';+ }+ if (typeof root !== 'object' || root === null || Array.isArray(root)) return 'skipped-unparseable';+ if (!root.hooks || typeof root.hooks !== 'object' || Array.isArray(root.hooks)) return 'absent';+ const before = JSON.stringify(root);+ for (const event of Object.keys(root.hooks)) {+ const prior = root.hooks[event];+ if (!Array.isArray(prior)) continue;+ const kept = prior.filter((e: unknown) => !JSON.stringify(e ?? '').includes('graft-hooks.cjs'));+ if (kept.length === 0) delete root.hooks[event];+ else root.hooks[event] = kept;+ }+ if (Object.keys(root.hooks).length === 0) delete root.hooks;+ if (JSON.stringify(root) === before) return 'absent';+ if (!apply) return Object.keys(root).length === 0 ? 'deleted' : 'removed';+ if (Object.keys(root).length === 0) return removeFile(path, true);+ writeFileSync(path, `${JSON.stringify(root, null, 2)}\n`);+ return 'removed';+}++/**+ * Drop graft's block from `.gitignore` / `.ignore`.+ *+ * Both are written as a comment line plus entries; the comment is graft's own+ * wording, so it identifies the block. Entries are matched individually too, so+ * a hand-tidied file (comment deleted, entry kept) still retracts cleanly.+ */+function stripIgnoreEntries(path: string, entries: RegExp[], apply: boolean): RetractAction {+ if (!existsSync(path)) return 'absent';+ const text = readFileSync(path, 'utf8');+ const kept = text+ .split('\n')+ .filter((l) => {+ const t = l.trim();+ if (t.startsWith('#') && t.includes('graft')) return false;+ return !entries.some((re) => re.test(t));+ })+ .join('\n')+ .replace(/\n{3,}/g, '\n\n')+ .replace(/^\n+/, '')+ .replace(/\n+$/, '\n');+ if (kept === text) return 'absent';+ if (!apply) return isBlank(kept) ? 'deleted' : 'removed';+ if (isBlank(kept)) return removeFile(path, true);+ writeFileSync(path, kept.endsWith('\n') ? kept : `${kept}\n`);+ return 'removed';+}++function removeDir(path: string, apply: boolean): RetractAction {+ try {+ if (!statSync(path).isDirectory()) return 'absent';+ } catch {+ return 'absent';+ }+ if (apply) {+ rmSync(path, { recursive: true, force: true });+ pruneEmptyDirs(dirname(path));+ }+ return 'deleted';+}++// ---------------------------------------------------------------------------+// the target list+// ---------------------------------------------------------------------------++type Op = (apply: boolean) => RetractAction;+interface Target extends Omit<Retraction, 'action'> {+ run: Op;+}++/**+ * Every target graft could have written, in removal order.+ *+ * Derived from the live registries, NOT hand-listed: `HOSTS` gives the+ * instruction files, `mcpTargets` over *all* host ids gives the MCP configs+ * (with the format and top-level key each one needs), and `claudeTargets`+ * gives the Claude Code layer. That's what keeps this complete as hosts are+ * added — see the module note.+ */+function targets(repo: string, opts: RetractOpts): Target[] {+ const home = opts.home ?? homedir();+ const exclude = new Set(opts.exclude ?? []);+ const out: Target[] = [];++ /**+ * Paths a *kept* host also writes, which must survive even though some other,+ * unselected host names them too.+ *+ * Three hosts share `AGENTS.md` (agents, hermes, antigravity). Excluding by host+ * id alone would strip that shared block on behalf of a host nobody selected,+ * and the only reason the end state came out right was that `init` happened to+ * rewrite it immediately afterwards. Exclude by path as well, so retraction+ * never depends on what runs next.+ */+ const keptPaths = new Set<string>();+ for (const host of HOSTS) {+ if (exclude.has(host.id)) keptPaths.add(join(repo, host.relPath));+ }+ for (const t of mcpTargets(repo, [...exclude], { home })) keptPaths.add(t.path);+ if (exclude.has('claude')) for (const t of claudeTargets(repo)) keptPaths.add(t.path);+ if (exclude.has('agents')) for (const t of hookTargets(home)) keptPaths.add(t.path);+ if (exclude.has('antigravity')) for (const t of antigravitySkillTargets(home)) keptPaths.add(t.path);++ /** Queue a target unless a kept host owns that path, or it's already queued. */+ const seen = new Set<string>();+ const add = (t: Target): void => {+ if (keptPaths.has(t.path) || seen.has(t.path)) return;+ seen.add(t.path);+ out.push(t);+ };++ // 1. Instruction files, one per host. Owned files go wholesale; shared files+ // lose only their fenced block.+ for (const host of HOSTS) {+ if (exclude.has(host.id)) continue;+ const path = join(repo, host.relPath);+ add(+ host.kind === 'owned'+ ? { hostId: host.id, path, what: 'graft-owned instruction file', scope: 'repo', run: (a) => removeFile(path, a) }+ : { hostId: host.id, path, what: 'fenced graft section', scope: 'repo', run: (a) => stripSection(path, a) },+ );+ }++ // 1b. Instruction files from hosts that no longer exist in the registry.+ for (const legacy of LEGACY_TARGETS) {+ const path = join(repo, legacy.relPath);+ add({+ hostId: 'legacy', path, what: legacy.what, scope: 'repo',+ run: (a) => (legacy.kind === 'owned' ? removeFile(path, a) : stripSection(path, a)),+ });+ }++ // 2. MCP registrations. Asking for every host id at once yields the union of+ // config files, each already carrying its format and top-level key.+ const allIds = HOSTS.map((h) => h.id).filter((id) => !exclude.has(id));+ for (const t of mcpTargets(repo, allIds, { home })) {+ if (opts.global === false && t.scope === 'global') continue;+ add({+ hostId: t.hostId, path: t.path, what: t.what, scope: t.scope,+ run: (a) => (t.format === 'toml' ? removeTomlSection(t.path, a) : removeJsonKey(t.path, t.topKey!, a)),+ });+ }++ // 3. Claude Code: settings fragments, both shims, the skill, and the .mcp.json key.+ if (!exclude.has('claude')) {+ const [settings, statusline, hooks, skill, mcp] = claudeTargets(repo).map((t) => t.path);+ for (const t of [+ { hostId: 'claude', path: settings, what: 'statusline + hooks + allowlist + footer regex', scope: 'repo', run: (a) => stripClaudeSettings(settings, a) },+ { hostId: 'claude', path: statusline, what: 'statusline shim', scope: 'repo', run: (a) => removeFile(statusline, a) },+ { hostId: 'claude', path: hooks, what: 'hooks shim', scope: 'repo', run: (a) => removeFile(hooks, a) },+ { hostId: 'claude', path: skill, what: 'graft skill', scope: 'repo', run: (a) => removeFile(skill, a) },+ { hostId: 'claude', path: mcp, what: 'mcpServers.graft', scope: 'repo', run: (a) => removeJsonKey(mcp, 'mcpServers', a) },+ ] as Target[]) add(t);+ }++ // 4. Global: Codex's hook shim + entries, and Antigravity's shared skill.+ if (opts.global !== false) {+ if (!exclude.has('agents')) {+ for (const t of hookTargets(home)) {+ add({+ hostId: t.hostId, path: t.path, what: t.what, scope: 'global',+ run: (a) => (t.path.endsWith('.json') ? stripCodexHooks(t.path, a) : removeFile(t.path, a)),+ });+ }+ }+ if (!exclude.has('antigravity')) {+ for (const t of antigravitySkillTargets(home)) {+ add({ hostId: t.hostId, path: t.path, what: t.what, scope: 'global', run: (a) => removeFile(t.path, a) });+ }+ }+ }++ // 5. The graph cache and the ignore entries that admit it. Last, so a failure+ // here can't strand the wiring half-retracted.+ if (opts.cache !== false) {+ const cache = join(repo, 'graft');+ const gitignore = join(repo, '.gitignore');+ const ignore = join(repo, '.ignore');+ for (const t of [+ { hostId: 'graph', path: cache, what: 'local graph cache', scope: 'repo', run: (a) => removeDir(cache, a) },+ { hostId: 'graph', path: gitignore, what: 'graft/ ignore entry', scope: 'repo', run: (a) => stripIgnoreEntries(gitignore, [/^\/?graft\/?$/], a) },+ { hostId: 'graph', path: ignore, what: 'graft/ search re-admit entries', scope: 'repo', run: (a) => stripIgnoreEntries(ignore, [/^!?graft\/?$/, /^graft\/\.(cache|graph)\/?$/], a) },+ ] as Target[]) add(t);+ }++ return out;+}++// ---------------------------------------------------------------------------+// public API+// ---------------------------------------------------------------------------++/** What a retraction *would* remove. Pure — touches nothing. */+export function planRetract(repo: string, opts: RetractOpts = {}): Retraction[] {+ return targets(repo, { ...opts, apply: false }).map(({ run, ...t }) => ({ ...t, action: run(false) }));+}++/**+ * Remove graft's contribution from every target. Reports every target it+ * considered, including the ones that were already clean, so a caller can show+ * either the full sweep or just what changed.+ */+export function runRetract(repo: string, opts: RetractOpts = {}): Retraction[] {+ const apply = opts.apply !== false;+ return targets(repo, opts).map(({ run, ...t }) => ({ ...t, action: run(apply) }));+}++/** The subset worth showing a user: targets that had something to remove. */+export function changed(retractions: Retraction[]): Retraction[] {+ return retractions.filter((r) => r.action !== 'absent');+}diff --git a/test/hosts-retract.test.ts b/test/hosts-retract.test.tsnew file mode 100644index 00000000..f5707152--- /dev/null+++ b/test/hosts-retract.test.ts@@ -0,0 +1,337 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';++// Pin the MCP launch form so expectations don't depend on whether the machine+// running the tests happens to have graft on PATH.+process.env.GRAFT_MCP_NPX = '1';++import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, dirname } from 'node:path';+import { planRetract, runRetract, changed } from '../src/hosts/retract.js';+import { runInit } from '../src/claude/init.js';+import { runHostsInit } from '../src/hosts/init.js';+import { registerMcpConfigs } from '../src/hosts/mcp-config.js';+import { mergeGraftSettings } from '../src/claude/settings-merge.js';++function fresh(): string {+ return mkdtempSync(join(tmpdir(), 'graft-retract-'));+}++function write(dir: string, rel: string, body: string): string {+ const path = join(dir, rel);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, body);+ return path;+}++/** A retraction report keyed by path, for asserting one target at a time. */+function byPath(rs: ReturnType<typeof runRetract>): Map<string, string> {+ return new Map(rs.map((r) => [r.path, r.action]));+}++const BLOCK = '<!-- graft:start -->\n## Graft — old text\nstale guidance\n<!-- graft:end -->';++// --------------------------------------------------------------------------+// instruction files+// --------------------------------------------------------------------------++test('an owned instruction file is deleted outright', () => {+ const d = fresh();+ const rule = write(d, join('.cursor', 'rules', 'graft.mdc'), 'stale cursor rule\n');+ const r = byPath(runRetract(d, { apply: true, global: false }));+ assert.equal(r.get(rule), 'deleted');+ assert.ok(!existsSync(rule));+});++test('a fenced section is stripped and the user\'s prose survives intact', () => {+ const d = fresh();+ const agents = write(d, 'AGENTS.md', `# My repo\n\nUser notes here.\n\n${BLOCK}\n\nMore user notes.\n`);+ runRetract(d, { apply: true, global: false });+ assert.equal(readFileSync(agents, 'utf8'), '# My repo\n\nUser notes here.\n\nMore user notes.\n');+});++test('a file that held nothing but the graft block is deleted, not left blank', () => {+ const d = fresh();+ const gemini = write(d, 'GEMINI.md', `${BLOCK}\n`);+ const r = byPath(runRetract(d, { apply: true, global: false }));+ assert.equal(r.get(gemini), 'deleted');+ assert.ok(!existsSync(gemini), 'an empty GEMINI.md is residue too');+});++test('a shared file with no graft block is reported absent and never touched', () => {+ const d = fresh();+ const agents = write(d, 'AGENTS.md', '# Just my notes\n');+ const r = byPath(runRetract(d, { apply: true, global: false }));+ assert.equal(r.get(agents), 'absent');+ assert.equal(readFileSync(agents, 'utf8'), '# Just my notes\n');+});++// --------------------------------------------------------------------------+// JSON configs+// --------------------------------------------------------------------------++test('mcpServers.graft is removed and foreign servers are preserved', () => {+ const d = fresh();+ const mcp = write(d, '.mcp.json', JSON.stringify({+ mcpServers: { graft: { command: 'graft', args: ['mcp'] }, other: { command: 'x' } },+ }));+ runRetract(d, { apply: true, global: false });+ const root = JSON.parse(readFileSync(mcp, 'utf8'));+ assert.deepEqual(Object.keys(root.mcpServers), ['other']);+});++test('a JSON config holding only the graft server is deleted', () => {+ const d = fresh();+ const kiro = write(d, join('.kiro', 'settings', 'mcp.json'), JSON.stringify({ mcpServers: { graft: {} } }));+ const r = byPath(runRetract(d, { apply: true, global: false }));+ assert.equal(r.get(kiro), 'deleted');+ assert.ok(!existsSync(kiro), 'no orphan {} left behind');+});++test('unparseable JSON is reported and left byte-for-byte alone', () => {+ const d = fresh();+ const body = '{ "mcpServers": { "graft": } // trailing junk\n';+ const mcp = write(d, '.mcp.json', body);+ const r = byPath(runRetract(d, { apply: true, global: false }));+ assert.equal(r.get(mcp), 'skipped-unparseable');+ assert.equal(readFileSync(mcp, 'utf8'), body);+});++// --------------------------------------------------------------------------+// TOML+// --------------------------------------------------------------------------++test('[mcp_servers.graft] is removed and the neighbouring table survives', () => {+ const d = fresh();+ const toml = write(d, join('.grok', 'config.toml'),+ '[mcp_servers.graft]\ncommand = "npx"\nargs = ["-y","@nanonets/graft","mcp"]\n\n[mcp_servers.keepme]\ncommand = "y"\n');+ runRetract(d, { apply: true, global: false });+ const text = readFileSync(toml, 'utf8');+ assert.ok(!text.includes('mcp_servers.graft'));+ assert.ok(text.includes('[mcp_servers.keepme]'));+ assert.ok(!text.startsWith('\n'), 'no leading blank line left behind');+});++// --------------------------------------------------------------------------+// .claude/settings.json — graft's fragments inside a file the user owns+// --------------------------------------------------------------------------++test('graft settings fragments are removed and the user\'s own settings kept', () => {+ const d = fresh();+ const settings = write(d, join('.claude', 'settings.json'), JSON.stringify({+ statusLine: { type: 'command', command: 'node ".claude/helpers/graft-statusline.cjs"' },+ hooks: {+ PostToolUse: [+ { matcher: 'Write', hooks: [{ type: 'command', command: 'node graft-hooks.cjs post-edit' }] },+ { matcher: 'Bash', hooks: [{ type: 'command', command: 'my-own-hook.sh' }] },+ ],+ Stop: [{ hooks: [{ type: 'command', command: 'node graft-hooks.cjs stop' }] }],+ },+ footerLinksRegexes: ['graft/[\\w./-]+\\.md', 'docs/.*'],+ permissions: { allow: ['Bash(graft:*)', 'Bash(ls:*)'] },+ model: 'opus',+ }));+ runRetract(d, { apply: true, global: false });+ const root = JSON.parse(readFileSync(settings, 'utf8'));++ assert.equal(root.statusLine, undefined, 'graft statusline gone');+ assert.equal(root.hooks.Stop, undefined, 'graft-only event dropped entirely');+ assert.equal(root.hooks.PostToolUse.length, 1);+ assert.equal(root.hooks.PostToolUse[0].hooks[0].command, 'my-own-hook.sh', 'foreign hook kept');+ assert.deepEqual(root.footerLinksRegexes, ['docs/.*']);+ assert.deepEqual(root.permissions.allow, ['Bash(ls:*)']);+ assert.equal(root.model, 'opus', 'unrelated settings untouched');+});++test('an older statusline shape is still recognized as graft\'s own', () => {+ const d = fresh();+ // A hypothetical v4 command: different wrapper, same shim path.+ const settings = write(d, join('.claude', 'settings.json'), JSON.stringify({+ statusLine: { type: 'command', command: 'sh -c \'node .claude/helpers/graft-statusline.cjs\'' },+ }));+ const r = byPath(runRetract(d, { apply: true, global: false }));+ assert.equal(r.get(settings), 'deleted', 'matched by shim path, not string equality');+});++test('a statusline the user actually wrote is left alone', () => {+ const d = fresh();+ const settings = write(d, join('.claude', 'settings.json'), JSON.stringify({+ statusLine: { type: 'command', command: 'my-prompt.sh' },+ }));+ runRetract(d, { apply: true, global: false });+ const root = JSON.parse(readFileSync(settings, 'utf8'));+ assert.equal(root.statusLine.command, 'my-prompt.sh');+});++// --------------------------------------------------------------------------+// the cache + ignore entries+// --------------------------------------------------------------------------++test('graft/ and its ignore entries go, and the user\'s ignores stay', () => {+ const d = fresh();+ mkdirSync(join(d, 'graft'), { recursive: true });+ writeFileSync(join(d, 'graft', 'INDEX.md'), '# index\n');+ const gitignore = write(d, '.gitignore', 'node_modules/\ndist/\n\n# graft\'s local graph cache — regenerable, not committed (run `graft build`).\n/graft/\n');+ runRetract(d, { apply: true, global: false });+ assert.ok(!existsSync(join(d, 'graft')));+ assert.equal(readFileSync(gitignore, 'utf8'), 'node_modules/\ndist/\n');+});++test('--keep-cache leaves graft/ and .gitignore untouched', () => {+ const d = fresh();+ mkdirSync(join(d, 'graft'), { recursive: true });+ const gitignore = write(d, '.gitignore', '/graft/\n');+ runRetract(d, { apply: true, global: false, cache: false });+ assert.ok(existsSync(join(d, 'graft')), 'cache kept');+ assert.equal(readFileSync(gitignore, 'utf8'), '/graft/\n');+});++// --------------------------------------------------------------------------+// contract-level properties+// --------------------------------------------------------------------------++test('planRetract is pure — it reports without touching anything', () => {+ const d = fresh();+ const rule = write(d, join('.cursor', 'rules', 'graft.mdc'), 'stale\n');+ const agents = write(d, 'AGENTS.md', `notes\n\n${BLOCK}\n`);+ const plan = planRetract(d, { global: false });++ assert.ok(existsSync(rule), 'plan did not delete');+ assert.equal(readFileSync(agents, 'utf8'), `notes\n\n${BLOCK}\n`);+ const p = new Map(plan.map((r) => [r.path, r.action]));+ assert.equal(p.get(rule), 'deleted');+ assert.equal(p.get(agents), 'removed');+});++test('a full init is fully retractable, and retraction is idempotent', () => {+ const d = fresh();+ runInit(d, { build: false });+ runHostsInit(d, { agents: ['cursor', 'agents'], home: d, global: false });++ const first = changed(runRetract(d, { apply: true, global: false }));+ assert.ok(first.length > 0, 'init left something to retract');++ // Everything init wrote for those hosts is gone.+ for (const rel of [+ join('.claude', 'settings.json'),+ join('.claude', 'helpers', 'graft-statusline.cjs'),+ join('.claude', 'helpers', 'graft-hooks.cjs'),+ join('.claude', 'skills', 'graft', 'SKILL.md'),+ join('.cursor', 'rules', 'graft.mdc'),+ '.mcp.json',+ ]) {+ assert.ok(!existsSync(join(d, rel)), `${rel} should be gone`);+ }++ // A second sweep finds nothing — no residue, no double-removal.+ const second = changed(runRetract(d, { apply: true, global: false }));+ assert.deepEqual(second, [], `second sweep should be a no-op, got ${JSON.stringify(second)}`);+});++test('exclude spares the hosts init is about to rewrite', () => {+ const d = fresh();+ const cursor = write(d, join('.cursor', 'rules', 'graft.mdc'), 'cursor\n');+ const kiro = write(d, join('.kiro', 'steering', 'graft.md'), 'kiro\n');+ runRetract(d, { apply: true, global: false, exclude: ['cursor'] });+ assert.ok(existsSync(cursor), 'selected host kept');+ assert.ok(!existsSync(kiro), 'unselected host retracted');+});++test('--no-global never reaches outside the repo', () => {+ const d = fresh();+ const home = fresh();+ // A machine-level Codex install with graft's hook shim in it.+ write(home, join('.codex', 'hooks', 'graft', 'graft-hooks.cjs'), 'shim\n');+ const rs = runRetract(d, { apply: true, home, global: false });+ assert.equal(rs.filter((r) => r.scope === 'global').length, 0, 'no global targets even considered');+ assert.ok(existsSync(join(home, '.codex', 'hooks', 'graft', 'graft-hooks.cjs')));+});++test('global sweep strips graft hook entries from Codex hooks.json, keeping foreign ones', () => {+ const d = fresh();+ const home = fresh();+ mkdirSync(join(home, '.codex'), { recursive: true });+ const cfg = write(home, join('.codex', 'hooks.json'), JSON.stringify({+ hooks: {+ PostToolUse: [+ { hooks: [{ type: 'command', command: 'node "/x/graft-hooks.cjs" post-edit' }] },+ { hooks: [{ type: 'command', command: 'their-hook.sh' }] },+ ],+ },+ }));+ runRetract(d, { apply: true, home, global: true });+ const root = JSON.parse(readFileSync(cfg, 'utf8'));+ assert.equal(root.hooks.PostToolUse.length, 1);+ assert.equal(root.hooks.PostToolUse[0].hooks[0].command, 'their-hook.sh');+});++test('emptied directories are pruned, not left hollow', () => {+ const d = fresh();+ write(d, join('.claude', 'skills', 'graft', 'SKILL.md'), 'skill\n');+ runRetract(d, { apply: true, global: false });+ assert.ok(!existsSync(join(d, '.claude', 'skills', 'graft')), 'graft/ skill dir pruned');+ assert.ok(!existsSync(join(d, '.claude', 'skills')), 'now-empty skills/ pruned too');+});++// --------------------------------------------------------------------------+// the two append-only writers, now converging+// --------------------------------------------------------------------------++test('a stale [mcp_servers.graft] is replaced, not skipped', () => {+ const d = fresh();+ const cfg = write(d, join('.grok', 'config.toml'),+ '[mcp_servers.keepme]\ncommand = "y"\n\n[mcp_servers.graft]\ncommand = "OLD-BINARY"\nargs = ["stale"]\n');+ const [w] = registerMcpConfigs(d, ['grok'], { home: d });++ assert.equal(w.action, 'updated', 'an existing section used to freeze the launch command');+ const text = readFileSync(cfg, 'utf8');+ assert.ok(!text.includes('OLD-BINARY'), 'stale command gone');+ assert.ok(text.includes('[mcp_servers.keepme]'), 'foreign table preserved');+ assert.equal((text.match(/\[mcp_servers\.graft\]/g) ?? []).length, 1, 'exactly one graft section');++ // Second run is a no-op, not a churn.+ assert.equal(registerMcpConfigs(d, ['grok'], { home: d })[0].action, 'unchanged');+ assert.equal(readFileSync(cfg, 'utf8'), text, 'byte-identical on re-run');+});++test('a renamed allowlist entry is dropped; the user\'s own rules stay', () => {+ const { merged } = mergeGraftSettings({+ permissions: { allow: ['Bash(graft-dev:*)', 'Bash(ls:*)', 'Bash(graft-mytool:*)'] },+ });+ const allow: string[] = merged.permissions.allow;+ assert.ok(allow.includes('Bash(ls:*)'), 'unrelated rule kept');+ assert.ok(allow.includes('Bash(graft-mytool:*)'), 'the user\'s own graft-prefixed rule kept');+ assert.equal(allow.filter((a) => a === 'Bash(graft-dev:*)').length, 1, 'no duplicate of graft\'s own entry');+});++test('a superseded footer regex is replaced rather than stacked', () => {+ const { merged } = mergeGraftSettings({+ footerLinksRegexes: ['graft/OLD-PATTERN\\.md', 'docs/.*'],+ });+ assert.ok(!merged.footerLinksRegexes.includes('graft/OLD-PATTERN\\.md'), 'old graft pattern gone');+ assert.ok(merged.footerLinksRegexes.includes('docs/.*'), 'user pattern kept');+ assert.equal(merged.footerLinksRegexes.filter((r: string) => r.startsWith('graft/')).length, 1);+});++test('mergeGraftSettings stays idempotent over repeated runs', () => {+ const once = mergeGraftSettings({}).merged;+ const twice = mergeGraftSettings(structuredClone(once)).merged;+ assert.deepEqual(twice, once, 'a re-init must not grow the file');+});++test('a shared AGENTS.md is spared when any host that writes it is kept', () => {+ const d = fresh();+ // Three registry hosts name AGENTS.md: agents, hermes, antigravity.+ const agents = write(d, 'AGENTS.md', `# Notes\n\n${BLOCK}\n`);+ runRetract(d, { apply: true, global: false, exclude: ['agents'] });+ assert.ok(readFileSync(agents, 'utf8').includes('graft:start'),+ 'hermes/antigravity must not strip the block that the kept `agents` host owns');+});++test('hosts sharing one path produce a single retraction, not one each', () => {+ const d = fresh();+ const agents = write(d, 'AGENTS.md', `# Notes\n\n${BLOCK}\n`);+ const rs = runRetract(d, { global: false }).filter((r) => r.path === agents);+ assert.equal(rs.length, 1, `AGENTS.md should be queued once, got ${rs.length}`);+});