Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

graft init: pick what gets written instead of every detected agent

anirudhkumar-nanonets325fc4973e38
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 53f16bd9..68748f16 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,36 @@
# Changelog
+## 0.8.0
+
+### Changed
+
+- **`graft init` now asks which agents to wire, instead of writing files for every
+ agent it detects.** Detection keyed off directories in `$HOME`, so anyone who had
+ tried several coding CLIs got instruction files and MCP configs for all of them —
+ plain `graft init` effectively behaved like `--all-agents`. On a terminal it now
+ shows every known agent, which ones were detected, and the exact files each would
+ write, and wires only what you select (Claude Code pre-selected).
+
+ **Migration —** `graft init` in CI, a Dockerfile, or any non-interactive shell now
+ writes **nothing** and prints the command to run instead. Add `--yes` for the old
+ behaviour, or `--agents <ids>` to be explicit:
+
+ ```bash
+ graft init --yes # wire every detected agent (pre-0.8 default)
+ graft init --agents claude # or name them
+ ```
+
+### Added
+
+- **`graft init --dry-run`** — print every path `init` would touch, then exit without
+ writing. Out-of-repo writes get their own section.
+- **`graft init --no-global`** — skip every write outside the repo. Selecting the
+ `agents` host writes to `~/.codex/config.toml`, `~/.codex/hooks.json`, and
+ `~/.codex/hooks/graft/`; those are user-level and apply to every repo you open with
+ Codex, and previously nothing suppressed the `config.toml` write (`--no-hooks` only
+ covered the other two). These are now labelled `machine-wide` in the picker.
+- **`graft init --yes`** — wire every detected agent without prompting.
+
## 0.7.0
### Changed
diff --git a/README.md b/README.md
index 137e46a3..8fa0d9bb 100644
--- a/README.md
+++ b/README.md
@@ -61,7 +61,9 @@ npm install -g @nanonets/graft # install the CLI, once
graft init # build the graph + wire it into Claude Code
```
-That is the whole setup. `graft init` builds `graft/` from your code and drops a statusline and hooks into `.claude/`, so from the next session on Graft rides along in Claude Code: it pulls the matching nodes into each prompt and rebuilds the graph in the background after every turn. No daemon, no re-indexing to remember, nothing to run or maintain by default — the graph is just files.
+That is the whole setup. `graft init` asks which of your coding agents to wire up, builds `graft/` from your code, and drops a statusline and hooks into `.claude/`, so from the next session on Graft rides along in Claude Code: it pulls the matching nodes into each prompt and rebuilds the graph in the background after every turn. No daemon, no re-indexing to remember, nothing to run or maintain by default — the graph is just files.
+
+Nothing is written until you pick. Run `graft init --dry-run` to see every file it would touch first, or `graft init --agents claude` to skip the prompt and wire Claude Code alone.
`graft build` adds `graft/` to your `.gitignore` automatically — the graph is a local, regenerable cache (like `node_modules`), not something you commit. What you share is the wiring `init` dropped into `.claude/`; each teammate runs `graft build` to generate their own graph:
@@ -165,16 +167,33 @@ npx @nanonets/graft init
# Claude Code additionally gets the live statusline + hooks below
```
-`init` auto-detects which agents are present (via their config directories) and writes a marker-fenced Graft section into each one's shared instruction file — `AGENTS.md` (Codex, OpenCode and other CLIs that read it), `GEMINI.md`, `.github/copilot-instructions.md` — or a wholly-owned rule/skill file for the agents that use one — `.cursor/rules/graft.mdc`, `.kiro/steering/graft.md`, `.windsurf/rules/graft.md`, `.adal/skills/graft/SKILL.md` for [AdaL](https://adal.sylph.ai) (progressive-disclosure skill, same shape as the Claude Code skill below). Re-running only updates Graft's own section (or replaces the owned file) and never touches the rest of your content.
+On a terminal, `init` shows you every agent it knows about — flagging the ones it detected (via their config directories) and listing the exact files each would write — and wires only the ones you select. Claude Code is pre-selected; nothing else is. Selected agents get a marker-fenced Graft section in their shared instruction file — `AGENTS.md` (Codex, OpenCode and other CLIs that read it), `GEMINI.md`, `.github/copilot-instructions.md` — or a wholly-owned rule/skill file for the agents that use one — `.cursor/rules/graft.mdc`, `.kiro/steering/graft.md`, `.windsurf/rules/graft.md`, `.adal/skills/graft/SKILL.md` for [AdaL](https://adal.sylph.ai) (progressive-disclosure skill, same shape as the Claude Code skill below). Re-running only updates Graft's own section (or replaces the owned file) and never touches the rest of your content.
+
+With no TTY to prompt on — CI, a Dockerfile, a piped shell — `init` writes **nothing** and prints the command to run instead. Pass `--agents <ids>` or `--yes` to make a scripted run explicit.
| Flag | Effect |
|---|---|
-| `--agents <ids...>` | wire only these — ids: `agents`, `cursor`, `gemini`, `copilot`, `kiro`, `windsurf`, `adal`, `claude` |
+| `--agents <ids...>` | wire only these, no prompt — ids: `agents`, `cursor`, `gemini`, `copilot`, `kiro`, `windsurf`, `adal`, `claude` |
+| `--yes`, `-y` | skip the prompt and wire every **detected** agent |
+| `--dry-run` | print every file `init` would touch, then exit without writing |
| `--all-agents` | write instruction files for every known agent, detected or not |
| `--no-agents` | Claude Code wiring only; skip other agents |
| `--list-agents` | print the known agent ids and exit |
| `--no-mcp` | skip MCP server registration |
| `--no-hooks` | skip hook installation |
+| `--no-global` | skip writes outside this repo (the `~/.codex/` entries below) |
+
+#### Writes outside the repo
+
+Selecting the `agents` host also touches your **user-level** Codex config, when `~/.codex/` exists:
+
+| Path | What changes |
+|---|---|
+| `~/.codex/config.toml` | registers the Graft MCP server (`[mcp_servers.graft]`) |
+| `~/.codex/hooks/graft/graft-hooks.cjs` | the post-edit hook shim |
+| `~/.codex/hooks.json` | a `PostToolUse` entry matching `Write\|Edit\|MultiEdit` |
+
+Both configs are user-level, so they apply to **every** repo you open with Codex, not just this one. The picker labels these `machine-wide`, `--dry-run` lists them in their own section, and `--no-global` skips them while still wiring `AGENTS.md`.
### MCP server
@@ -244,9 +263,12 @@ graft check --json # print the drift report as JSON
graft viz [dir] # see the graph: serves an interactive viewer on localhost
graft viz --port 5000 --no-open # pick a port; don't auto-open the browser
-graft init [dir] # wire Graft into the coding agents detected in this repo (Claude Code always gets full hooks + statusline + MCP)
+graft init [dir] # pick which agents to wire (prompts on a terminal; writes nothing until you choose)
+graft init --dry-run # list every file it would touch, then exit
+graft init --agents cursor kiro # wire only these agents, no prompt (ids: agents, cursor, gemini, copilot, kiro, windsurf, adal, claude)
+graft init --yes # no prompt; wire every detected agent
+graft init --no-global # skip writes outside this repo (~/.codex/ config + hooks)
graft init --no-build # wire the files only; don't build the graph
-graft init --agents cursor kiro # wire only these agents (ids: agents, cursor, gemini, copilot, kiro, windsurf, adal, claude)
graft init --all-agents # wire every known agent, detected or not
graft init --list-agents # list known agent ids and exit
diff --git a/src/claude/init.ts b/src/claude/init.ts
index df118375..70535fdc 100644
--- a/src/claude/init.ts
+++ b/src/claude/init.ts
@@ -1,11 +1,30 @@
import { mkdirSync, writeFileSync, readFileSync, existsSync, chmodSync } from 'node:fs';
-import { join } from 'node:path';
+import { join, dirname } from 'node:path';
import { execFileSync } from 'node:child_process';
import { mergeGraftSettings } from './settings-merge.js';
import { statuslineShim, hooksShim } from './shim-template.js';
import { skillTemplate } from './skill-template.js';
import { claudeDistDir } from './paths.js';
import { mergeJsonKey, SERVER_ENTRY, type McpWrite } from '../hosts/mcp-config.js';
+import type { PlannedWrite } from '../hosts/plan.js';
+
+/**
+ * The files `runInit` writes — pure, no writes, so `--dry-run` and the picker
+ * can report them up front. All repo-local: the Claude Code layer never writes
+ * outside the project.
+ */
+export function claudeTargets(dir: string): PlannedWrite[] {
+ const t = (path: string, what: string, kind: PlannedWrite['kind'] = 'claude'): PlannedWrite =>
+ ({ hostId: 'claude', id: 'claude', path, scope: 'repo', kind, what });
+ return [
+ t(join(dir, '.claude', 'settings.json'), 'graft statusline + hook blocks'),
+ t(join(dir, '.claude', 'helpers', 'graft-statusline.cjs'), 'statusline shim'),
+ t(join(dir, '.claude', 'helpers', 'graft-hooks.cjs'), 'hooks shim'),
+ t(join(dir, '.claude', 'skills', 'graft', 'SKILL.md'), 'graft skill'),
+ // Tagged 'mcp' so the picker doesn't label Claude Code as having no MCP.
+ t(join(dir, '.mcp.json'), 'mcpServers.graft', 'mcp'),
+ ];
+}
export interface InitResult {
settingsPath: string;
@@ -18,32 +37,33 @@ export interface InitResult {
}
export function runInit(dir: string, opts: { build?: boolean; cliPath?: string } = {}): InitResult {
- const helpersDir = join(dir, '.claude', 'helpers');
- mkdirSync(helpersDir, { recursive: true });
+ // 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);
+
+ mkdirSync(dirname(statusline), { recursive: true });
- const settingsPath = join(dir, '.claude', 'settings.json');
+ const settingsPath = settings;
let existing: Record<string, any> = {};
try { existing = JSON.parse(readFileSync(settingsPath, 'utf8')); } catch { /* none/invalid → start fresh */ }
const { merged, warnings } = mergeGraftSettings(existing);
writeFileSync(settingsPath, `${JSON.stringify(merged, null, 2)}\n`);
- const sl = join(helpersDir, 'graft-statusline.cjs');
- const hk = join(helpersDir, 'graft-hooks.cjs');
+ const sl = statusline;
+ const hk = hooks;
const bakedDir = claudeDistDir(); // absolute <pkg>/dist/claude — the shims' primary resolution path
writeFileSync(sl, statuslineShim(bakedDir)); chmodSync(sl, 0o755);
writeFileSync(hk, hooksShim(bakedDir)); chmodSync(hk, 0o755);
// Install the graft skill — the piece that redirects the agent to graft/ before it
// greps source. Overwritten each run (graft owns this file), like the shims above.
- const skillDir = join(dir, '.claude', 'skills', 'graft');
- mkdirSync(skillDir, { recursive: true });
- const skillPath = join(skillDir, 'SKILL.md');
+ const skillPath = skill;
+ mkdirSync(dirname(skillPath), { recursive: true });
writeFileSync(skillPath, skillTemplate());
// Register the graft MCP server in the project's .mcp.json so Claude Code
// exposes graft_ask/graft_callers/etc. as tools — the same keyed merge the
// other hosts use (existing servers preserved; unparseable files skipped).
- const mcp = mergeJsonKey('claude', join(dir, '.mcp.json'), 'mcpServers', SERVER_ENTRY);
+ const mcp = mergeJsonKey('claude', mcpTarget, 'mcpServers', SERVER_ENTRY);
let built = false;
const wiring = join(dir, 'graft', '.graph', 'wiring.json');
diff --git a/src/cli-picker.ts b/src/cli-picker.ts
new file mode 100644
index 00000000..1f454472
--- /dev/null
+++ b/src/cli-picker.ts
@@ -0,0 +1,309 @@
+/**
+ * `graft init`'s agent picker and `--dry-run` plan printer.
+ *
+ * Split three ways so the logic is testable without a TTY: `renderPicker` and
+ * `reducePicker` are pure, `runPicker` is the only part that touches stdin.
+ */
+import { relative, dirname, sep } from 'node:path';
+import { createInterface } from 'node:readline';
+import type { HostPlan, PlannedWrite } from './hosts/plan.js';
+
+const indigo = (s: string) => `\x1b[38;2;84;111;255m${s}\x1b[0m`;
+const muted = (s: string) => `\x1b[38;5;244m${s}\x1b[0m`;
+const amber = (s: string) => `\x1b[38;5;179m${s}\x1b[0m`;
+
+/** `/Users/me/.codex/x` → `~/.codex/x`, for display only. */
+export function tilde(path: string, home: string): string {
+ return path === home || path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path;
+}
+
+/** Deepest directory containing every given path. */
+function commonDir(paths: string[]): string {
+ const split = paths.map((p) => dirname(p).split(sep));
+ const first = split[0] ?? [];
+ let i = 0;
+ while (i < first.length && split.every((s) => s[i] === first[i])) i++;
+ return first.slice(0, i).join(sep);
+}
+
+/**
+ * One-line summary of what selecting a host writes: repo-relative paths, then
+ * a count for anything landing outside the repo — those are the writes users
+ * can't see in `git status`, so they get named explicitly.
+ */
+export function describeWrites(
+ writes: PlannedWrite[],
+ repo: string,
+ home: string,
+ maxShown = 3,
+): string {
+ const repoPaths = writes.filter((w) => w.scope === 'repo').map((w) => relative(repo, w.path));
+ const globals = writes.filter((w) => w.scope === 'global');
+ const parts: string[] = [];
+ if (repoPaths.length > 0) {
+ parts.push(
+ repoPaths.length <= maxShown
+ ? repoPaths.join(', ')
+ : `${repoPaths.slice(0, maxShown).join(', ')} +${repoPaths.length - maxShown} more`,
+ );
+ }
+ if (globals.length > 0) {
+ const where = tilde(commonDir(globals.map((w) => w.path)), home);
+ parts.push(`+ ${globals.length} in ${where}/ (machine-wide)`);
+ }
+ if (!writes.some((w) => w.kind === 'mcp')) parts.push('no MCP');
+ return parts.join(' · ');
+}
+
+export interface PickerRow {
+ id: string;
+ detected: boolean;
+ summary: string;
+ /** True when selecting this host writes outside the repo. */
+ hasGlobal: boolean;
+}
+
+export interface PickerState {
+ rows: PickerRow[];
+ cursor: number;
+ checked: ReadonlySet<string>;
+ done: boolean;
+ aborted: boolean;
+}
+
+/** Claude Code starts checked — it's the deep integration — everything else off. */
+export function initialPickerState(plan: HostPlan[], repo: string, home: string): PickerState {
+ return {
+ rows: plan.map((p) => ({
+ id: p.id,
+ detected: p.detected,
+ summary: describeWrites(p.writes, repo, home),
+ hasGlobal: p.writes.some((w) => w.scope === 'global'),
+ })),
+ cursor: 0,
+ checked: new Set(plan.some((p) => p.id === 'claude') ? ['claude'] : []),
+ done: false,
+ aborted: false,
+ };
+}
+
+export type PickerKey = 'up' | 'down' | 'space' | 'all' | 'enter' | 'abort';
+
+export const KEY_UP = '\x1b[A';
+export const KEY_DOWN = '\x1b[B';
+export const KEY_ESC = '\x1b';
+export const KEY_CTRL_C = '\x03';
+
+/** A single keypress → the key we act on, or null to ignore. */
+export function keyOf(chunk: string): PickerKey | null {
+ switch (chunk) {
+ case KEY_UP: case 'k': return 'up';
+ case KEY_DOWN: case 'j': return 'down';
+ case ' ': return 'space';
+ case 'a': return 'all';
+ case '\r': case '\n': return 'enter';
+ case KEY_ESC: case KEY_CTRL_C: case 'q': return 'abort';
+ default: return null;
+ }
+}
+
+/**
+ * Split a raw stdin chunk into keypresses. A terminal is free to batch bytes —
+ * held keys, pasted input, or a pty replaying a script all arrive as one chunk —
+ * so a chunk is a sequence, never a single key. CSI sequences (ESC '[' final)
+ * are consumed whole so an arrow key never reads as a bare ESC (i.e. abort).
+ */
+export function keysOf(chunk: string): PickerKey[] {
+ const keys: PickerKey[] = [];
+ let i = 0;
+ while (i < chunk.length) {
+ let token: string;
+ if (chunk[i] === KEY_ESC && chunk[i + 1] === '[') {
+ // ESC '[' then optional parameter bytes, then one final byte @-~.
+ let j = i + 2;
+ while (j < chunk.length && !/[@-~]/.test(chunk[j])) j++;
+ token = chunk.slice(i, Math.min(j + 1, chunk.length));
+ } else {
+ token = chunk[i];
+ }
+ i += token.length;
+ const key = keyOf(token);
+ if (key !== null) keys.push(key);
+ }
+ return keys;
+}
+
+export function reducePicker(state: PickerState, key: PickerKey): PickerState {
+ const n = state.rows.length;
+ switch (key) {
+ case 'up':
+ return { ...state, cursor: (state.cursor - 1 + n) % n };
+ case 'down':
+ return { ...state, cursor: (state.cursor + 1) % n };
+ case 'space': {
+ const next = new Set(state.checked);
+ const id = state.rows[state.cursor].id;
+ if (next.has(id)) next.delete(id); else next.add(id);
+ return { ...state, checked: next };
+ }
+ case 'all': {
+ const allOn = state.rows.every((r) => state.checked.has(r.id));
+ return { ...state, checked: new Set(allOn ? [] : state.rows.map((r) => r.id)) };
+ }
+ case 'enter':
+ return { ...state, done: true };
+ case 'abort':
+ return { ...state, aborted: true };
+ }
+}
+
+export function renderPicker(state: PickerState, tty = true): string {
+ const dim = tty ? muted : (s: string) => s;
+ const hot = tty ? indigo : (s: string) => s;
+ const warn = tty ? amber : (s: string) => s;
+
+ // Pad on the plain label so the summary column lines up regardless of which
+ // rows carry the '(not detected)' tag or the cursor's colour codes.
+ const label = (r: PickerRow) => `${r.id}${r.detected ? '' : ' (not detected)'}`;
+ const width = Math.max(...state.rows.map((r) => label(r).length));
+ const lines = ['graft init — select what to wire into this repo:', ''];
+ for (const [i, row] of state.rows.entries()) {
+ const here = i === state.cursor;
+ const box = state.checked.has(row.id) ? '[x]' : '[ ]';
+ const gap = ' '.repeat(width - label(row).length);
+ const name = here ? hot(row.id) : row.id;
+ const tag = row.detected ? '' : dim(' (not detected)');
+ const summary = row.hasGlobal ? warn(row.summary) : dim(row.summary);
+ lines.push(`${here ? '›' : ' '} ${box} ${name}${tag}${gap} ${summary}`);
+ }
+ lines.push('', dim('↑↓ move · space toggle · a all · enter confirm · esc cancel'));
+ return lines.join('\n');
+}
+
+/** Ids in plan order, so output ordering never depends on toggle order. */
+export function pickedIds(state: PickerState): string[] {
+ return state.rows.filter((r) => state.checked.has(r.id)).map((r) => r.id);
+}
+
+/**
+ * Drive the picker on a real terminal. Resolves the chosen ids, or null if the
+ * user cancelled — in which case the caller must write nothing.
+ */
+export async function runPicker(
+ plan: HostPlan[],
+ repo: string,
+ home: string,
+): Promise<string[] | null> {
+ let state = initialPickerState(plan, repo, home);
+ const out = process.stderr;
+ const stdin = process.stdin;
+
+ let lastLines = 0;
+ const draw = () => {
+ if (lastLines > 0) out.write(`\x1b[${lastLines}A\x1b[0J`);
+ const text = renderPicker(state);
+ out.write(`${text}\n`);
+ lastLines = text.split('\n').length;
+ };
+
+ const rl = createInterface({ input: stdin });
+ const wasRaw = Boolean(stdin.isRaw);
+ stdin.setRawMode?.(true);
+ stdin.resume();
+ draw();
+
+ try {
+ return await new Promise<string[] | null>((resolve) => {
+ const finish = (onData: (b: Buffer) => void) => {
+ stdin.off('data', onData);
+ draw();
+ resolve(state.aborted ? null : pickedIds(state));
+ };
+ const onData = (buf: Buffer) => {
+ const keys = keysOf(buf.toString('utf8'));
+ if (keys.length === 0) return;
+ for (const key of keys) {
+ state = reducePicker(state, key);
+ if (state.done || state.aborted) {
+ finish(onData);
+ return;
+ }
+ }
+ draw();
+ };
+ stdin.on('data', onData);
+ // A closed stdin (piped input that ran out) must not hang the prompt.
+ stdin.once('end', () => { state = { ...state, aborted: true }; finish(onData); });
+ });
+ } finally {
+ stdin.setRawMode?.(wasRaw);
+ rl.close();
+ stdin.pause();
+ }
+}
+
+/**
+ * Shown when there's no TTY to prompt on and no flag saying what to wire.
+ * Writing nothing is deliberate: a scripted run shouldn't get files for every
+ * agent the machine happens to have installed.
+ */
+export function formatNonInteractiveHelp(detectedIds: string[]): string {
+ const list = detectedIds.length > 0 ? detectedIds.join(", ") : "none";
+ const examples: [string, string][] = [
+ ...(detectedIds.length > 0
+ ? ([
+ [`graft init --agents ${detectedIds.join(" ")}`, "wire these"],
+ ["graft init --yes", "same, without spelling them out"],
+ ] as [string, string][])
+ : []),
+ ["graft init --agents claude", "Claude Code only"],
+ ["graft init --dry-run", "list every file first"],
+ ];
+ const width = Math.max(...examples.map(([cmd]) => cmd.length));
+ return [
+ "graft init: no TTY to prompt on, and no --agents/--yes given — nothing written.",
+ `detected: ${list}`,
+ "",
+ ...examples.map(([cmd, note]) => ` ${cmd.padEnd(width)} # ${note}`),
+ ].join("\n");
+}
+
+/**
+ * `--dry-run` output: every path init would touch, repo writes first, then a
+ * separate section for anything outside the repo.
+ */
+export function formatPlan(
+ plan: HostPlan[],
+ ids: string[],
+ repo: string,
+ home: string,
+ tty = Boolean(process.stderr.isTTY),
+): string {
+ const dim = tty ? muted : (s: string) => s;
+ const warn = tty ? amber : (s: string) => s;
+ const writes = plan.filter((p) => ids.includes(p.id)).flatMap((p) => p.writes);
+ if (writes.length === 0) return 'would write — nothing (no agents selected)';
+
+ const pad = (rows: PlannedWrite[], f: (p: string) => string) => {
+ const w = Math.max(...rows.map((r) => f(r.path).length));
+ return rows.map((r) => ` ${f(r.path).padEnd(w)} ${dim(r.what)}`);
+ };
+
+ const lines: string[] = [];
+ const repoWrites = writes.filter((w) => w.scope === 'repo');
+ if (repoWrites.length > 0) {
+ lines.push('would write — this repo:', ...pad(repoWrites, (p) => relative(repo, p)));
+ }
+ const globalWrites = writes.filter((w) => w.scope === 'global');
+ if (globalWrites.length > 0) {
+ if (lines.length) lines.push('');
+ lines.push(
+ warn('would write — your machine, affects ALL repos:'),
+ ...pad(globalWrites, (p) => tilde(p, home)),
+ '',
+ dim('suppress the out-of-repo writes with --no-global'),
+ );
+ }
+ lines.push('', dim('nothing was written (--dry-run)'));
+ return lines.join('\n');
+}
diff --git a/src/cli.ts b/src/cli.ts
index 16161bc4..969cb372 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -28,6 +28,9 @@ import {
runWorkspaceMap,
} from "./graph/workspace-cli.js";
import { formatInitEpilogue } from "./cli-epilogue.js";
+import { planInit } from "./hosts/plan.js";
+import { formatNonInteractiveHelp, formatPlan, runPicker } from "./cli-picker.js";
+import { homedir } from "node:os";
import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, runUpgrade } from "./cli-meta.js";
const program = new Command();
@@ -432,7 +435,10 @@ program
.option("--list-agents", "list known agent ids and exit")
.option("--no-mcp", "skip MCP server registration for other agents")
.option("--no-hooks", "skip hook installation for other agents")
- .action((dir: string, opts: { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean }) => {
+ .option("--dry-run", "print every file init would touch, then exit without writing")
+ .option("-y, --yes", "skip the picker and wire every detected agent (the pre-0.8 default)")
+ .option("--no-global", "skip writes outside this repo (the ~/.codex/ config + hooks)")
+ .action(async (dir: string, opts: { build?: boolean; agents?: string[]; allAgents?: boolean; listAgents?: boolean; mcp?: boolean; hooks?: boolean; dryRun?: boolean; yes?: boolean; global?: boolean }) => {
if (opts.listAgents) {
for (const id of [...hostIds(), "claude"]) console.log(id);
return;
@@ -449,7 +455,42 @@ program
}
}
- const wantClaude = !explicit || explicit.includes("claude");
+ // Which agents to wire, decided before anything is written. Explicit flags
+ // win; otherwise prompt on a TTY, and on a pipe write nothing rather than
+ // guessing (pre-0.8 this silently wired every agent the machine had ever
+ // installed — see --yes to get that back).
+ const home = homedir();
+ const plan = planInit(repo, { home });
+ const detectedIds = plan.filter((p) => p.detected).map((p) => p.id);
+ const noAgents = (opts as { agents?: unknown }).agents === false;
+
+ let ids: string[];
+ if (explicit) ids = explicit;
+ else if (opts.allAgents) ids = plan.map((p) => p.id);
+ else if (noAgents) ids = ["claude"];
+ else if (opts.yes || opts.dryRun) ids = detectedIds;
+ else if (process.stdin.isTTY && process.stderr.isTTY) {
+ const picked = await runPicker(plan, repo, home);
+ if (picked === null) {
+ console.error("· cancelled — nothing written");
+ return;
+ }
+ ids = picked;
+ } else {
+ console.error(formatNonInteractiveHelp(detectedIds));
+ return;
+ }
+
+ if (opts.dryRun) {
+ console.error(formatPlan(plan, ids, repo, home));
+ return;
+ }
+ if (ids.length === 0) {
+ console.error("· no agents selected — nothing written");
+ return;
+ }
+
+ const wantClaude = ids.includes("claude");
if (wantClaude) {
const cliPath = fileURLToPath(import.meta.url);
@@ -467,19 +508,21 @@ program
for (const w of res.warnings) console.error(`⚠ ${w}`);
}
- const skipOthers = (opts as { agents?: unknown }).agents === false;
- if (!skipOthers) {
+ // `ids` is already resolved, so hosts init is always driven by an explicit
+ // list — never by its own detection fallback.
+ const others = ids.filter((id) => id !== "claude");
+ if (others.length > 0) {
const r = runHostsInit(repo, {
- agents: explicit?.filter((id) => id !== "claude"),
- all: opts.allAgents,
+ agents: others,
+ home,
mcp: opts.mcp,
hooks: opts.hooks,
+ global: opts.global,
});
for (const w of r.written) console.error(`✓ ${w.id}: ${w.path} (${w.action})`);
- if (!explicit && !opts.allAgents && r.written.length === 0)
- console.error("· no other agents detected (see --list-agents / --all-agents)");
for (const m of r.mcp) console.error(`✓ mcp ${m.id}: ${m.path} (${m.action})`);
for (const h of r.hooks) console.error(`✓ hook ${h.id}: ${h.path} (${h.action})`);
+ if (opts.global === false) console.error("· skipped out-of-repo writes (--no-global)");
}
const globalOpts = program.opts<{ dir?: string }>();
diff --git a/src/hosts/codex-hooks.ts b/src/hosts/codex-hooks.ts
index a0dd30c1..92f96ccc 100644
--- a/src/hosts/codex-hooks.ts
+++ b/src/hosts/codex-hooks.ts
@@ -7,6 +7,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, statSync
import { dirname, join } from 'node:path';
import { hooksShim } from '../claude/shim-template.js';
import { claudeDistDir } from '../claude/paths.js';
+import type { PlannedWrite } from './plan.js';
export interface HookWrite {
id: string;
@@ -18,6 +19,29 @@ function dirExists(p: string): boolean {
try { return statSync(p).isDirectory(); } catch { return false; }
}
+/**
+ * The files installing the Codex hook would touch — pure, no writes. Both live
+ * under `~/.codex`, so both are scoped 'global': the PostToolUse entry fires on
+ * every edit in every repo opened with Codex, not just this one. Empty when the
+ * CLI isn't installed, mirroring `installCodexHooks`' early return.
+ */
+export function hookTargets(home: string): PlannedWrite[] {
+ const base = join(home, '.codex');
+ if (!dirExists(base)) return [];
+ return [
+ {
+ hostId: 'agents', id: 'codex-hook-shim',
+ path: join(base, 'hooks', 'graft', 'graft-hooks.cjs'),
+ scope: 'global', kind: 'hook', what: 'post-edit hook shim',
+ },
+ {
+ hostId: 'agents', id: 'codex-hooks',
+ path: join(base, 'hooks.json'),
+ scope: 'global', kind: 'hook', what: 'PostToolUse: Write|Edit|MultiEdit',
+ },
+ ];
+}
+
function writeOwned(id: string, path: string, content: string, mode?: number): HookWrite {
const existed = existsSync(path);
if (existed && readFileSync(path, 'utf8') === content) {
@@ -35,13 +59,13 @@ function isGraftEntry(entry: unknown): boolean {
}
export function installCodexHooks(home: string): HookWrite[] {
- const base = join(home, '.codex');
- if (!dirExists(base)) return [];
+ const targets = hookTargets(home);
+ if (targets.length === 0) return [];
- const shimPath = join(base, 'hooks', 'graft', 'graft-hooks.cjs');
+ const shimPath = targets[0].path;
const shimWrite = writeOwned('codex-hook-shim', shimPath, hooksShim(claudeDistDir()), 0o755);
- const cfgPath = join(base, 'hooks.json');
+ const cfgPath = targets[1].path;
let root: Record<string, any> = {};
const existed = existsSync(cfgPath);
if (existed) {
diff --git a/src/hosts/init.ts b/src/hosts/init.ts
index 1a606291..2da93202 100644
--- a/src/hosts/init.ts
+++ b/src/hosts/init.ts
@@ -36,7 +36,15 @@ function writeOwned(path: string, content: string): string {
export function runHostsInit(
repo: string,
- opts: { agents?: string[]; all?: boolean; home?: string; mcp?: boolean; hooks?: boolean } = {},
+ opts: {
+ agents?: string[];
+ all?: boolean;
+ home?: string;
+ mcp?: boolean;
+ hooks?: boolean;
+ /** false → skip every write outside the repo (the ~/.codex/ targets). */
+ global?: boolean;
+ } = {},
): HostsInitResult {
const home = opts.home ?? homedir();
const probe = probeFor(home, repo);
@@ -63,9 +71,13 @@ export function runHostsInit(
written.push({ id: host.id, path, action });
}
const skipped = HOSTS.filter((h) => !selected.includes(h)).map((h) => h.id);
- const mcp = opts.mcp === false ? [] : registerMcpConfigs(repo, selected.map((h) => h.id), { home });
+ const mcp =
+ opts.mcp === false
+ ? []
+ : registerMcpConfigs(repo, selected.map((h) => h.id), { home, global: opts.global });
+ // Every hook target is user-level, so --no-global suppresses the lot.
const hooks =
- opts.hooks === false || !selected.some((h) => h.id === 'agents')
+ opts.hooks === false || opts.global === false || !selected.some((h) => h.id === 'agents')
? []
: installCodexHooks(home);
return { written, skipped, unknown, mcp, hooks };
diff --git a/src/hosts/mcp-config.ts b/src/hosts/mcp-config.ts
index 578eec8d..248d0843 100644
--- a/src/hosts/mcp-config.ts
+++ b/src/hosts/mcp-config.ts
@@ -2,10 +2,15 @@
* Register the graft MCP server in each host's config.
* JSON hosts get a keyed merge (other servers preserved; unparseable files
* are never rewritten). The TOML host gets an append-if-absent section.
+ *
+ * `mcpTargets()` is the pure "which files would this touch" half, so `graft
+ * init --dry-run` and the picker can report paths without writing;
+ * `registerMcpConfigs()` walks that same list to do the writing.
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';
+import type { PlannedWrite } from './plan.js';
export interface McpWrite {
id: string;
@@ -13,6 +18,15 @@ export interface McpWrite {
action: 'created' | 'updated' | 'unchanged' | 'skipped-unparseable';
}
+/** A planned MCP write, plus the detail needed to actually perform it. */
+export interface McpTarget extends PlannedWrite {
+ format: 'json' | 'toml';
+ /** JSON only: the top-level key holding the server map. */
+ topKey?: string;
+ /** JSON only: the server entry to merge in under `graft`. */
+ entry?: object;
+}
+
export const SERVER_ENTRY = { command: 'npx', args: ['-y', '@nanonets/graft', 'mcp'] };
const OPENCODE_ENTRY = { type: 'local', command: ['npx', '-y', '@nanonets/graft', 'mcp'], enabled: true };
@@ -53,35 +67,70 @@ function upsertCodexToml(id: string, path: string): McpWrite {
return { id, path, action: existed ? 'updated' : 'created' };
}
-export function registerMcpConfigs(
+function jsonTarget(
+ hostId: string,
+ id: string,
+ path: string,
+ topKey: string,
+ entry: object,
+ scope: PlannedWrite['scope'] = 'repo',
+): McpTarget {
+ return { hostId, id, path, scope, kind: 'mcp', what: `${topKey}.graft`, format: 'json', topKey, entry };
+}
+
+/**
+ * The MCP config files selecting these hosts would touch — pure, no writes.
+ * Codex's target is the user-level `~/.codex/config.toml`, so it is scoped
+ * 'global': registering there affects every project on the machine.
+ */
+export function mcpTargets(
repo: string,
ids: string[],
opts: { home?: string } = {},
-): McpWrite[] {
+): McpTarget[] {
const home = opts.home ?? homedir();
- const out: McpWrite[] = [];
+ const out: McpTarget[] = [];
for (const id of ids) {
switch (id) {
case 'cursor':
- out.push(mergeJsonKey(id, join(repo, '.cursor', 'mcp.json'), 'mcpServers', SERVER_ENTRY));
+ out.push(jsonTarget(id, id, join(repo, '.cursor', 'mcp.json'), 'mcpServers', SERVER_ENTRY));
break;
case 'gemini':
- out.push(mergeJsonKey(id, join(repo, '.gemini', 'settings.json'), 'mcpServers', SERVER_ENTRY));
+ out.push(jsonTarget(id, id, join(repo, '.gemini', 'settings.json'), 'mcpServers', SERVER_ENTRY));
break;
case 'kiro':
- out.push(mergeJsonKey(id, join(repo, '.kiro', 'settings', 'mcp.json'), 'mcpServers', SERVER_ENTRY));
+ out.push(jsonTarget(id, id, join(repo, '.kiro', 'settings', 'mcp.json'), 'mcpServers', SERVER_ENTRY));
break;
case 'agents':
+ // Guarded on the CLI actually being installed, so a plan only ever
+ // lists files a real run would touch.
if (dirExists(join(home, '.codex'))) {
- out.push(upsertCodexToml('codex', join(home, '.codex', 'config.toml')));
+ out.push({
+ hostId: id, id: 'codex', path: join(home, '.codex', 'config.toml'),
+ scope: 'global', kind: 'mcp', what: '[mcp_servers.graft]', format: 'toml',
+ });
}
if (dirExists(join(home, '.config', 'opencode'))) {
- out.push(mergeJsonKey('opencode', join(repo, 'opencode.json'), 'mcp', OPENCODE_ENTRY));
+ out.push(jsonTarget(id, 'opencode', join(repo, 'opencode.json'), 'mcp', OPENCODE_ENTRY));
}
break;
default:
- break; // copilot / windsurf / claude: no MCP target in this phase
+ break; // copilot / windsurf / adal: no MCP target in this phase
}
}
return out;
}
+
+export function registerMcpConfigs(
+ repo: string,
+ ids: string[],
+ opts: { home?: string; global?: boolean } = {},
+): McpWrite[] {
+ return mcpTargets(repo, ids, opts)
+ .filter((t) => opts.global !== false || t.scope !== 'global')
+ .map((t) =>
+ t.format === 'toml'
+ ? upsertCodexToml(t.id, t.path)
+ : mergeJsonKey(t.id, t.path, t.topKey!, t.entry!),
+ );
+}
diff --git a/src/hosts/plan.ts b/src/hosts/plan.ts
new file mode 100644
index 00000000..8edc30bb
--- /dev/null
+++ b/src/hosts/plan.ts
@@ -0,0 +1,90 @@
+/**
+ * What `graft init` *would* write, computed before anything is written.
+ *
+ * The picker and `--dry-run` both need the exact path list up front, so every
+ * writer in the init path (instruction files, MCP configs, hooks, the Claude
+ * Code layer) exposes a pure `*Targets()` function and then consumes that same
+ * list to do its writing. One source of truth, so a plan can never drift from
+ * what a real run touches.
+ */
+import { join } from 'node:path';
+import { homedir } from 'node:os';
+import { statSync } from 'node:fs';
+import { HOSTS, detectHosts, type DetectProbe, type HostTarget } from './registry.js';
+import { mcpTargets } from './mcp-config.js';
+import { hookTargets } from './codex-hooks.js';
+import { claudeTargets } from '../claude/init.js';
+
+/** Where a write lands. 'global' = outside the repo, affects every project. */
+export type WriteScope = 'repo' | 'global';
+
+export interface PlannedWrite {
+ /** The selectable host this write belongs to ('claude', 'agents', 'cursor', …). */
+ hostId: string;
+ /** Reporting id — differs from hostId where one host writes several configs
+ * (the 'agents' host covers both 'codex' and 'opencode'). */
+ id: string;
+ path: string;
+ scope: WriteScope;
+ kind: 'instruction' | 'mcp' | 'hook' | 'claude';
+ /** Short human label for what changes in that file. */
+ what: string;
+}
+
+export interface HostPlan {
+ id: string;
+ name: string;
+ detected: boolean;
+ writes: PlannedWrite[];
+}
+
+function probeFor(home: string, repo: string): DetectProbe {
+ return {
+ home, repo,
+ dirExists: (p) => { try { return statSync(p).isDirectory(); } catch { return false; } },
+ };
+}
+
+/** The instruction-file write for one host, derived from its registry entry. */
+function instructionTarget(repo: string, host: HostTarget): PlannedWrite {
+ return {
+ hostId: host.id,
+ id: host.id,
+ path: join(repo, host.relPath),
+ scope: 'repo',
+ kind: 'instruction',
+ what: host.kind === 'owned' ? 'graft-owned file' : 'fenced graft section',
+ };
+}
+
+/**
+ * Every host graft can wire, each with the full set of files selecting it would
+ * touch. Claude Code comes first — it's the deep integration and the picker's
+ * default. `ids`, when given, restricts the plan to those hosts.
+ */
+export function planInit(repo: string, opts: { home?: string; ids?: string[] } = {}): HostPlan[] {
+ const home = opts.home ?? homedir();
+ const probe = probeFor(home, repo);
+ const detected = new Set(detectHosts(probe).map((h) => h.id));
+
+ const plans: HostPlan[] = [
+ { id: 'claude', name: 'Claude Code', detected: true, writes: claudeTargets(repo) },
+ ...HOSTS.map((host) => ({
+ id: host.id,
+ name: host.name,
+ detected: detected.has(host.id),
+ writes: [
+ instructionTarget(repo, host),
+ ...mcpTargets(repo, [host.id], { home }),
+ ...(host.id === 'agents' ? hookTargets(home) : []),
+ ],
+ })),
+ ];
+
+ return opts.ids ? plans.filter((p) => opts.ids!.includes(p.id)) : plans;
+}
+
+/** Flatten a plan down to the writes for the selected host ids. */
+export function selectedWrites(plan: HostPlan[], ids: string[]): PlannedWrite[] {
+ return plan.filter((p) => ids.includes(p.id)).flatMap((p) => p.writes);
+}
diff --git a/test/cli-picker.test.ts b/test/cli-picker.test.ts
new file mode 100644
index 00000000..041dcd9a
--- /dev/null
+++ b/test/cli-picker.test.ts
@@ -0,0 +1,211 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { planInit } from '../src/hosts/plan.js';
+import {
+ KEY_CTRL_C, KEY_DOWN, KEY_ESC, KEY_UP,
+ describeWrites, formatNonInteractiveHelp, formatPlan, initialPickerState,
+ keyOf, keysOf, pickedIds, reducePicker, renderPicker, tilde,
+ type PickerKey,
+} from '../src/cli-picker.js';
+
+function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-picker-')); }
+
+function fullHome(): string {
+ const home = fresh();
+ for (const d of ['.codex', '.cursor', '.gemini', '.adal', join('.config', 'opencode')]) {
+ mkdirSync(join(home, d), { recursive: true });
+ }
+ return home;
+}
+
+/** Feed a key sequence through the reducer, no TTY involved. */
+function drive(repo: string, home: string, keys: PickerKey[]) {
+ let state = initialPickerState(planInit(repo, { home }), repo, home);
+ for (const k of keys) state = reducePicker(state, k);
+ return state;
+}
+
+test('keyOf maps arrows, vim keys, toggles and aborts', () => {
+ assert.equal(keyOf(KEY_UP), 'up');
+ assert.equal(keyOf(KEY_DOWN), 'down');
+ assert.equal(keyOf('k'), 'up');
+ assert.equal(keyOf('j'), 'down');
+ assert.equal(keyOf(' '), 'space');
+ assert.equal(keyOf('a'), 'all');
+ assert.equal(keyOf('\r'), 'enter');
+ assert.equal(keyOf(KEY_ESC), 'abort');
+ assert.equal(keyOf(KEY_CTRL_C), 'abort');
+ assert.equal(keyOf('z'), null);
+});
+
+test('keysOf splits a batched chunk into every keypress it contains', () => {
+ // A pty hands over held/pasted/replayed input in one chunk — this must not
+ // read as a single unrecognised key (which used to hang the prompt).
+ assert.deepEqual(keysOf(`${KEY_DOWN} \r`), ['down', 'space', 'enter']);
+ assert.deepEqual(keysOf('jjk a'), ['down', 'down', 'up', 'space', 'all']);
+});
+
+test('keysOf consumes CSI sequences whole, so an arrow is never a bare ESC', () => {
+ assert.deepEqual(keysOf(KEY_UP), ['up']);
+ // An arrow followed by enter must not abort.
+ assert.deepEqual(keysOf(`${KEY_UP}\r`), ['up', 'enter']);
+ // A real lone ESC still aborts.
+ assert.deepEqual(keysOf(KEY_ESC), ['abort']);
+ // Unrecognised CSI (e.g. Home) is dropped, not mistaken for ESC.
+ assert.deepEqual(keysOf('\x1b[H'), []);
+ // Parameterised CSI (e.g. a mouse/modifier report) is also consumed whole.
+ assert.deepEqual(keysOf('\x1b[1;5A'), []);
+});
+
+test('keysOf ignores keys with no binding', () => {
+ assert.deepEqual(keysOf('xyz'), []);
+ assert.deepEqual(keysOf(''), []);
+});
+
+test('a batched chunk drives the reducer to a complete selection', () => {
+ const repo = fresh(); const home = fullHome();
+ let state = initialPickerState(planInit(repo, { home }), repo, home);
+ for (const key of keysOf(`${KEY_DOWN} \r`)) state = reducePicker(state, key);
+ assert.ok(state.done);
+ assert.deepEqual(pickedIds(state), ['claude', 'agents']);
+});
+
+test('claude starts checked, nothing else does', () => {
+ const repo = fresh(); const home = fullHome();
+ const state = initialPickerState(planInit(repo, { home }), repo, home);
+ assert.deepEqual(pickedIds(state), ['claude']);
+ assert.equal(state.rows[0].id, 'claude');
+});
+
+test('enter with no toggling wires claude only', () => {
+ const repo = fresh(); const home = fullHome();
+ const state = drive(repo, home, ['enter']);
+ assert.ok(state.done);
+ assert.deepEqual(pickedIds(state), ['claude']);
+});
+
+test('space toggles the row under the cursor, off and on again', () => {
+ const repo = fresh(); const home = fullHome();
+ assert.deepEqual(pickedIds(drive(repo, home, ['space'])), []);
+ assert.deepEqual(pickedIds(drive(repo, home, ['space', 'space'])), ['claude']);
+});
+
+test('down then space adds the second host', () => {
+ const repo = fresh(); const home = fullHome();
+ const state = drive(repo, home, ['down', 'space', 'enter']);
+ assert.deepEqual(pickedIds(state), ['claude', 'agents']);
+});
+
+test('cursor wraps at both ends', () => {
+ const repo = fresh(); const home = fullHome();
+ const n = planInit(repo, { home }).length;
+ assert.equal(drive(repo, home, ['up']).cursor, n - 1);
+ assert.equal(drive(repo, home, Array(n).fill('down') as PickerKey[]).cursor, 0);
+});
+
+test('a toggles all on, then all off', () => {
+ const repo = fresh(); const home = fullHome();
+ const n = planInit(repo, { home }).length;
+ assert.equal(pickedIds(drive(repo, home, ['all'])).length, n);
+ assert.deepEqual(pickedIds(drive(repo, home, ['all', 'all'])), []);
+});
+
+test('picked ids come back in plan order, not toggle order', () => {
+ const repo = fresh(); const home = fullHome();
+ // Toggle a late row first, then an earlier one.
+ const state = drive(repo, home, ['up', 'space', 'down', 'down', 'space', 'enter']);
+ const ids = pickedIds(state);
+ assert.deepEqual(ids, [...ids].sort((a, b) =>
+ state.rows.findIndex((r) => r.id === a) - state.rows.findIndex((r) => r.id === b)));
+});
+
+test('abort sets aborted and never done', () => {
+ const state = drive(fresh(), fullHome(), ['space', 'abort']);
+ assert.ok(state.aborted);
+ assert.ok(!state.done);
+});
+
+test('tilde shortens home paths and leaves others alone', () => {
+ assert.equal(tilde('/Users/me/.codex/config.toml', '/Users/me'), '~/.codex/config.toml');
+ assert.equal(tilde('/repo/AGENTS.md', '/Users/me'), '/repo/AGENTS.md');
+ // A sibling directory that merely shares a prefix is not the home dir.
+ assert.equal(tilde('/Users/mediocre/x', '/Users/me'), '/Users/mediocre/x');
+});
+
+test('describeWrites names out-of-repo writes as machine-wide', () => {
+ const repo = fresh(); const home = fullHome();
+ const agents = planInit(repo, { home, ids: ['agents'] })[0];
+ const summary = describeWrites(agents.writes, repo, home);
+ assert.match(summary, /AGENTS\.md/);
+ assert.match(summary, /\+ 3 in ~\/\.codex\/ \(machine-wide\)/);
+});
+
+test('describeWrites flags hosts with no MCP target', () => {
+ const repo = fresh(); const home = fullHome();
+ const adal = planInit(repo, { home, ids: ['adal'] })[0];
+ assert.match(describeWrites(adal.writes, repo, home), /no MCP/);
+ const cursor = planInit(repo, { home, ids: ['cursor'] })[0];
+ assert.doesNotMatch(describeWrites(cursor.writes, repo, home), /no MCP/);
+});
+
+test('describeWrites truncates long path lists', () => {
+ const repo = fresh(); const home = fullHome();
+ const claude = planInit(repo, { home, ids: ['claude'] })[0];
+ assert.match(describeWrites(claude.writes, repo, home), /\+2 more/);
+});
+
+test('renderPicker marks the cursor, the checkboxes and undetected hosts', () => {
+ const repo = fresh(); const home = fresh(); // nothing installed
+ const state = initialPickerState(planInit(repo, { home }), repo, home);
+ const text = renderPicker(state, false);
+ assert.match(text, /› \[x\] claude/);
+ assert.match(text, /\[ \] cursor.*\(not detected\)/);
+ assert.match(text, /space toggle/);
+ // Every host gets a row, plus header, blank lines and the key legend.
+ assert.equal(text.split('\n').filter((l) => /\[[ x]\]/.test(l)).length, state.rows.length);
+});
+
+test('formatPlan separates repo writes from machine-wide ones', () => {
+ const repo = fresh(); const home = fullHome();
+ const plan = planInit(repo, { home });
+ const text = formatPlan(plan, ['claude', 'agents'], repo, home, false);
+ const repoAt = text.indexOf('would write — this repo:');
+ const globalAt = text.indexOf('affects ALL repos:');
+ assert.ok(repoAt >= 0 && globalAt > repoAt, 'repo section comes first');
+ assert.match(text, /~\/\.codex\/hooks\.json/);
+ assert.match(text, /PostToolUse: Write\|Edit\|MultiEdit/);
+ assert.match(text, /nothing was written \(--dry-run\)/);
+ assert.match(text, /--no-global/);
+});
+
+test('formatPlan omits the machine-wide section when there is nothing global', () => {
+ const repo = fresh(); const home = fullHome();
+ const text = formatPlan(planInit(repo, { home }), ['claude'], repo, home, false);
+ assert.doesNotMatch(text, /affects ALL repos/);
+ assert.doesNotMatch(text, /--no-global/);
+});
+
+test('formatPlan says so when nothing is selected', () => {
+ const repo = fresh();
+ assert.match(formatPlan(planInit(repo, { home: fresh() }), [], repo, fresh(), false), /nothing/);
+});
+
+test('formatNonInteractiveHelp lists detected ids and a runnable command', () => {
+ const text = formatNonInteractiveHelp(['claude', 'cursor']);
+ assert.match(text, /nothing written/);
+ assert.match(text, /detected: claude, cursor/);
+ assert.match(text, /graft init --agents claude cursor {3}# wire these/);
+ assert.match(text, /--dry-run/);
+});
+
+test('formatNonInteractiveHelp still helps when nothing was detected', () => {
+ const text = formatNonInteractiveHelp([]);
+ assert.match(text, /detected: none/);
+ // No `--yes` example, since there is nothing for it to wire (the header
+ // still mentions the flag by name).
+ assert.doesNotMatch(text, /^ +graft init --yes/m);
+ assert.match(text, /--agents claude/);
+});
diff --git a/test/hosts-init.test.ts b/test/hosts-init.test.ts
index 435cd086..65e11cbb 100644
--- a/test/hosts-init.test.ts
+++ b/test/hosts-init.test.ts
@@ -1,9 +1,9 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, writeFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { execFileSync } from 'node:child_process';
+import { execFileSync, spawnSync } from 'node:child_process';
import { runHostsInit } from '../src/hosts/init.js';
function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-hostsinit-')); }
@@ -136,3 +136,90 @@ test('hooks: false skips hook installation', () => {
assert.deepEqual(r.hooks, []);
assert.ok(!existsSync(join(home, '.codex', 'hooks.json')));
});
+
+test('global: false keeps the instruction file but skips every ~ write', () => {
+ const home = fresh(); const repo = fresh();
+ mkdirSync(join(home, '.codex'), { recursive: true });
+ mkdirSync(join(home, '.config', 'opencode'), { recursive: true });
+ const r = runHostsInit(repo, { home, agents: ['agents'], global: false });
+
+ assert.deepEqual(r.written.map((w) => w.id), ['agents']);
+ assert.ok(existsSync(join(repo, 'AGENTS.md')));
+ assert.deepEqual(r.hooks, []);
+ assert.ok(!existsSync(join(home, '.codex', 'hooks.json')));
+ assert.ok(!existsSync(join(home, '.codex', 'config.toml')));
+ // The repo-local opencode MCP config is not a global write, so it survives.
+ assert.deepEqual(r.mcp.map((m) => m.id), ['opencode']);
+ assert.ok(existsSync(join(repo, 'opencode.json')));
+});
+
+// --- CLI: choosing what gets written ------------------------------------
+
+/**
+ * Run `graft init` with a scratch HOME so tests never touch the real ~/.codex,
+ * and return stderr. The child gets a pipe rather than a TTY, which is exactly
+ * the non-interactive path we want to exercise.
+ */
+function cliStderr(repo: string, home: string, extra: string[] = []): string {
+ const res = spawnSync(
+ process.execPath,
+ ['--import', 'tsx', 'src/cli.ts', 'init', repo, '--no-build', ...extra],
+ { encoding: 'utf8', env: { ...process.env, HOME: home } },
+ );
+ assert.equal(res.status, 0, `exited ${res.status}: ${res.stderr}`);
+ return res.stderr ?? '';
+}
+
+test('CLI: no flags and no TTY writes nothing and names the detected agents', () => {
+ const home = fresh(); const repo = fresh();
+ mkdirSync(join(home, '.cursor'));
+ const out = cliStderr(repo, home);
+ assert.match(out, /nothing written/);
+ assert.match(out, /detected: claude, cursor/);
+ assert.match(out, /graft init --agents claude cursor/);
+ assert.deepEqual(readdirSync(repo), []);
+});
+
+test('CLI: --dry-run prints the plan, both sections, and writes nothing', () => {
+ const home = fresh(); const repo = fresh();
+ mkdirSync(join(home, '.codex'), { recursive: true });
+ const out = cliStderr(repo, home, ['--dry-run']);
+
+ assert.match(out, /would write — this repo:/);
+ assert.match(out, /\.claude\/settings\.json/);
+ assert.match(out, /AGENTS\.md/);
+ assert.match(out, /affects ALL repos:/);
+ assert.match(out, /~\/\.codex\/hooks\.json/);
+ assert.match(out, /nothing was written/);
+
+ assert.deepEqual(readdirSync(repo), []);
+ assert.ok(!existsSync(join(home, '.codex', 'hooks.json')));
+});
+
+test('CLI: --yes wires every detected agent (the pre-0.8 default)', () => {
+ const home = fresh(); const repo = fresh();
+ mkdirSync(join(home, '.cursor'));
+ cliStderr(repo, home, ['--yes']);
+ assert.ok(existsSync(join(repo, '.claude', 'settings.json')));
+ assert.ok(existsSync(join(repo, '.cursor', 'rules', 'graft.mdc')));
+ // gemini was never installed in this scratch home, so it is not wired.
+ assert.ok(!existsSync(join(repo, 'GEMINI.md')));
+});
+
+test('CLI: --no-global writes AGENTS.md but leaves ~/.codex alone', () => {
+ const home = fresh(); const repo = fresh();
+ mkdirSync(join(home, '.codex'), { recursive: true });
+ const out = cliStderr(repo, home, ['--agents', 'agents', '--no-global']);
+ assert.ok(existsSync(join(repo, 'AGENTS.md')));
+ assert.deepEqual(readdirSync(join(home, '.codex')), []);
+ assert.match(out, /skipped out-of-repo writes/);
+});
+
+test('CLI: --dry-run respects an explicit --agents list', () => {
+ const home = fresh(); const repo = fresh();
+ mkdirSync(join(home, '.codex'), { recursive: true });
+ const out = cliStderr(repo, home, ['--agents', 'adal', '--dry-run']);
+ assert.match(out, /\.adal\/skills\/graft\/SKILL\.md/);
+ assert.doesNotMatch(out, /AGENTS\.md/);
+ assert.doesNotMatch(out, /affects ALL repos/);
+});
diff --git a/test/hosts-plan.test.ts b/test/hosts-plan.test.ts
new file mode 100644
index 00000000..d68aba50
--- /dev/null
+++ b/test/hosts-plan.test.ts
@@ -0,0 +1,100 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, readdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { planInit, selectedWrites } from '../src/hosts/plan.js';
+import { runHostsInit } from '../src/hosts/init.js';
+import { hostIds } from '../src/hosts/registry.js';
+
+function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-plan-')); }
+
+/** A home with every CLI graft can detect installed. */
+function fullHome(): string {
+ const home = fresh();
+ for (const d of ['.codex', '.cursor', '.gemini', '.kiro', '.adal', join('.codeium', 'windsurf'), join('.config', 'opencode')]) {
+ mkdirSync(join(home, d), { recursive: true });
+ }
+ return home;
+}
+
+test('planInit covers claude plus every registry host, claude first', () => {
+ const plan = planInit(fresh(), { home: fresh() });
+ assert.equal(plan.length, hostIds().length + 1);
+ assert.equal(plan[0].id, 'claude');
+ assert.deepEqual(plan.map((p) => p.id).slice(1), hostIds());
+});
+
+test('planInit writes nothing — it only describes', () => {
+ const repo = fresh(); const home = fullHome();
+ const plan = planInit(repo, { home });
+ assert.ok(plan.length > 0);
+ for (const p of plan) for (const w of p.writes) assert.ok(w.path.length > 0);
+ // The repo gained nothing.
+ assert.deepEqual(readdirSync(repo), []);
+});
+
+test('claude writes are all repo-scoped — the claude layer never touches ~', () => {
+ 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)));
+});
+
+test('the three ~/.codex writes are scoped global', () => {
+ const home = fullHome();
+ const agents = planInit(fresh(), { home, ids: ['agents'] })[0];
+ const globals = agents.writes.filter((w) => w.scope === 'global');
+ assert.equal(globals.length, 3);
+ assert.deepEqual(
+ globals.map((w) => w.path.slice(home.length)).sort(),
+ ['/.codex/config.toml', '/.codex/hooks.json', '/.codex/hooks/graft/graft-hooks.cjs'],
+ );
+});
+
+test('global writes vanish when the CLI is not installed', () => {
+ const agents = planInit(fresh(), { home: fresh(), ids: ['agents'] })[0];
+ assert.deepEqual(agents.writes.filter((w) => w.scope === 'global'), []);
+ // AGENTS.md is still planned — the instruction file does not depend on ~.
+ assert.equal(agents.writes.length, 1);
+ assert.match(agents.writes[0].path, /AGENTS\.md$/);
+});
+
+test('detected mirrors detectHosts; claude is always available', () => {
+ const home = fresh(); mkdirSync(join(home, '.adal'));
+ const plan = planInit(fresh(), { home });
+ const detected = plan.filter((p) => p.detected).map((p) => p.id).sort();
+ assert.deepEqual(detected, ['adal', 'claude']);
+});
+
+test('adal is an instruction-only host — no MCP target', () => {
+ const adal = planInit(fresh(), { home: fullHome(), ids: ['adal'] })[0];
+ assert.equal(adal.writes.length, 1);
+ assert.equal(adal.writes[0].kind, 'instruction');
+ assert.match(adal.writes[0].path, /\.adal\/skills\/graft\/SKILL\.md$/);
+});
+
+// The assertion that keeps the plan honest: whatever a real run writes must be
+// exactly what the plan said it would.
+test('every path a real runHostsInit writes was in the plan, and vice versa', () => {
+ const repo = fresh(); const home = fullHome();
+ const ids = hostIds();
+
+ const planned = new Set(selectedWrites(planInit(repo, { home }), ids).map((w) => w.path));
+ const r = runHostsInit(repo, { home, agents: ids });
+ const actual = new Set([
+ ...r.written.map((w) => w.path),
+ ...r.mcp.map((m) => m.path),
+ ...r.hooks.map((h) => h.path),
+ ]);
+
+ assert.deepEqual([...actual].sort(), [...planned].sort());
+});
+
+test('selectedWrites filters to the chosen hosts only', () => {
+ const repo = fresh();
+ const plan = planInit(repo, { home: fullHome() });
+ const writes = selectedWrites(plan, ['claude', 'adal']);
+ assert.deepEqual([...new Set(writes.map((w) => w.hostId))].sort(), ['adal', 'claude']);
+});