Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
fix(init): robust shim resolution so global installs get the statusline
anirudhkumar-nanonets553371cc32b1
diff --git a/package.json b/package.jsonindex 36fac4c2..76a09f1d 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@nanonets/graft",- "version": "0.4.1",+ "version": "0.4.2","description": "Build a repo's context graph as a folder of linked markdown files that live in the repo and stay in sync with the code through git.","keywords": ["ai",diff --git a/src/claude/init.ts b/src/claude/init.tsindex 4e7abb42..aa71e51b 100644--- a/src/claude/init.ts+++ b/src/claude/init.ts@@ -4,6 +4,7 @@ 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';export interface InitResult {settingsPath: string;@@ -25,8 +26,9 @@ export function runInit(dir: string, opts: { build?: boolean; cliPath?: string }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);+ 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.diff --git a/src/claude/paths.ts b/src/claude/paths.tsindex e9f73a9f..12022f7d 100644--- a/src/claude/paths.ts+++ b/src/claude/paths.ts@@ -12,6 +12,13 @@ export function graftCliPath(): string {return join(CLAUDE_DIR, '..', 'cli.js');}+/** Absolute path to this package's `dist/claude` dir. Baked into the generated shims at+ * init time as their primary resolution candidate, so the statusline/hooks find graft+ * without runtime guesswork — correct regardless of how Node was installed. */+export function claudeDistDir(): string {+ return CLAUDE_DIR;+}+/** Absolute path to a sibling script in the claude dir (e.g. `sync-run.js`). */export function claudeScriptPath(name: string): string {return join(CLAUDE_DIR, name);diff --git a/src/claude/shim-template.ts b/src/claude/shim-template.tsindex c65bb9da..6499946e 100644--- a/src/claude/shim-template.ts+++ b/src/claude/shim-template.ts@@ -1,20 +1,63 @@-function shim(entryFile: string, call: string): string {+// Generates the tiny `.cjs` shims committed into a repo's `.claude/helpers/`. Their only+// job is to locate the installed `@nanonets/graft` package's `dist/claude/<entry>.js` and+// call into it — so the real logic lives in the package and upgrades with it.+//+// Resolution order (first hit wins), designed so a global install works regardless of how+// Node was installed (Homebrew/Windows/volta all shipped broken before this):+// 1. `bakedDir` — the absolute `dist/claude` graft was running from at init time.+// Correct with zero guesswork for whoever ran `graft init`.+// 2. repo node_modules — a local dev-dep install.+// 3. `execDir/../lib` — the cheap legacy guess (covers nvm / classic prefix layout).+// 4. `npm root -g` — authoritative global dir, layout-agnostic. Only shelled out to+// when 1–3 miss (the baked path hits first for the installer), so it's+// rarely reached; queried on demand — no on-disk cache, which on a+// shared machine would be a world-writable path an attacker could point+// at their own code for us to import.+function shim(entryFile: string, call: string, bakedDir: string): string {return `#!/usr/bin/env nodeconst path = require('path');+const fs = require('fs');+const { pathToFileURL } = require('url');+const { execFileSync } = require('child_process');const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();+const BAKED = ${JSON.stringify(bakedDir)};++// The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched.+function fromPkg(base) {+ try {+ const pkg = require.resolve('@nanonets/graft/package.json', { paths: [base] });+ return path.join(path.dirname(pkg), 'dist', 'claude');+ } catch { return null; }+}++// The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand.+function globalRoot() {+ try {+ const root = execFileSync('npm', ['root', '-g'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], shell: true }).trim();+ return root || null;+ } catch { return null; /* npm unavailable */ }+}++function candidates() {+ const out = [];+ if (BAKED) out.push(BAKED);+ const local = fromPkg(dir); if (local) out.push(local);+ const legacy = fromPkg(path.join(path.dirname(process.execPath), '..', 'lib')); if (legacy) out.push(legacy);+ const gr = globalRoot(); if (gr) out.push(path.join(gr, '@nanonets', 'graft', 'dist', 'claude'));+ return out;+}+function entry(name) {- const globalBase = path.join(path.dirname(process.execPath), '..', 'lib');- for (const base of [dir, globalBase]) {- try {- const pkg = require.resolve('@nanonets/graft/package.json', { paths: [base] });- return path.join(path.dirname(pkg), 'dist', 'claude', name);- } catch { /* try next base */ }+ for (const d of candidates()) {+ const f = path.join(d, name);+ if (fs.existsSync(f)) return f;}- return path.join(dir, 'dist', 'claude', name);+ return path.join(dir, 'dist', 'claude', name); // last-ditch; import will no-op if absent}-import(entry(${JSON.stringify(entryFile)})).then((m) => ${call}).catch(() => { /* graft unavailable — no-op */ });++import(pathToFileURL(entry(${JSON.stringify(entryFile)})).href).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])'); }+export function statuslineShim(bakedDir: string): string { return shim('statusline.js', 'm.main()', bakedDir); }+export function hooksShim(bakedDir: string): string { return shim('hooks.js', 'm.main(process.argv[2])', bakedDir); }diff --git a/test/claude-shim-template.test.ts b/test/claude-shim-template.test.tsindex f456e3c6..0252941c 100644--- a/test/claude-shim-template.test.ts+++ b/test/claude-shim-template.test.ts@@ -3,19 +3,31 @@ 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 resolves local + global, with local fallback`, () => {+const BAKED = '/opt/graft/dist/claude';++for (const [name, src] of [['statusline', statuslineShim(BAKED)], ['hooks', hooksShim(BAKED)]] as const) {+ test(`${name} shim parses and resolves via baked → node_modules → lib → npm root -g`, () => {const body = src.replace(/^#!.*\n/, ''); // strip shebang for vmassert.doesNotThrow(() => new vm.Script(body), 'valid JS');++ // 1. baked dir is present as the first candidate+ assert.match(src, new RegExp(`const BAKED = "${BAKED}"`));+ // 2. repo node_modules via require.resolve from the project dirassert.match(src, /require\.resolve\('@nanonets\/graft\/package\.json', \{ paths: \[base\] \}\)/);- assert.match(src, /const globalBase = path\.join\(path\.dirname\(process\.execPath\), '\.\.', 'lib'\)/);- assert.match(src, /for \(const base of \[dir, globalBase\]\)/);- assert.match(src, /path\.join\(dir, 'dist', 'claude'/);- assert.match(src, /\.catch\(\(\) => \{/); // best-effort+ assert.match(src, /fromPkg\(dir\)/);+ // 3. legacy execPath/../lib guess retained+ assert.match(src, /path\.join\(path\.dirname\(process\.execPath\), '\.\.', 'lib'\)/);+ // 4. npm root -g catch-all, queried on demand (no on-disk cache)+ assert.match(src, /execFileSync\('npm', \['root', '-g'\]/);+ assert.doesNotMatch(src, /tmpdir/); // no predictable temp cache path++ // Windows-safe dynamic import + best-effort catch+ assert.match(src, /pathToFileURL\(entry\(/);+ assert.match(src, /\.catch\(\(\) => \{/);});}test('statusline calls main(); hooks passes the event arg', () => {- assert.match(statuslineShim(), /m\.main\(\)/);- assert.match(hooksShim(), /m\.main\(process\.argv\[2\]\)/);+ assert.match(statuslineShim(BAKED), /m\.main\(\)/);+ assert.match(hooksShim(BAKED), /m\.main\(process\.argv\[2\]\)/);});