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
docs: spec + plan for graft init onboarding (0.3.0)
Shrish Dwivedi62b7d6cbf8a7
diff --git a/docs/superpowers/plans/2026-07-20-graft-init-onboarding.md b/docs/superpowers/plans/2026-07-20-graft-init-onboarding.mdnew file mode 100644index 00000000..93c9b6e6--- /dev/null+++ b/docs/superpowers/plans/2026-07-20-graft-init-onboarding.md@@ -0,0 +1,545 @@+# `graft init` Onboarding Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Make the Claude Code integration work in any repo via `npm i -D @nanonets/graft` + `npx graft init`, then publish `0.3.0`.++**Architecture:** A pure `mergeGraftSettings` + shim-source generators live in `src/claude/`; `runInit` orchestrates writing `.claude/` files and (optionally) building the graph; `cli.ts` exposes `graft init`. Consumer shims resolve the installed package on disk and dynamic-import the absolute file (bypassing the restrictive `exports` map). A `postinstall` script prints a one-line nudge.++**Tech Stack:** Node 20+ (ESM), TypeScript (strict), `node:test` + `node:assert/strict`, `tsx`, `commander`. No new dependencies.++## Global Constraints++- **Money guard:** `graft init`'s build step runs only plain `graft build` — structural, offline, `$0`. Never `--deep`. (spec §4.6)+- **Never clobber user config:** merging `.claude/settings.json` preserves all foreign keys; a foreign `statusLine`/`subagentStatusLine` is left untouched with a warning; Graft hook entries are appended (and de-duplicated on re-run). (spec §4.3)+- **Idempotent:** re-running `graft init` updates in place — no duplicate hook entries, no duplicate footer regex. (spec §4.4)+- **Best-effort install:** `postinstall` never fails an install (any error → exit 0); silent when `CI` is set or already initialized. (spec §4.5)+- **Smart shim resolution:** shims resolve `@nanonets/graft/package.json` from the target dir and import `<pkgRoot>/dist/claude/<file>`; fall back to `<dir>/dist/claude/<file>` for Graft's own repo. Absolute-path `import()` bypasses `exports`. (spec §4.1)+- Node ESM (`.js` import extensions in `src/`). State/most conventions follow the existing `src/claude/*`.++---++## File Structure++**Created:** `src/claude/shim-template.ts`, `src/claude/settings-merge.ts`, `src/claude/init.ts`, `scripts/postinstall.mjs`, `test/claude-shim-template.test.ts`, `test/claude-settings-merge.test.ts`, `test/claude-init.test.ts`.+**Modified:** `src/cli.ts` (add `init`), `.claude/helpers/graft-statusline.cjs` + `graft-hooks.cjs` (smart form), `package.json` (`exports["./package.json"]`, `scripts.postinstall`, version `0.3.0`).++---++## Task 1: Smart shim template + own-repo shims + exports++**Files:**+- Create: `src/claude/shim-template.ts`, `test/claude-shim-template.test.ts`+- Modify: `.claude/helpers/graft-statusline.cjs`, `.claude/helpers/graft-hooks.cjs`, `package.json` (`exports`)++**Interfaces:**+- Produces: `statuslineShim(): string`, `hooksShim(): string`++- [ ] **Step 1: Write the failing test**++```ts+// test/claude-shim-template.test.ts+import { test } from 'node:test';+import assert from 'node:assert/strict';+import vm from 'node:vm';+import { statuslineShim, hooksShim } from '../src/claude/shim-template.js';++for (const [name, src] of [['statusline', statuslineShim()], ['hooks', hooksShim()]] as const) {+ test(`${name} shim parses and has package-resolve + local fallback`, () => {+ const body = src.replace(/^#!.*\n/, ''); // strip shebang for vm+ assert.doesNotThrow(() => new vm.Script(body), 'valid JS');+ assert.match(src, /require\.resolve\('@nanonets\/graft\/package\.json', \{ paths: \[dir\] \}\)/);+ assert.match(src, /path\.join\(dir, 'dist', 'claude'/);+ assert.match(src, /\.catch\(\(\) => \{/); // best-effort+ });+}++test('statusline calls main(); hooks passes the event arg', () => {+ assert.match(statuslineShim(), /m\.main\(\)/);+ assert.match(hooksShim(), /m\.main\(process\.argv\[2\]\)/);+});+```++- [ ] **Step 2: Run test — expect FAIL** (`Cannot find module '../src/claude/shim-template.js'`)++Run: `node --import tsx --test test/claude-shim-template.test.ts`++- [ ] **Step 3: Implement `src/claude/shim-template.ts`**++```ts+function shim(entryFile: string, call: string): string {+ return `#!/usr/bin/env node+const path = require('path');+const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();+function entry(name) {+ try {+ const pkg = require.resolve('@nanonets/graft/package.json', { paths: [dir] });+ return path.join(path.dirname(pkg), 'dist', 'claude', name);+ } catch {+ return path.join(dir, 'dist', 'claude', name);+ }+}+import(entry(${JSON.stringify(entryFile)})).then((m) => ${call}).catch(() => { /* graft unavailable — no-op */ });+`;+}++export function statuslineShim(): string { return shim('statusline.js', 'm.main()'); }+export function hooksShim(): string { return shim('hooks.js', 'm.main(process.argv[2])'); }+```++- [ ] **Step 4: Run test — expect PASS**++Run: `node --import tsx --test test/claude-shim-template.test.ts`++- [ ] **Step 5: Regenerate Graft's own committed shims to the smart form**++Overwrite `.claude/helpers/graft-statusline.cjs` with the exact output of `statuslineShim()` and `.claude/helpers/graft-hooks.cjs` with `hooksShim()`. Generate them deterministically:++```bash+node --import tsx -e "import('./src/claude/shim-template.ts').then(m=>{require('fs').writeFileSync('.claude/helpers/graft-statusline.cjs',m.statuslineShim());require('fs').writeFileSync('.claude/helpers/graft-hooks.cjs',m.hooksShim());})"+chmod +x .claude/helpers/graft-statusline.cjs .claude/helpers/graft-hooks.cjs+```++- [ ] **Step 6: Add `./package.json` to `exports` in `package.json`**++Change the `exports` block to:++```json+ "exports": {+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },+ "./package.json": "./package.json"+ },+```++- [ ] **Step 7: Build + verify the own-repo shim still renders (dogfood fallback path)**++```bash+npm run build+echo '{"session_id":"t","cwd":"'"$PWD"'","context_window":{"used_percentage":30}}' | node .claude/helpers/graft-statusline.cjs+```+Expected: the graft bar renders (in this repo, `require.resolve('@nanonets/graft/...')` fails → falls back to `./dist/claude/statusline.js`). If `graft/.cache/stats.json` is absent it falls back further to `wiring.json` — still a real bar, not "not built".++- [ ] **Step 8: Commit**++```bash+git add src/claude/shim-template.ts test/claude-shim-template.test.ts .claude/helpers/graft-statusline.cjs .claude/helpers/graft-hooks.cjs package.json+git commit -m "feat(claude): smart shim resolution (installed package + local fallback) + package.json export"+```++---++## Task 2: `mergeGraftSettings` — non-clobbering, idempotent settings merge++**Files:**+- Create: `src/claude/settings-merge.ts`, `test/claude-settings-merge.test.ts`++**Interfaces:**+- Produces: `mergeGraftSettings(existing: Record<string, any>): { merged: Record<string, any>; warnings: string[] }`++- [ ] **Step 1: Write the failing test**++```ts+// test/claude-settings-merge.test.ts+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mergeGraftSettings } from '../src/claude/settings-merge.js';++const SL = 'node "${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs"';++test('empty settings gets the full Graft blocks', () => {+ const { merged, warnings } = mergeGraftSettings({});+ assert.equal(merged.statusLine.command, SL);+ assert.equal(merged.subagentStatusLine.command, SL);+ assert.ok(Array.isArray(merged.hooks.PostToolUse));+ assert.equal(merged.hooks.PostToolUse[0].matcher, 'Write|Edit|MultiEdit');+ for (const e of ['PostToolUse', 'UserPromptSubmit', 'SessionStart', 'Stop']) {+ assert.ok(merged.hooks[e][0].hooks[0].command.includes('graft-hooks.cjs'), `${e} wired`);+ }+ assert.ok(merged.footerLinksRegexes.includes('graft/[\\w./-]+\\.md'));+ assert.deepEqual(warnings, []);+});++test('foreign statusLine is preserved with a warning; Graft not forced in', () => {+ const { merged, warnings } = mergeGraftSettings({ statusLine: { type: 'command', command: 'my-bar.sh' } });+ assert.equal(merged.statusLine.command, 'my-bar.sh');+ assert.equal(warnings.length, 1);+ assert.match(warnings[0], /statusLine/);+});++test('existing foreign hooks are preserved; Graft appended', () => {+ const existing = { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: 'mine.sh' }] }] } };+ const { merged } = mergeGraftSettings(existing);+ assert.equal(merged.hooks.PostToolUse.length, 2);+ assert.equal(merged.hooks.PostToolUse[0].hooks[0].command, 'mine.sh');+ assert.ok(merged.hooks.PostToolUse[1].hooks[0].command.includes('graft-hooks.cjs'));+});++test('re-running is idempotent (no duplicate Graft entries or footer)', () => {+ const once = mergeGraftSettings({}).merged;+ const twice = mergeGraftSettings(once).merged;+ assert.equal(twice.hooks.PostToolUse.length, 1);+ assert.equal(twice.hooks.Stop.length, 1);+ assert.equal(twice.footerLinksRegexes.filter((r: string) => r === 'graft/[\\w./-]+\\.md').length, 1);+});++test('foreign top-level keys survive', () => {+ const { merged } = mergeGraftSettings({ model: 'claude-sonnet-5', permissions: { allow: ['Bash(ls)'] } });+ assert.equal(merged.model, 'claude-sonnet-5');+ assert.deepEqual(merged.permissions.allow, ['Bash(ls)']);+});+```++- [ ] **Step 2: Run test — expect FAIL**++Run: `node --import tsx --test test/claude-settings-merge.test.ts`++- [ ] **Step 3: Implement `src/claude/settings-merge.ts`**++```ts+type Json = Record<string, any>;++const SL_CMD = 'node "${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs"';+const FOOTER = 'graft/[\\w./-]+\\.md';++function hookCmd(arg: string): string {+ return `node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs" ${arg}`;+}+function graftBlocks(): Record<string, Json> {+ return {+ PostToolUse: { matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: hookCmd('post-edit'), timeout: 10000 }] },+ UserPromptSubmit: { hooks: [{ type: 'command', command: hookCmd('prompt'), timeout: 8000 }] },+ SessionStart: { hooks: [{ type: 'command', command: hookCmd('session-start'), timeout: 8000 }] },+ Stop: { hooks: [{ type: 'command', command: hookCmd('stop'), timeout: 8000 }] },+ };+}+function isGraftHookEntry(entry: Json): boolean {+ return JSON.stringify(entry ?? '').includes('graft-hooks.cjs');+}++export function mergeGraftSettings(existing: Json): { merged: Json; warnings: string[] } {+ const merged: Json = { ...(existing ?? {}) };+ const warnings: string[] = [];++ if (!merged.statusLine) merged.statusLine = { type: 'command', command: SL_CMD };+ else if (merged.statusLine.command !== SL_CMD)+ warnings.push('Existing statusLine left untouched (a session allows only one). To use Graft, point it at .claude/helpers/graft-statusline.cjs.');++ if (!merged.subagentStatusLine) merged.subagentStatusLine = { type: 'command', command: SL_CMD };+ else if (merged.subagentStatusLine.command !== SL_CMD)+ warnings.push('Existing subagentStatusLine left untouched.');++ merged.hooks = { ...(merged.hooks ?? {}) };+ for (const [event, block] of Object.entries(graftBlocks())) {+ const prior = Array.isArray(merged.hooks[event]) ? merged.hooks[event] : [];+ const foreign = prior.filter((e: Json) => !isGraftHookEntry(e)); // drop old Graft entries → idempotent+ merged.hooks[event] = [...foreign, block];+ }++ const footer = Array.isArray(merged.footerLinksRegexes) ? [...merged.footerLinksRegexes] : [];+ if (!footer.includes(FOOTER)) footer.push(FOOTER);+ merged.footerLinksRegexes = footer;++ return { merged, warnings };+}+```++- [ ] **Step 4: Run test — expect PASS (5 tests)**++Run: `node --import tsx --test test/claude-settings-merge.test.ts`++- [ ] **Step 5: Commit**++```bash+git add src/claude/settings-merge.ts test/claude-settings-merge.test.ts+git commit -m "feat(claude): non-clobbering, idempotent settings merge for graft init"+```++---++## Task 3: `runInit` + `graft init` command++**Files:**+- Create: `src/claude/init.ts`, `test/claude-init.test.ts`+- Modify: `src/cli.ts`++**Interfaces:**+- Consumes: `mergeGraftSettings` (Task 2); `statuslineShim`/`hooksShim` (Task 1).+- Produces: `runInit(dir: string, opts?: { build?: boolean; cliPath?: string }): InitResult` where `interface InitResult { settingsPath: string; shims: string[]; warnings: string[]; built: boolean }`++- [ ] **Step 1: Write the failing test**++```ts+// test/claude-init.test.ts+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runInit } from '../src/claude/init.js';++function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-init-')); }++test('runInit scaffolds settings + both shims (build skipped)', () => {+ const d = fresh();+ const r = runInit(d, { build: false });+ 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')));+ assert.equal(r.built, false);+ const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));+ assert.ok(s.statusLine.command.includes('graft-statusline.cjs'));+ assert.ok(s.hooks.Stop[0].hooks[0].command.includes('graft-hooks.cjs'));+});++test('runInit preserves foreign settings and warns on foreign statusLine', () => {+ const d = fresh();+ const { writeFileSync, mkdirSync } = require('node:fs');+ 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 s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));+ assert.equal(s.model, 'x');+ assert.equal(s.statusLine.command, 'mine');+ assert.equal(r.warnings.length, 1);+});++test('runInit is idempotent', () => {+ const d = fresh();+ runInit(d, { build: false });+ runInit(d, { build: false });+ const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));+ assert.equal(s.hooks.PostToolUse.length, 1);+});+```++- [ ] **Step 2: Run test — expect FAIL**++Run: `node --import tsx --test test/claude-init.test.ts`++- [ ] **Step 3: Implement `src/claude/init.ts`**++```ts+import { mkdirSync, writeFileSync, readFileSync, existsSync, chmodSync } from 'node:fs';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { mergeGraftSettings } from './settings-merge.js';+import { statuslineShim, hooksShim } from './shim-template.js';++export interface InitResult {+ settingsPath: string;+ shims: string[];+ warnings: string[];+ built: boolean;+}++export function runInit(dir: string, opts: { build?: boolean; cliPath?: string } = {}): InitResult {+ const helpersDir = join(dir, '.claude', 'helpers');+ mkdirSync(helpersDir, { recursive: true });++ const settingsPath = join(dir, '.claude', 'settings.json');+ 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');+ writeFileSync(sl, statuslineShim()); chmodSync(sl, 0o755);+ writeFileSync(hk, hooksShim()); chmodSync(hk, 0o755);++ 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 */ }+ }+ return { settingsPath, shims: [sl, hk], warnings, built };+}+```++- [ ] **Step 4: Run test — expect PASS (3 tests)**++Run: `node --import tsx --test test/claude-init.test.ts`++- [ ] **Step 5: Add the `init` command to `src/cli.ts`**++Add these imports near the top (match existing import style):++```ts+import { fileURLToPath } from 'node:url';+import { resolve } from 'node:path';+import { runInit } from './claude/init.js';+```++Add the command (place it alongside the other `.command(...)` blocks, before `program.parseAsync()`):++```ts+program+ .command('init')+ .description('Set up the Claude Code integration (.claude/ statusline + hooks) in this repo')+ .argument('[dir]', 'target repo directory', '.')+ .option('--no-build', 'skip building the graph (wire files only)')+ .action((dir: string, opts: { build?: boolean }) => {+ const cliPath = fileURLToPath(import.meta.url);+ const res = runInit(resolve(dir), { build: opts.build, cliPath });+ console.error(`✓ wrote ${res.settingsPath}`);+ for (const s of res.shims) console.error(`✓ wrote ${s}`);+ console.error(res.built ? '✓ built the graph (graft build)' : '· skipped graph build');+ for (const w of res.warnings) console.error(`⚠ ${w}`);+ console.error('\nDone. The statusline + hooks activate in Claude Code sessions in this repo.');+ console.error('For LLM summaries: set OPENROUTER_API_KEY and run `graft build --deep`.');+ });+```++> If `commander`'s `--no-build` mapping is unclear: commander sets `opts.build = false` when `--no-build` is passed and `true` otherwise. `runInit` treats `build !== false` as "build".++- [ ] **Step 6: Build + smoke-test the command in a temp consumer dir**++```bash+npm run build+TMP=$(mktemp -d); node dist/cli.js init "$TMP" --no-build; echo "---"; ls -la "$TMP/.claude/helpers"; cat "$TMP/.claude/settings.json" | head -20+```+Expected: writes settings + both shims; prints the summary; `--no-build` skips the build.++- [ ] **Step 7: Commit**++```bash+git add src/claude/init.ts test/claude-init.test.ts src/cli.ts+git commit -m "feat(cli): graft init — scaffold .claude/ integration into any repo"+```++---++## Task 4: `postinstall` nudge++**Files:**+- Create: `scripts/postinstall.mjs`+- Modify: `package.json` (`scripts.postinstall`)+- Test: `test/claude-init.test.ts` (append a subprocess test)++- [ ] **Step 1: Write the failing test** (append to `test/claude-init.test.ts`)++```ts+import { execFileSync } from 'node:child_process';++function runPostinstall(env: Record<string, string>): string {+ try {+ return execFileSync(process.execPath, ['scripts/postinstall.mjs'],+ { encoding: 'utf8', env: { ...process.env, ...env } });+ } catch { return ''; }+}++test('postinstall prints the nudge in a fresh dir', () => {+ const d = fresh();+ const out = runPostinstall({ INIT_CWD: d, CI: '' });+ assert.match(out, /npx graft init/);+});++test('postinstall is silent when already initialized', () => {+ const d = fresh();+ runInit(d, { build: false });+ const out = runPostinstall({ INIT_CWD: d, CI: '' });+ assert.equal(out.trim(), '');+});++test('postinstall is silent under CI', () => {+ const out = runPostinstall({ INIT_CWD: fresh(), CI: '1' });+ assert.equal(out.trim(), '');+});+```++- [ ] **Step 2: Run test — expect FAIL** (`scripts/postinstall.mjs` missing → catch → '' → nudge assertion fails)++Run: `node --import tsx --test test/claude-init.test.ts`++- [ ] **Step 3: Implement `scripts/postinstall.mjs`**++```js+// Prints a one-line nudge after install. Never fails the install.+try {+ if (process.env.CI) process.exit(0);+ const { existsSync } = await import('node:fs');+ const { join } = await import('node:path');+ const dir = process.env.INIT_CWD || process.cwd();+ if (existsSync(join(dir, '.claude', 'helpers', 'graft-statusline.cjs'))) process.exit(0);+ console.log('\n Graft installed. Run `npx graft init` to enable the Claude Code integration (statusline + hooks + auto-sync).\n');+} catch {+ /* never fail an install */+}+```++- [ ] **Step 4: Wire `postinstall` in `package.json`**++Add to `scripts`: `"postinstall": "node scripts/postinstall.mjs"`.++- [ ] **Step 5: Run test — expect PASS (3 new tests)**++Run: `node --import tsx --test test/claude-init.test.ts`++- [ ] **Step 6: Confirm `scripts/` ships in the package**++`package.json` `files` is `["dist", "README.md", "LICENSE"]` — `scripts/` is NOT included, so the published `postinstall` would 404. Add `"scripts"` to `files`:++```json+ "files": ["dist", "scripts", "README.md", "LICENSE"],+```++Verify: `npm pack --dry-run 2>&1 | grep -E "postinstall|scripts/"` shows `scripts/postinstall.mjs` in the tarball.++- [ ] **Step 7: Commit**++```bash+git add scripts/postinstall.mjs package.json test/claude-init.test.ts+git commit -m "feat: postinstall nudge to run graft init (silent in CI / when initialized)"+```++---++## Task 5: Version bump + full verification + consumer smoke++**Files:** Modify `package.json` (version).++- [ ] **Step 1: Full suite green**++Run: `npm test`+Expected: all `test/*.test.ts` pass (existing `claude-*` + the 3 new files), no regressions.++- [ ] **Step 2: Build clean**++Run: `npm run build`+Expected: exit 0; `dist/claude/{init,settings-merge,shim-template}.js` present (`ls dist/claude`).++- [ ] **Step 3: Consumer smoke — prove the shim resolves an *installed* package**++Simulate a consumer repo whose `node_modules/@nanonets/graft` points at this build:++```bash+CONSUMER=$(mktemp -d)+mkdir -p "$CONSUMER/node_modules/@nanonets"+ln -s "$PWD" "$CONSUMER/node_modules/@nanonets/graft"+node dist/cli.js init "$CONSUMER" --no-build+# drive the written statusline shim as Claude Code would, from the consumer dir:+CLAUDE_PROJECT_DIR="$CONSUMER" bash -c 'echo "{\"session_id\":\"t\",\"cwd\":\"$CLAUDE_PROJECT_DIR\"}" | node "$CLAUDE_PROJECT_DIR/.claude/helpers/graft-statusline.cjs"'+```+Expected: the shim resolves `@nanonets/graft/package.json` from the consumer dir → imports THIS repo's `dist/claude/statusline.js` → renders a graft bar (the consumer has no graph, so it shows `graft · not built · run graft build` — which is the correct, resolved output, proving the package path works). `rm -rf "$CONSUMER"` after.++- [ ] **Step 4: Bump version to 0.3.0**++```bash+npm version 0.3.0 --no-git-tag-version+git add package.json package-lock.json 2>/dev/null; git commit -m "chore(release): 0.3.0 — graft init onboarding"+```++- [ ] **Step 5: Final confirmation for the controller**++Report: full suite green, build clean, consumer smoke resolved the installed-package path, version at 0.3.0. Publishing (security-key 2FA) is a controller/human step, not part of this task.++---++## Notes for the implementer++- Never add `--deep` anywhere. `runInit`'s build is plain `graft build`.+- The consumer shims must resolve the package via `require.resolve('@nanonets/graft/package.json', { paths: [dir] })`, then import the absolute `dist/claude/*.js` — do NOT `import('@nanonets/graft/dist/claude/...')` (blocked by the `exports` map).+- Keep the merge non-destructive: foreign keys, foreign `statusLine`, and foreign hook entries must survive; Graft entries de-dupe on re-run.diff --git a/docs/superpowers/specs/2026-07-20-graft-init-onboarding-design.md b/docs/superpowers/specs/2026-07-20-graft-init-onboarding-design.mdnew file mode 100644index 00000000..2c5beba0--- /dev/null+++ b/docs/superpowers/specs/2026-07-20-graft-init-onboarding-design.md@@ -0,0 +1,143 @@+# `graft init` — one-command onboarding for the Claude Code integration++**Date:** 2026-07-20+**Status:** Draft for review+**Owner:** Shrish+**Scope:** One implementation plan. Builds on the shipped `.claude/` integration (`src/claude/*`).++## 1. Goal++Make the Claude Code integration work in **any** repo that installs `@nanonets/graft`, not just Graft's own repo. After install, a single command wires everything up:++```+npm i -D @nanonets/graft # postinstall prints a one-line nudge+npx graft init # scaffolds .claude/, builds the graph — done+# open Claude Code in the repo → statusline + hooks + auto-sync live+```++## 2. Why it doesn't work today (the two gaps)++1. **Shims resolve the wrong place.** `.claude/helpers/graft-*.cjs` import `<CLAUDE_PROJECT_DIR>/dist/claude/*.js` — the *consumer's* dist, which only exists in Graft's own repo. In any other repo that path is empty, so the statusline/hooks silently no-op.+2. **No installer.** The `.claude/settings.json` + shims exist in Graft's repo only because they were hand-authored. A fresh `npm i @nanonets/graft` drops zero `.claude/` files.++Also relevant: `package.json` has a **restrictive `exports` map** (`"."` only), so a consumer shim cannot `import('@nanonets/graft/dist/claude/…')` — Node blocks non-declared subpaths. The fix resolves the package's location on disk and dynamic-imports the **absolute** file path (which bypasses `exports`).++## 3. Scope++**In scope:**+- Smart shims that resolve the installed package (with a local-build fallback for Graft's own repo).+- `exports` addition: `"./package.json": "./package.json"` (guarantees the resolve).+- `graft init` command: merge settings, write shims, build graph if absent, print next steps. Idempotent.+- `postinstall` nudge script.+- Version bump to `0.3.0` and publish.++**Out of scope (deferred):**+- An interactive wizard / key prompt flow (init just *tells* the user about `OPENROUTER_API_KEY`).+- `graft init --uninstall` / teardown.+- A `graft doctor` health check for the integration.+- Auto-writing `.claude/` from `postinstall` (rejected — invasive, skipped under `--ignore-scripts`, can't prompt).++## 4. Design++### 4.1 Smart shim resolution (the core fix)++`graft init` writes each shim so it resolves the integration from wherever Graft actually lives:++```js+// .claude/helpers/graft-statusline.cjs+#!/usr/bin/env node+const path = require('path');+const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();+function entry(name) {+ try {+ // consumer repo: graft is an installed dependency+ const pkg = require.resolve('@nanonets/graft/package.json', { paths: [dir] });+ return path.join(path.dirname(pkg), 'dist', 'claude', name);+ } catch {+ // graft's own repo (dogfood): compiled into ./dist+ return path.join(dir, 'dist', 'claude', name);+ }+}+import(entry('statusline.js')).then((m) => m.main()).catch(() => { /* best-effort */ });+```++The hooks shim is identical except it imports `entry('hooks.js')` and calls `m.main(process.argv[2])`.++- Absolute-path `import()` is **not** subject to the `exports` map, so this works despite `"."`-only exports.+- Fallback path keeps Graft's own repo working (there, `@nanonets/graft` is not in `node_modules`, so `require.resolve` throws and we use `./dist`).+- Graft's **own committed** `.claude/helpers/*.cjs` are updated to this same smart form (single shim shape for both cases).++### 4.2 `package.json` change++Add `"./package.json"` to `exports` so `require.resolve('@nanonets/graft/package.json', …)` is guaranteed under strict resolution:++```json+"exports": {+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },+ "./package.json": "./package.json"+}+```++### 4.3 Settings merge (never clobber)++`mergeGraftSettings(existing) → { merged, warnings }`, a pure function:+- **statusLine:** set Graft's only if absent. If the user already has a `statusLine`, **skip it and emit a warning** (a session can have only one). subagentStatusLine: same rule.+- **hooks:** for each of `PostToolUse` / `UserPromptSubmit` / `SessionStart` / `Stop`, **append** Graft's hook entry to any existing array (create the array if absent). Dedupe: if a Graft entry (identified by the `graft-hooks.cjs` command string) is already present for that event, replace it rather than duplicate — makes re-running init idempotent.+- **footerLinksRegexes:** add Graft's regex if not already present (union, deduped).+- Everything else in the existing settings is preserved untouched.++### 4.4 `graft init` command++`graft init [dir] [--no-build]`:+1. Resolve target dir (arg or cwd).+2. Read existing `.claude/settings.json` (or `{}`); compute `mergeGraftSettings`; write it back (pretty JSON). Print any warnings.+3. Write `.claude/helpers/graft-statusline.cjs` and `graft-hooks.cjs` (smart shims), `chmod +x`.+4. If no `graft/.graph/wiring.json` exists and not `--no-build`: run a structural `graft build` ($0). Never `--deep`.+5. Print a short next-steps block: what was written, that the integration activates in Claude Code sessions here, and that `OPENROUTER_API_KEY` + `graft build --deep` enriches summaries.+6. Idempotent: re-running updates in place, no duplicates.++Implemented as `runInit(dir, { build }): InitResult` in `src/claude/init.ts`; `cli.ts` adds `.command("init")`.++### 4.5 Install nudge (`postinstall`)++`scripts/postinstall.mjs`, wired as `"postinstall"` in `package.json`:+- Prints one line: `Graft installed. Run \`npx graft init\` to enable the Claude Code integration (statusline + hooks + auto-sync).`+- **Never fails the install:** wrapped so any error exits 0.+- **Quiet when noise would hurt:** skip if `CI` is set, if `.claude/helpers/graft-statusline.cjs` already exists (already initialized), or if not a TTY-ish interactive install (best-effort check). Skipping is silent.++### 4.6 Money guard (unchanged, still binding)++`graft init`'s build step and everything downstream run only plain `graft build` — structural, offline, `$0`. Never `--deep`. Enrichment stays a manual, explicit, keyed step.++## 5. File structure++**Created:**+- `src/claude/settings-merge.ts` — `mergeGraftSettings` (pure) + the Graft block constants.+- `src/claude/shim-template.ts` — `statuslineShim()` / `hooksShim()` returning the `.cjs` source strings.+- `src/claude/init.ts` — `runInit(dir, opts)` orchestration.+- `scripts/postinstall.mjs` — the nudge.+- `test/claude-settings-merge.test.ts`, `test/claude-init.test.ts` — tests.++**Modified:**+- `src/cli.ts` — add the `init` command.+- `.claude/helpers/graft-statusline.cjs`, `.claude/helpers/graft-hooks.cjs` — updated to the smart-resolution form.+- `package.json` — `exports["./package.json"]`, `scripts.postinstall`, version `0.3.0`.++## 6. Testing++- **settings-merge (unit):** empty settings → full Graft blocks; existing foreign `statusLine` → skipped + warning; existing hooks array → Graft appended; re-run → idempotent (no dupes); foreign keys preserved.+- **shim-template (unit):** generated source is valid JS (loads via `require`/`new Function`) and contains both the package-resolve and the local-fallback branches.+- **init (integration):** run `runInit` in a temp dir → asserts `.claude/settings.json` + both shims written, graph build skipped with `--no-build`, and a second run is idempotent.+- **consumer smoke (manual, in verification task):** create a throwaway dir with a fake `node_modules/@nanonets/graft` (symlink to the built package), run the written statusline shim with a stdin payload, confirm it resolves the package path and renders (not "not built").+- Full suite stays green; `npm run build` clean.++## 7. Publish (after the branch merges / or from the branch once green)++- Bump `0.3.0` (minor — additive feature, no breaking change to existing CLI).+- `npm publish` requires **security-key 2FA** — use the established pseudo-TTY + auto-ENTER recipe so npm opens the browser and the key is tapped in one shot (tokens expire fast; a publish 404 means auth, not a missing package).+- Post-publish verify: `npm view @nanonets/graft version` shows `0.3.0`; a scratch `npm i @nanonets/graft && npx graft init` in a temp repo wires up and renders.++## 8. Open decisions++1. **`graft init` runs `graft build` by default** (with `--no-build` to skip). Confirmed: yes — keeps "one command → everything in place" true.+2. **postinstall nudge verbosity:** one line, skipped in CI / when already initialized. (Leaning: as specified — minimal.)