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
fix(hosts): install Claude Code wiring in ~ too, so worktrees keep graft (#276)
anirudhkumar-nanonets2f69b3f60ad8
diff --git a/src/claude/init.ts b/src/claude/init.tsindex ca563e93..111c0f92 100644--- a/src/claude/init.ts+++ b/src/claude/init.ts@@ -1,6 +1,8 @@import { mkdirSync, writeFileSync, readFileSync, chmodSync } from 'node:fs';import { join, dirname } from 'node:path';+import { homedir } from 'node:os';import { execFileSync } from 'node:child_process';+import { installClaudeGlobal, type GlobalWrite } from '../hosts/claude-global.js';import { mergeGraftSettings } from './settings-merge.js';import { statuslineShim, hooksShim } from './shim-template.js';import { skillTemplate } from './skill-template.js';@@ -52,11 +54,16 @@ export interface InitResult {skill: string;/** the `.mcp.json` write registering the graft MCP server for Claude Code. */mcp: McpWrite;+ /** the user-level writes under `~/.claude`, empty when `global: false`. */+ global: GlobalWrite[];warnings: string[];built: boolean;}-export function runInit(dir: string, opts: { build?: boolean; cliPath?: string; statusline?: boolean } = {}): InitResult {+export function runInit(+ dir: string,+ opts: { build?: boolean; cliPath?: string; statusline?: boolean; global?: boolean; home?: string } = {},+): InitResult {// Same list `--dry-run` and the picker report, so the two can't drift apart.const [settings, statusline, hooks, skill, mcpTarget] = claudeTargets(dir).map((t) => t.path);@@ -85,6 +92,13 @@ export function runInit(dir: string, opts: { build?: boolean; cliPath?: string;// other hosts use (existing servers preserved; unparseable files skipped).const mcp = mergeJsonKey('claude', mcpTarget, 'mcpServers', serverEntry());+ // The same wiring again, one level up in `~/.claude`, because everything above+ // this line can be erased by a `.gitignore` and lost to `git worktree add`. See+ // hosts/claude-global.ts for the failure that motivates it. Gated on the same+ // flag `registerMcpConfigs` uses, so `--no-global` still means "nothing outside+ // this repo".+ const global = opts.global === false ? [] : installClaudeGlobal(opts.home ?? homedir());+const built = buildGraphIfMissing(dir, opts);- return { settingsPath, shims: [sl, hk], skill: skillPath, mcp, warnings, built };+ return { settingsPath, shims: [sl, hk], skill: skillPath, mcp, global, warnings, built };}diff --git a/src/claude/settings-merge.ts b/src/claude/settings-merge.tsindex 6571d4c7..3ee1d15b 100644--- a/src/claude/settings-merge.ts+++ b/src/claude/settings-merge.ts@@ -18,13 +18,23 @@ const ALLOW_ENTRIES = ['Bash(node dist/cli.js:*)',];-function hookCmd(arg: string): string {- return `node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs" ${arg}`;+/** Where the repo-level install's shims sit, relative to whatever project is open. */+const REPO_HELPERS = '${CLAUDE_PROJECT_DIR:-.}/.claude/helpers';++/**+ * `helpers` is the directory holding `graft-hooks.cjs`, and it is a parameter for+ * one reason: the user-level install (see hosts/claude-global.ts) has to name an+ * absolute path. A `${CLAUDE_PROJECT_DIR}` command works only where a previous+ * `graft init` wrote a shim into that project — which is exactly the case the+ * global copy exists to cover, so it cannot reuse the repo form.+ */+function hookCmd(arg: string, helpers: string = REPO_HELPERS): string {+ return `node "${helpers}/graft-hooks.cjs" ${arg}`;}-function graftBlocks(): Record<string, Json[]> {+function graftBlocks(helpers?: string): Record<string, Json[]> {return {PostToolUse: [- { matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: hookCmd('post-edit'), timeout: 10000 }] },+ { matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: hookCmd('post-edit', helpers), timeout: 10000 }] },// Score the usage mix and sum token savings. A graft retrieval (CLI `graft …`// via Bash, or the `graft_*` MCP tools) prints a `[graft] tokens saved ≈ N`// footer this hook sums into the session total; the same hook classifies@@ -32,7 +42,7 @@ function graftBlocks(): Record<string, Json[]> {// `graft stats` and the `session_summary` graft-vs-grep ratio. Broad matcher,// but the handler no-ops instantly unless there is something to record, so an// unrelated Bash or a plain Read costs only a stdin read.- { matcher: 'Bash|mcp__graft__|Read|Grep|Glob', hooks: [{ type: 'command', command: hookCmd('tool-savings'), timeout: 8000 }] },+ { matcher: 'Bash|mcp__graft__|Read|Grep|Glob', hooks: [{ type: 'command', command: hookCmd('tool-savings', helpers), timeout: 8000 }] },],// Longer budget than the other hooks: its `graft ask` is a real query, and a// query now brings the graph up to date first (graph/refresh.ts) — usually@@ -42,9 +52,9 @@ function graftBlocks(): Record<string, Json[]> {// this bump (8s) keeps a child that fits inside 8s. Changing the number here is// therefore safe on its own — but it only reaches an existing repo when someone// re-runs `graft init`, since that is the only caller of this function.- UserPromptSubmit: [{ hooks: [{ type: 'command', command: hookCmd('prompt'), timeout: 15000 }] }],- SessionStart: [{ hooks: [{ type: 'command', command: hookCmd('session-start'), timeout: 8000 }] }],- Stop: [{ hooks: [{ type: 'command', command: hookCmd('stop'), timeout: 8000 }] }],+ UserPromptSubmit: [{ hooks: [{ type: 'command', command: hookCmd('prompt', helpers), timeout: 15000 }] }],+ SessionStart: [{ hooks: [{ type: 'command', command: hookCmd('session-start', helpers), timeout: 8000 }] }],+ Stop: [{ hooks: [{ type: 'command', command: hookCmd('stop', helpers), timeout: 8000 }] }],};}/**@@ -141,3 +151,29 @@ export function mergeGraftSettings(return { merged, warnings };}++/**+ * The hook blocks alone, merged into a settings file, with the shims addressed by+ * absolute path — `~/.claude/settings.json`, where a write reaches every project on+ * the machine (see hosts/claude-global.ts for why that copy has to exist).+ *+ * Hooks only, deliberately. `mergeGraftSettings` also claims the statusline, the+ * footer regex and a Bash allowlist, and each of those is a reasonable thing to+ * accept for a repo you ran `graft init` in and an unreasonable thing to impose on+ * every repo you ever open — a statusline especially, since a session allows exactly+ * one and taking it globally would silently outrank the user's own. The hooks are the+ * piece that has to be global, because they are what a worktree loses.+ *+ * Same idempotent shape as the repo merge: graft's prior entries are dropped before+ * the current set is added, so re-running converges instead of stacking.+ */+export function mergeGraftHooks(existing: Json, helpers: string): { merged: Json } {+ const merged: Json = { ...(existing ?? {}) };+ merged.hooks = { ...(merged.hooks ?? {}) };+ for (const [event, blocks] of Object.entries(graftBlocks(helpers))) {+ const prior = Array.isArray(merged.hooks[event]) ? merged.hooks[event] : [];+ const foreign = prior.filter((e: Json) => !isGraftEntry(e));+ merged.hooks[event] = [...foreign, ...blocks];+ }+ return { merged };+}diff --git a/src/cli.ts b/src/cli.tsindex afeb81da..edd7ef4e 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -1062,7 +1062,10 @@ function wireTarget(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, statusline: wantStatusline });+ // `global`/`home` are threaded through alongside `statusline`: the claude layer+ // writes under `~/.claude` now (hosts/claude-global.ts), so --no-global has to+ // reach it or the flag would silently mean "no out-of-repo writes, except three".+ const res = runInit(repo, { build: opts.build, cliPath, statusline: wantStatusline, global: opts.global, home });console.error(`✓ wrote ${res.settingsPath}`);for (const s of res.shims) console.error(`✓ wrote ${s}`);console.error(`✓ wrote ${res.skill}`);diff --git a/src/hosts/claude-global.ts b/src/hosts/claude-global.tsnew file mode 100644index 00000000..30900877--- /dev/null+++ b/src/hosts/claude-global.ts@@ -0,0 +1,125 @@+/**+ * User-level install for Claude Code: the copy of graft's wiring that lives+ * outside every repo.+ *+ * Why this exists. Everything `graft init` writes for Claude Code lands *in* the+ * repo — `.mcp.json` and `.claude/settings.json`. A `.gitignore` is free to ignore+ * both, and `git worktree add` checks out tracked files only, so a worktree of such+ * a repo starts with graft's shims present and neither of the two files that *point+ * at* them. No settings.json means no SessionStart hook; no `.mcp.json` means no+ * tool server. graft is absent, silently, in a tree that looks correctly wired.+ *+ * graft already carries the repair for exactly that — `reconcileWiring` rewrites+ * both files — and it is unreachable here: `runUpkeep` is called only from the hook+ * and from the MCP server, which are the two things that are missing. Seeding can't+ * help either, since it runs on the query path, which needs the server.+ *+ * So the fix cannot live in the repo. `~/.claude/` is not in anyone's working tree,+ * no `.gitignore` reaches it, and Claude Code reads it for every project — worktrees+ * included. Codex has been installed this way from the start (see ./codex-hooks.ts,+ * whose own note says the entries "fire in every repo opened with Codex, not just+ * this one"); Claude Code was the one host graft wired repo-only. This module closes+ * that gap, and is a deliberate mirror of that file.+ *+ * The repo-level writes stay exactly as they were. A project that has its own+ * `.mcp.json` and settings keeps using them; this is the floor underneath, not a+ * replacement.+ */+import { writeFileSync, mkdirSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { hooksShim } from '../claude/shim-template.js';+import { claudeDistDir } from '../claude/paths.js';+import { mergeGraftHooks } from '../claude/settings-merge.js';+import { toPosixPath } from '../util/paths.js';+import { readJsonObject, writeOwned, type ConfigWrite } from './config-write.js';+import { mergeJsonKey, serverEntry } from './mcp-config.js';+import type { PlannedWrite } from './plan.js';++/** Same `{ id, path, action }` contract every other writer in this layer reports. */+export type GlobalWrite = ConfigWrite;++/** The directory the user-level shim lives in — the base every hook command names. */+export function globalHelpersDir(home: string): string {+ return join(home, '.claude', 'helpers');+}++/**+ * The files a user-level install would touch — pure, no writes, so `--dry-run` and+ * the picker can report them up front. All three are scoped 'global': they apply to+ * every project opened with Claude Code, not just this one.+ *+ * `~/.claude.json` holds the *user* MCP scope — the top-level `mcpServers` map, the+ * one `claude mcp add --scope user` writes. Not to be confused with the same file's+ * `projects["<abs path>"].mcpServers`, which is `--scope local` and per-directory:+ * a worktree is its own project entry there, so a local registration would miss it+ * for precisely the same reason the repo file does.+ */+export function claudeGlobalTargets(home: string): PlannedWrite[] {+ const g = (id: string, path: string, kind: PlannedWrite['kind'], what: string): PlannedWrite =>+ ({ hostId: 'claude', id, path, scope: 'global', kind, what });+ return [+ g('claude-global-shim', join(globalHelpersDir(home), 'graft-hooks.cjs'), 'hook', 'hooks shim (user level)'),+ g('claude-global-hooks', join(home, '.claude', 'settings.json'), 'hook', 'SessionStart / UserPromptSubmit / PostToolUse / Stop'),+ g('claude-global-mcp', join(home, '.claude.json'), 'mcp', 'mcpServers.graft'),+ ];+}++/** Merge graft's hook blocks into a settings file, preserving everything else. */+function upsertGlobalHooks(id: string, path: string, helpers: string): GlobalWrite {+ const loaded = readJsonObject(path);+ if (loaded === 'unparseable') return { id, path, action: 'skipped-unparseable' };+ const { root: existing, existed } = loaded;+ const before = JSON.stringify(existing);+ const { merged } = mergeGraftHooks(existing, helpers);+ if (JSON.stringify(merged) === before) return { id, path, action: 'unchanged' };+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${JSON.stringify(merged, null, 2)}\n`);+ return { id, path, action: existed ? 'updated' : 'created' };+}++/**+ * Install the user-level copy: the shim, the hook entries that call it, and the+ * user-scope MCP registration.+ *+ * The shim is written to `home` and the hook commands name it by absolute path, for+ * the reason the repo form can't be reused: `${CLAUDE_PROJECT_DIR}/.claude/helpers/`+ * resolves inside whatever project is open, and the whole point is to work in one+ * that has no such file. `hooksShim(claudeDistDir())` bakes in the installed+ * package's `dist/`, exactly as the Codex install does.+ *+ * Best-effort by contract, like every other writer here: a failure is reported as an+ * action, never raised, so a bad `~/.claude.json` can't fail a `graft init`.+ */+export function installClaudeGlobal(home: string): GlobalWrite[] {+ const [shim, settings, mcp] = claudeGlobalTargets(home);+ const out: GlobalWrite[] = [];++ try {+ out.push(writeOwned(shim.id, shim.path, hooksShim(claudeDistDir()), 0o755));+ } catch {+ out.push({ id: shim.id, path: shim.path, action: 'skipped-unparseable' });+ }++ // Only wire the hooks once the shim they call is actually on disk — a hook+ // entry pointing at a missing file is an error in every session, which is a+ // worse failure than not installing.+ if (out[0].action !== 'skipped-unparseable') {+ try {+ // Posix form in the command string: `join` gives backslashes on Windows and+ // the template appends `/graft-hooks.cjs`, so the raw path produces a mixed+ // `C:\Users\…\helpers/graft-hooks.cjs`. Node accepts forward slashes on+ // Windows, so one separator throughout is both correct and readable.+ out.push(upsertGlobalHooks(settings.id, settings.path, toPosixPath(globalHelpersDir(home))));+ } catch {+ out.push({ id: settings.id, path: settings.path, action: 'skipped-unparseable' });+ }+ }++ try {+ out.push(mergeJsonKey(mcp.id, mcp.path, 'mcpServers', serverEntry()));+ } catch {+ out.push({ id: mcp.id, path: mcp.path, action: 'skipped-unparseable' });+ }++ return out;+}diff --git a/src/hosts/plan.ts b/src/hosts/plan.tsindex 991b97f9..38b225b3 100644--- a/src/hosts/plan.ts+++ b/src/hosts/plan.ts@@ -16,6 +16,7 @@ import { hookTargets } from './codex-hooks.js';import { cursorHookTargets } from './cursor-hooks.js';import { antigravitySkillTargets } from './antigravity.js';import { claudeTargets } from '../claude/init.js';+import { claudeGlobalTargets } from './claude-global.js';/** Where a write lands. 'global' = outside the repo, affects every project. */export type WriteScope = 'repo' | 'global';@@ -70,7 +71,10 @@ export function planInit(repo: string, opts: { home?: string; ids?: string[] } =const detected = new Set(detectHosts(probe).map((h) => h.id));const plans: HostPlan[] = [- { id: 'claude', name: 'Claude Code', detected: true, writes: claudeTargets(repo) },+ // Repo writes plus the user-level copy under `~/.claude` — the picker and+ // `--dry-run` render 'global' writes in their own section, so a user sees+ // what lands outside the repo before agreeing to it.+ { id: 'claude', name: 'Claude Code', detected: true, writes: [...claudeTargets(repo), ...claudeGlobalTargets(home)] },...HOSTS.map((host) => ({id: host.id,name: host.name,diff --git a/src/hosts/retract.ts b/src/hosts/retract.tsindex b8fddbd3..8cb7b8a8 100644--- a/src/hosts/retract.ts+++ b/src/hosts/retract.ts@@ -31,6 +31,7 @@ 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 { claudeGlobalTargets } from './claude-global.js';import { claudeTargets } from '../claude/init.js';import { isGraftAllowEntry, isGraftFooterRegex } from '../claude/settings-merge.js';import type { WriteScope } from './plan.js';@@ -364,7 +365,10 @@ function targets(repo: string, opts: RetractOpts): Target[] {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('claude')) {+ for (const t of claudeTargets(repo)) keptPaths.add(t.path);+ for (const t of claudeGlobalTargets(home)) 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);@@ -420,8 +424,17 @@ function targets(repo: string, opts: RetractOpts): Target[] {] as Target[]) add(t);}- // 4. Global: Codex's hook shim + entries, and Antigravity's shared skill.+ // 4. Global: Claude Code's user-level copy, Codex's hook shim + entries, and+ // Antigravity's shared skill.if (opts.global !== false) {+ if (!exclude.has('claude')) {+ const [shim, settings, mcp] = claudeGlobalTargets(home);+ for (const t of [+ { hostId: 'claude', path: shim.path, what: shim.what, scope: 'global', run: (a) => removeFile(shim.path, a) },+ { hostId: 'claude', path: settings.path, what: settings.what, scope: 'global', run: (a) => stripClaudeSettings(settings.path, a) },+ { hostId: 'claude', path: mcp.path, what: mcp.what, scope: 'global', run: (a) => removeJsonKey(mcp.path, 'mcpServers', a) },+ ] as Target[]) add(t);+ }if (!exclude.has('agents')) {for (const t of hookTargets(home)) {add({diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex e5072509..05d29df6 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -5,6 +5,8 @@import { createInterface } from 'node:readline';import { TOOLS, callTool } from './tools.js';import { mcpInstructions } from './instructions.js';+import { hasGraftIndex } from '../graph/root.js';+import { mainWorktreeRoot } from '../graph/seed.js';import { runUpkeep } from '../upkeep-run.js';import { runningVersion } from '../upkeep.js';import { maybeFlushInBackground, track } from '../telemetry/index.js';@@ -36,6 +38,31 @@ function replyError(id: unknown, code: number, message: string): void {send({ jsonrpc: '2.0', id, error: { code, message } });}+/**+ * Which tools this server admits to having.+ *+ * `hosts/claude-global.ts` registers graft at the *user* MCP scope, which starts this+ * server in every project the user opens — including ones that never asked for graft.+ * Six tool schemas is real context, charged on every turn of every session, and in a+ * repo with no graph every one of them can only answer "run graft build". So a repo+ * that never invited graft is told there is nothing to call.+ *+ * The parent-checkout clause is not an optimization, it is the case the global+ * registration exists for: a fresh `git worktree add` has no `graft/` of its own+ * (it's gitignored, so git never checks it out) and gets one from its parent on the+ * first query — see graph/seed.ts. Gating on this tree alone would hide graft in+ * precisely the worktree the user is trying to work in, which is the bug, inverted.+ *+ * A `--dir` override is an explicit "the graph is over there", so it always+ * advertises without a probe.+ */+function advertised(root: string, dirOverride?: string): typeof TOOLS {+ if (dirOverride !== undefined) return TOOLS;+ if (hasGraftIndex(root)) return TOOLS;+ const main = mainWorktreeRoot(root);+ return main && hasGraftIndex(main) ? TOOLS : [];+}+/*** `version` is threaded in from the CLI rather than read here: `readCurrentVersion`* resolves package.json relative to the calling module, and from `dist/mcp/` that@@ -88,11 +115,11 @@ export function startMcpServer(root: string, dirOverride?: string, version = '0'case 'ping':if (!isNotification) reply(id, {});return;- case 'tools/list':- if (!isNotification) {- reply(id, { tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });- }+ case 'tools/list': {+ if (isNotification) return;+ reply(id, { tools: advertised(root, dirOverride).map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });return;+ }case 'tools/call': {if (isNotification) return;const name = String(params?.name ?? '');diff --git a/src/upkeep-run.ts b/src/upkeep-run.tsindex 775a8c67..7c64afa5 100644--- a/src/upkeep-run.ts+++ b/src/upkeep-run.ts@@ -39,7 +39,11 @@ export interface UpkeepResult {* `opts.global`/`opts.hooks`, replayed from the stamp.*/function rewriteWiring(repo: string, hosts: string[], opts: WiringOpts): void {- if (hosts.includes('claude')) runInit(repo, { build: false, cliPath: graftCliPath(), statusline: opts.statusline });+ // `opts.global` reaches the claude layer for the same reason `opts.statusline` does:+ // its `~/.claude` writes (hosts/claude-global.ts) are out-of-repo, and a user who+ // declined those at init time must keep declining them on every replay.+ if (hosts.includes('claude'))+ runInit(repo, { build: false, cliPath: graftCliPath(), statusline: opts.statusline, global: opts.global });const others = hosts.filter((h) => h !== 'claude');if (others.length)runHostsInit(repo, { agents: others, global: opts.global, mcp: opts.mcp, hooks: opts.hooks });diff --git a/test/claude-init.test.ts b/test/claude-init.test.tsindex 2babb32b..2a7fbf6d 100644--- a/test/claude-init.test.ts+++ b/test/claude-init.test.ts@@ -23,7 +23,7 @@ function runPostinstall(env: Record<string, string>): string {test('runInit scaffolds settings + both shims + the skill (build skipped)', () => {const d = fresh();- const r = runInit(d, { build: false });+ const r = runInit(d, { build: false, home: fresh() });assert.ok(existsSync(join(d, '.claude', 'settings.json')));assert.ok(existsSync(join(d, '.claude', 'helpers', 'graft-statusline.cjs')));assert.ok(existsSync(join(d, '.claude', 'helpers', 'graft-hooks.cjs')));@@ -43,7 +43,7 @@ test('runInit overwrites a stale skill file', () => {const skillPath = join(d, '.claude', 'skills', 'graft', 'SKILL.md');mkdirSync(join(d, '.claude', 'skills', 'graft'), { recursive: true });writeFileSync(skillPath, 'stale junk');- runInit(d, { build: false });+ runInit(d, { build: false, home: fresh() });assert.match(readFileSync(skillPath, 'utf8'), /name: graft/);});@@ -51,7 +51,7 @@ test('runInit preserves foreign settings and warns on foreign statusLine', () =>const d = fresh();mkdirSync(join(d, '.claude'), { recursive: true });writeFileSync(join(d, '.claude', 'settings.json'), JSON.stringify({ model: 'x', statusLine: { command: 'mine' } }));- const r = runInit(d, { build: false });+ const r = runInit(d, { build: false, home: fresh() });const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));assert.equal(s.model, 'x');assert.equal(s.statusLine.command, 'mine');@@ -97,8 +97,8 @@ test('CLI: --no-statusline leaves statusLine unset', () => {test('runInit is idempotent', () => {const d = fresh();- runInit(d, { build: false });- runInit(d, { build: false });+ runInit(d, { build: false, home: fresh() });+ runInit(d, { build: false, home: fresh() });const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));assert.equal(s.hooks.PostToolUse.length, 2); // post-edit + tool-savings, not duplicated on re-initassert.deepEqual(s.permissions.allow, ['Bash(graft:*)', 'Bash(npx graft:*)', 'Bash(graft-dev:*)', 'Bash(node dist/cli.js:*)']);@@ -108,7 +108,7 @@ test('runInit appends the allowlist to a pre-existing permissions block, preservconst d = fresh();mkdirSync(join(d, '.claude'), { recursive: true });writeFileSync(join(d, '.claude', 'settings.json'), JSON.stringify({ permissions: { allow: ['Bash(ls)'] } }));- runInit(d, { build: false });+ runInit(d, { build: false, home: fresh() });const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));assert.deepEqual(s.permissions.allow, ['Bash(ls)', 'Bash(graft:*)', 'Bash(npx graft:*)', 'Bash(graft-dev:*)', 'Bash(node dist/cli.js:*)']);});@@ -121,7 +121,7 @@ test('postinstall prints the nudge in a fresh dir', () => {test('postinstall is silent when already initialized', () => {const d = fresh();- runInit(d, { build: false });+ runInit(d, { build: false, home: fresh() });const out = runPostinstall({ INIT_CWD: d, CI: '' });assert.equal(out.trim(), '');});diff --git a/test/cli-picker.test.ts b/test/cli-picker.test.tsindex 0de3d9d3..d13f049c 100644--- a/test/cli-picker.test.ts+++ b/test/cli-picker.test.ts@@ -194,12 +194,23 @@ test('formatPlan separates repo writes from machine-wide ones', () => {});test('formatPlan omits the machine-wide section when there is nothing global', () => {+ // Cursor, not Claude Code: the claude layer now always carries three writes under+ // `~/.claude` (src/hosts/claude-global.ts), so it can no longer stand in for a+ // repo-only selection. Cursor is one — `.cursor/rules/` plus `.cursor/mcp.json`.const repo = fresh(); const home = fullHome();- const text = formatPlan(planInit(repo, { home }), ['claude'], repo, home, false);+ const text = formatPlan(planInit(repo, { home }), ['cursor'], repo, home, false);assert.doesNotMatch(text, /affects ALL repos/);assert.doesNotMatch(text, /--no-global/);});+test('formatPlan surfaces the claude layer\'s ~ writes as machine-wide', () => {+ const repo = fresh(); const home = fullHome();+ const text = formatPlan(planInit(repo, { home }), ['claude'], repo, home, false);+ assert.match(text, /affects ALL repos/);+ assert.match(text, /--no-global/);+ assert.match(text, /\.claude\.json/);+});+test('formatPlan says so when nothing is selected', () => {const repo = fresh();assert.match(formatPlan(planInit(repo, { home: fresh() }), [], repo, fresh(), false), /nothing/);diff --git a/test/hosts-claude-global.test.ts b/test/hosts-claude-global.test.tsnew file mode 100644index 00000000..6a690117--- /dev/null+++ b/test/hosts-claude-global.test.ts@@ -0,0 +1,226 @@+/**+ * The user-level Claude Code install — graft's wiring outside any repo.+ *+ * The bug it exists for, reported against a real repo: `.gitignore` line 1 was a+ * blanket `*.json`, which ignores both `.mcp.json` and `.claude/settings.json`.+ * `git worktree add` checks out tracked files only, so every worktree of that repo+ * started with graft's `.cjs` shims present and neither of the two files that point+ * at them — no SessionStart hook, no MCP server, graft silently absent in a tree+ * that looked correctly wired. The first test here drives real `git init` /+ * `git worktree add` rather than faking it, because the whole failure lives in what+ * git chooses to carry across.+ *+ * The rest hold the two properties that keep the fix safe to ship: nothing lands in+ * `~` when `--no-global` is passed, and `graft uninstall` removes exactly what an+ * init added.+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';++// Pin the MCP launch command to the npx form so expectations don't depend on+// whether the machine running the tests has graft on PATH.+process.env.GRAFT_MCP_NPX = '1';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { claudeGlobalTargets, globalHelpersDir, installClaudeGlobal } from '../src/hosts/claude-global.js';+import { runInit } from '../src/claude/init.js';+import { planRetract, runRetract } from '../src/hosts/retract.js';+import { planInit } from '../src/hosts/plan.js';+import { toPosixPath } from '../src/util/paths.js';+import { tmpRepo } from './helpers.js';++/**+ * Isolated from the developer's own git config, and carrying an identity of its own:+ * a CI runner has no `user.email`, and blanking GIT_CONFIG_GLOBAL removes any it did+ * have, so `git commit` fails without these. Same block as test/graph-seed.test.ts.+ */+const git = (d: string, ...args: string[]): void => {+ execFileSync('git', args, {+ cwd: d,+ stdio: 'ignore',+ env: {+ ...process.env,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_SYSTEM: '/dev/null',+ GIT_AUTHOR_NAME: 'graft test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'graft test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ },+ });+};++const settingsOf = (home: string): string => join(home, '.claude', 'settings.json');+const shimOf = (home: string): string => join(globalHelpersDir(home), 'graft-hooks.cjs');+const userMcpOf = (home: string): string => join(home, '.claude.json');++const readJson = (p: string): Record<string, any> => JSON.parse(readFileSync(p, 'utf8'));++/* ------------------------------------------------------------------ *+ * the reported failure+ * ------------------------------------------------------------------ */++/** sj's repo: `*.json` ignored wholesale, `.claude/` otherwise tracked. */+function repoIgnoringJson(): string {+ const d = tmpRepo('cgrepo');+ git(d, 'init', '-b', 'main');+ mkdirSync(join(d, 'src'), { recursive: true });+ writeFileSync(join(d, 'src', 'math.ts'), 'export const add = (a: number, b: number) => a + b;\n');+ writeFileSync(join(d, '.gitignore'), '*.json\ngraft/\n');+ return d;+}++test('a worktree of a repo that ignores *.json loses both repo-level triggers', () => {+ const home = tmpRepo('cghome');+ const main = repoIgnoringJson();++ runInit(main, { build: false, home });+ // Both repo files exist in the main checkout...+ assert.ok(existsSync(join(main, '.mcp.json')));+ assert.ok(existsSync(join(main, '.claude', 'settings.json')));++ git(main, 'add', '-A');+ git(main, 'commit', '-m', 'init');++ // ...and git refuses to track either of them, which is the root cause.+ for (const rel of ['.mcp.json', '.claude/settings.json']) {+ const tracked = execFileSync('git', ['ls-files', rel], { cwd: main, encoding: 'utf8' }).trim();+ assert.equal(tracked, '', `${rel} is ignored by *.json, so it is untracked`);+ }++ const wt = join(tmpRepo('cgwt'), 'feature');+ git(main, 'worktree', 'add', '--detach', wt, 'HEAD');++ // The shim travels (it's a .cjs). The two files that call it do not.+ assert.ok(existsSync(join(wt, '.claude', 'helpers', 'graft-hooks.cjs')), 'the .cjs shim is tracked');+ assert.equal(existsSync(join(wt, '.mcp.json')), false, 'no MCP server in the worktree');+ assert.equal(existsSync(join(wt, '.claude', 'settings.json')), false, 'no SessionStart hook either');++ // The user-level copy is what covers it: outside the repo, so no .gitignore+ // reaches it, and Claude Code reads it for every project including this one.+ assert.ok(existsSync(shimOf(home)));+ assert.ok(readJson(settingsOf(home)).hooks?.SessionStart, 'user-level SessionStart hook');+ assert.ok(readJson(userMcpOf(home)).mcpServers?.graft, 'user-scope MCP registration');+});++test('the user-level hook commands name the shim absolutely, not via CLAUDE_PROJECT_DIR', () => {+ const home = tmpRepo('cgabs');+ installClaudeGlobal(home);++ const cmd = readJson(settingsOf(home)).hooks.SessionStart[0].hooks[0].command;+ // The repo form would resolve inside whatever project is open — precisely the+ // project that has no shim, which is the case this install exists to cover.+ assert.ok(!cmd.includes('CLAUDE_PROJECT_DIR'), `absolute, got: ${cmd}`);+ // Posix form: the command uses one separator throughout, on every platform.+ assert.ok(cmd.includes(toPosixPath(shimOf(home))), `names the user-level shim, got: ${cmd}`);+});++/* ------------------------------------------------------------------ *+ * safe to run on someone's real home directory+ * ------------------------------------------------------------------ */++test('an existing settings.json keeps every key graft does not own', () => {+ const home = tmpRepo('cgkeep');+ mkdirSync(join(home, '.claude'), { recursive: true });+ writeFileSync(settingsOf(home), JSON.stringify({ theme: 'light', effortLevel: 'high' }, null, 2));++ installClaudeGlobal(home);++ const s = readJson(settingsOf(home));+ assert.equal(s.theme, 'light');+ assert.equal(s.effortLevel, 'high');+ assert.ok(s.hooks.Stop);+ // Hooks only: the statusline is a single per-session slot and taking it for every+ // repo would silently outrank the user's own.+ assert.equal(s.statusLine, undefined, 'no global statusline');+ assert.equal(s.permissions, undefined, 'no global allowlist');+});++test('an existing user-scope MCP server survives, and re-running converges', () => {+ const home = tmpRepo('cgmcp');+ writeFileSync(userMcpOf(home), JSON.stringify({ mcpServers: { paper: { command: 'paper' } } }, null, 2));++ installClaudeGlobal(home);+ const first = readJson(userMcpOf(home));+ assert.ok(first.mcpServers.paper, 'a foreign server is preserved');+ assert.ok(first.mcpServers.graft);++ const second = installClaudeGlobal(home);+ assert.ok(second.every((w) => w.action === 'unchanged'), `idempotent, got ${JSON.stringify(second)}`);+});++test('an unparseable file is reported, never overwritten', () => {+ const home = tmpRepo('cgbad');+ mkdirSync(join(home, '.claude'), { recursive: true });+ writeFileSync(settingsOf(home), '{ not json');+ writeFileSync(userMcpOf(home), '{ also not json');++ const w = installClaudeGlobal(home);+ assert.deepEqual(+ w.filter((x) => x.id !== 'claude-global-shim').map((x) => x.action),+ ['skipped-unparseable', 'skipped-unparseable'],+ );+ assert.equal(readFileSync(settingsOf(home), 'utf8'), '{ not json');+ assert.equal(readFileSync(userMcpOf(home), 'utf8'), '{ also not json');+});++test('--no-global writes nothing outside the repo', () => {+ const home = tmpRepo('cgnoglobal');+ const repo = tmpRepo('cgnoglobalrepo');++ const r = runInit(repo, { build: false, global: false, home });++ assert.deepEqual(r.global, []);+ assert.equal(existsSync(join(home, '.claude')), false);+ assert.equal(existsSync(userMcpOf(home)), false);+ // The repo half still happened.+ assert.ok(existsSync(join(repo, '.mcp.json')));+});++/* ------------------------------------------------------------------ *+ * the plan, and putting it back+ * ------------------------------------------------------------------ */++test('planInit reports the global writes so the picker can show them', () => {+ const home = tmpRepo('cgplan');+ const repo = tmpRepo('cgplanrepo');++ const claude = planInit(repo, { home, ids: ['claude'] })[0];+ const globals = claude.writes.filter((w) => w.scope === 'global').map((w) => w.path);++ assert.deepEqual(globals, claudeGlobalTargets(home).map((t) => t.path));+ assert.equal(globals.length, 3);+});++test('uninstall removes exactly what the global install added', () => {+ const home = tmpRepo('cgretract');+ const repo = tmpRepo('cgretractrepo');+ mkdirSync(join(home, '.claude'), { recursive: true });+ writeFileSync(settingsOf(home), JSON.stringify({ theme: 'light' }, null, 2));+ writeFileSync(userMcpOf(home), JSON.stringify({ mcpServers: { paper: { command: 'paper' } } }, null, 2));++ runInit(repo, { build: false, home });+ assert.ok(planRetract(repo, { home }).some((r) => r.path === shimOf(home)), 'the plan names the shim');++ runRetract(repo, { home, apply: true });++ assert.equal(existsSync(shimOf(home)), false, 'shim gone');+ const s = readJson(settingsOf(home));+ assert.equal(s.hooks, undefined, 'graft hooks gone');+ assert.equal(s.theme, 'light', "the user's own settings survive");+ const mcp = readJson(userMcpOf(home));+ assert.equal(mcp.mcpServers.graft, undefined, 'graft server gone');+ assert.ok(mcp.mcpServers.paper, 'the foreign server survives');+});++test('--no-global uninstall leaves the user-level copy in place', () => {+ const home = tmpRepo('cgretractkeep');+ const repo = tmpRepo('cgretractkeeprepo');++ runInit(repo, { build: false, home });+ runRetract(repo, { home, global: false, apply: true });++ assert.ok(existsSync(shimOf(home)));+ assert.ok(readJson(settingsOf(home)).hooks?.SessionStart);+});diff --git a/test/hosts-plan.test.ts b/test/hosts-plan.test.tsindex 2e40af2d..bc3129a4 100644--- a/test/hosts-plan.test.ts+++ b/test/hosts-plan.test.ts@@ -35,12 +35,27 @@ test('planInit writes nothing — it only describes', () => {assert.deepEqual(readdirSync(repo), []);});-test('claude writes are all repo-scoped — the claude layer never touches ~', () => {+/**+ * The claude layer used to be entirely repo-scoped. It no longer is, deliberately:+ * a repo-only install is invisible to a `git worktree add` of a repo whose+ * `.gitignore` covers `.mcp.json` / `.claude/settings.json`, and the user-level copy+ * is the only place a `.gitignore` cannot reach. See src/hosts/claude-global.ts.+ */+test('claude writes: five in the repo, three in ~ that no .gitignore can eat', () => {+ const home = fullHome();const repo = fresh();- const claude = planInit(repo, { home: fullHome(), ids: ['claude'] })[0];- assert.equal(claude.writes.length, 5);- assert.ok(claude.writes.every((w) => w.scope === 'repo'));- assert.ok(claude.writes.every((w) => w.path.startsWith(repo)));+ const claude = planInit(repo, { home, ids: ['claude'] })[0];++ const repoWrites = claude.writes.filter((w) => w.scope === 'repo');+ assert.equal(repoWrites.length, 5);+ assert.ok(repoWrites.every((w) => w.path.startsWith(repo)));++ const globals = claude.writes.filter((w) => w.scope === 'global');+ assert.deepEqual(+ globals.map((w) => toPosixPath(w.path.slice(home.length))).sort(),+ ['/.claude.json', '/.claude/helpers/graft-hooks.cjs', '/.claude/settings.json'],+ );+ assert.ok(globals.every((w) => !w.path.startsWith(repo)), 'nothing global lands in the repo');});test('the three ~/.codex writes are scoped global', () => {diff --git a/test/hosts-retract.test.ts b/test/hosts-retract.test.tsindex f5707152..dee31b8e 100644--- a/test/hosts-retract.test.ts+++ b/test/hosts-retract.test.ts@@ -206,7 +206,7 @@ test('planRetract is pure — it reports without touching anything', () => {test('a full init is fully retractable, and retraction is idempotent', () => {const d = fresh();- runInit(d, { build: false });+ runInit(d, { build: false, home: fresh() });runHostsInit(d, { agents: ['cursor', 'agents'], home: d, global: false });const first = changed(runRetract(d, { apply: true, global: false }));diff --git a/test/mcp-server.test.ts b/test/mcp-server.test.tsindex 8b37b42d..f0610e03 100644--- a/test/mcp-server.test.ts+++ b/test/mcp-server.test.ts@@ -1,10 +1,11 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { spawn } from 'node:child_process';-import { mkdtempSync } from 'node:fs';+import { execFileSync, spawn } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { once } from 'node:events';+import { buildGraph } from '../src/graph/build.js';async function rpc(messages: object[], dir: string, expected: number): Promise<any[]> {const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'mcp', dir], { stdio: ['pipe', 'pipe', 'pipe'] });@@ -44,20 +45,87 @@ test('initialize → tools/list → tools/call round-trip', async () => {assert.equal(init.result.protocolVersion, '2025-03-26');assert.ok(init.result.capabilities.tools);assert.equal(init.result.serverInfo.name, 'graft');+ // This dir has no graph and no parent checkout, so the server advertises+ // nothing: graft is registered at the user MCP scope now (hosts/claude-global.ts),+ // which starts it in every project the user opens, and six tool schemas charged+ // to a repo that never asked for graft is context spent for answers it cannot+ // give. See `advertised` in src/mcp/server.ts.const list = rs.find((r) => r.id === 2);- assert.deepEqual(list.result.tools.map((t: any) => t.name), [- 'graft_find_code',- 'graft_file_api',- 'graft_check_freshness',- 'graft_trace_calls',- 'graft_find_all',- 'graft_repo_map',- ]);+ assert.deepEqual(list.result.tools, []);+ // Not advertised is not the same as not callable — a client that calls anyway+ // still gets the soft error that names the fix.const call = rs.find((r) => r.id === 3);assert.equal(call.result.isError, true); // unbuilt repo → soft error contentassert.match(call.result.content[0].text, /graft build/);});+const ALL_TOOLS = [+ 'graft_find_code',+ 'graft_file_api',+ 'graft_check_freshness',+ 'graft_trace_calls',+ 'graft_find_all',+ 'graft_repo_map',+];++async function listTools(dir: string): Promise<string[]> {+ const rs = await rpc(+ [+ { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 't', version: '0' } } },+ { jsonrpc: '2.0', id: 2, method: 'tools/list' },+ ],+ dir,+ 2,+ );+ return rs.find((r) => r.id === 2).result.tools.map((t: any) => t.name);+}++test('a built repo advertises every tool', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'graft-mcpbuilt-'));+ mkdirSync(join(dir, 'src'), { recursive: true });+ writeFileSync(join(dir, 'src', 'math.ts'), 'export function add(a: number, b: number) {\n return a + b;\n}\n');+ await buildGraph(dir);++ assert.deepEqual(await listTools(dir), ALL_TOOLS);+});++test('a fresh worktree advertises every tool, on the strength of its parent', async () => {+ // The case the user-level registration exists for. `graft/` is gitignored, so+ // `git worktree add` never checks it out and this tree has no graph of its own —+ // it gets one from the parent on the first query (graph/seed.ts). Gating on this+ // tree alone would hide graft in exactly the worktree the user came to work in.+ const main = mkdtempSync(join(tmpdir(), 'graft-mcpwtmain-'));+ // Identity in the env, not the config: a CI runner has none, and blanking+ // GIT_CONFIG_GLOBAL removes any it had, so `git commit` would fail.+ const git = (...args: string[]): void =>+ execFileSync('git', args, {+ cwd: main,+ stdio: 'ignore',+ env: {+ ...process.env,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_SYSTEM: '/dev/null',+ GIT_AUTHOR_NAME: 'graft test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'graft test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ },+ });+ git('init', '-b', 'main');+ mkdirSync(join(main, 'src'), { recursive: true });+ writeFileSync(join(main, 'src', 'math.ts'), 'export function add(a: number, b: number) {\n return a + b;\n}\n');+ writeFileSync(join(main, '.gitignore'), 'graft/\n');+ git('add', '-A');+ git('commit', '-m', 'init');+ await buildGraph(main);++ const wt = join(mkdtempSync(join(tmpdir(), 'graft-mcpwt-')), 'feature');+ git('worktree', 'add', '--detach', wt, 'HEAD');+ assert.equal(existsSync(join(wt, 'graft')), false, 'the gitignored cache does not travel');++ assert.deepEqual(await listTools(wt), ALL_TOOLS);+});+test('initialize carries instructions — the layer that survives tool deferral', async () => {const dir = mkdtempSync(join(tmpdir(), 'graft-mcpsrv-instr-'));const rs = await rpc(