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
init: build the graph whatever was selected, plus picker cleanups
anirudhkumar-nanonetse2b758b31c20
diff --git a/src/claude/init.ts b/src/claude/init.tsindex 70535fdc..9c6efd06 100644--- a/src/claude/init.ts+++ b/src/claude/init.ts@@ -26,6 +26,23 @@ export function claudeTargets(dir: string): PlannedWrite[] {];}+/**+ * Build the graph if it isn't there yet. Not Claude-specific: the wiring for any+ * host points at `graft/`, so `graft init` builds whichever hosts were selected —+ * this lives beside `runInit` only because that's the caller that owns `built`.+ * Best-effort; the user can always run `graft build` (the epilogue says so).+ */+export function buildGraphIfMissing(dir: string, opts: { build?: boolean; cliPath?: string }): boolean {+ const wiring = join(dir, 'graft', '.graph', 'wiring.json');+ if (opts.build === false || !opts.cliPath || existsSync(wiring)) return false;+ try {+ execFileSync(process.execPath, [opts.cliPath, 'build', '.'], { cwd: dir, stdio: 'inherit', timeout: 300000 });+ return true;+ } catch {+ return false;+ }+}+export interface InitResult {settingsPath: string;shims: string[];@@ -65,13 +82,6 @@ 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', SERVER_ENTRY);- let built = false;- const wiring = join(dir, 'graft', '.graph', 'wiring.json');- if (opts.build !== false && opts.cliPath && !existsSync(wiring)) {- try {- execFileSync(process.execPath, [opts.cliPath, 'build', '.'], { cwd: dir, stdio: 'inherit', timeout: 300000 });- built = true;- } catch { /* build best-effort; user can run `graft build` manually */ }- }+ const built = buildGraphIfMissing(dir, opts);return { settingsPath, shims: [sl, hk], skill: skillPath, mcp, warnings, built };}diff --git a/src/cli-picker.ts b/src/cli-picker.tsindex 1f454472..696904f7 100644--- a/src/cli-picker.ts+++ b/src/cli-picker.ts@@ -5,7 +5,6 @@* `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`;@@ -206,7 +205,6 @@ export async function runPicker(lastLines = text.split('\n').length;};- const rl = createInterface({ input: stdin });const wasRaw = Boolean(stdin.isRaw);stdin.setRawMode?.(true);stdin.resume();@@ -214,8 +212,11 @@ export async function runPicker(try {return await new Promise<string[] | null>((resolve) => {+ // Both listeners come off together: a leftover 'end' would otherwise fire+ // after a confirmed pick and redraw the picker over init's own output.const finish = (onData: (b: Buffer) => void) => {stdin.off('data', onData);+ stdin.off('end', onEnd);draw();resolve(state.aborted ? null : pickedIds(state));};@@ -231,13 +232,13 @@ export async function runPicker(}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); });+ const onEnd = () => { state = { ...state, aborted: true }; finish(onData); };+ stdin.on('data', onData);+ stdin.on('end', onEnd);});} finally {stdin.setRawMode?.(wasRaw);- rl.close();stdin.pause();}}diff --git a/src/cli.ts b/src/cli.tsindex 969cb372..80ccd533 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -13,7 +13,7 @@ import { resolveConfig, type EngineConfig } from "./ai/providers.js";import type { ProviderKind } from "./ai/llm/factory.js";import { formatCheckReport } from "./context/check.js";import { formatGraphCheckReport } from "./graph/check.js";-import { runInit } from "./claude/init.js";+import { buildGraphIfMissing, runInit } from "./claude/init.js";import { runHostsInit } from "./hosts/init.js";import { hostIds } from "./hosts/registry.js";import { contextDirFor } from "./context/node-file.js";@@ -28,7 +28,7 @@ import {runWorkspaceMap,} from "./graph/workspace-cli.js";import { formatInitEpilogue } from "./cli-epilogue.js";-import { planInit } from "./hosts/plan.js";+import { planInit, selectedWrites } 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";@@ -491,9 +491,9 @@ program}const wantClaude = ids.includes("claude");+ const cliPath = fileURLToPath(import.meta.url);if (wantClaude) {- const cliPath = fileURLToPath(import.meta.url);const res = runInit(repo, { build: opts.build, cliPath });console.error(`✓ wrote ${res.settingsPath}`);for (const s of res.shims) console.error(`✓ wrote ${s}`);@@ -522,7 +522,19 @@ programfor (const w of r.written) console.error(`✓ ${w.id}: ${w.path} (${w.action})`);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)");+ // Only worth saying when there was actually something out-of-repo to skip.+ if (opts.global === false && selectedWrites(plan, ids).some((w) => w.scope === "global"))+ console.error("· skipped out-of-repo writes (--no-global)");+ }++ // Every host's wiring points at graft/, so the graph is built whatever was+ // selected — not only when Claude Code is in the list (runInit does its own).+ if (!wantClaude) {+ console.error(+ buildGraphIfMissing(repo, { build: opts.build, cliPath })+ ? "✓ built the graph (graft build)"+ : "· skipped graph build",+ );}const globalOpts = program.opts<{ dir?: string }>();diff --git a/test/claude-init.test.ts b/test/claude-init.test.tsindex ce6aa246..3f382e26 100644--- a/test/claude-init.test.ts+++ b/test/claude-init.test.ts@@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, existsSync, writeFileSync, mkdirSync } fromimport { tmpdir } from 'node:os';import { join } from 'node:path';import { execFileSync, spawnSync } from 'node:child_process';-import { runInit } from '../src/claude/init.js';+import { buildGraphIfMissing, runInit } from '../src/claude/init.js';import { formatInitEpilogue } from '../src/cli-epilogue.js';function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-init-')); }@@ -135,3 +135,22 @@ test('CLI: graft init epilogue has the wordmark + next steps, and never mentions// --no-build, never built before → "build the graph" is step 1assert.ok(res.stderr.includes('1. build the graph'));});++// --- buildGraphIfMissing --------------------------------------------------+// Shared with the CLI's non-Claude path, so its guards are pinned here.++test('buildGraphIfMissing: build:false never spawns a build', () => {+ assert.equal(buildGraphIfMissing(fresh(), { build: false, cliPath: '/nonexistent/cli.js' }), false);+});++test('buildGraphIfMissing: no cliPath means nothing to spawn', () => {+ assert.equal(buildGraphIfMissing(fresh(), { build: true }), false);+});++test('buildGraphIfMissing: an existing graph is left alone', () => {+ const dir = fresh();+ mkdirSync(join(dir, 'graft', '.graph'), { recursive: true });+ writeFileSync(join(dir, 'graft', '.graph', 'wiring.json'), '{}');+ // A bogus cliPath would throw if it were reached; the wiring check short-circuits.+ assert.equal(buildGraphIfMissing(dir, { build: true, cliPath: '/nonexistent/cli.js' }), false);+});diff --git a/test/hosts-init.test.ts b/test/hosts-init.test.tsindex 65e11cbb..c56d790f 100644--- a/test/hosts-init.test.ts+++ b/test/hosts-init.test.ts@@ -215,6 +215,24 @@ test('CLI: --no-global writes AGENTS.md but leaves ~/.codex alone', () => {assert.match(out, /skipped out-of-repo writes/);});+test('CLI: the graph build is attempted even when claude is not selected', () => {+ const home = fresh(); const repo = fresh();+ mkdirSync(join(home, '.cursor'));+ // Regression: the build used to sit inside `if (wantClaude)`, so picking only+ // cursor wired .cursor/ and never built the graph its rule file points at.+ const out = cliStderr(repo, home, ['--agents', 'cursor']);+ assert.match(out, /(built the graph|skipped graph build)/);+});++test('CLI: --no-global stays quiet when the selection has nothing out-of-repo', () => {+ const home = fresh(); const repo = fresh();+ mkdirSync(join(home, '.codex'), { recursive: true });+ // cursor writes only inside the repo, so there is nothing for --no-global to skip.+ const out = cliStderr(repo, home, ['--agents', 'cursor', '--no-global']);+ assert.ok(existsSync(join(repo, '.cursor', 'rules', 'graft.mdc')));+ assert.doesNotMatch(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 });