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
feat(cli): version + upgrade commands; friendlier init next-steps; brand color pass
Shrish Dwivedia07bf940464c
diff --git a/README.md b/README.mdindex 708f13a5..5d50e4e4 100644--- a/README.md+++ b/README.md@@ -204,8 +204,12 @@ graft init --agents cursor kiro # wire only these agents (ids: agents, cursgraft init --all-agents # wire every known agent, detected or notgraft init --list-agents # list known agent ids and exit+graft version # print the installed + latest published npm version+graft upgrade # npm install -g the latest published version+# globalgraft --dir <path> # use a context dir other than <repo>/graft+graft --version, -v # print the installed version and exit```## Visualize it (`graft viz`)diff --git a/src/cli-epilogue.ts b/src/cli-epilogue.tsindex 46894394..fec47e82 100644--- a/src/cli-epilogue.ts+++ b/src/cli-epilogue.ts@@ -17,6 +17,12 @@ const WORDMARK_LINES = [];const STATS_LINE_INDEX = 4;+// Nanonets indigo, and a muted grey for the secondary stats suffix — only+// applied when stderr is a real TTY (tests spawn/call this without one, so+// existing plain-text assertions keep passing).+const indigo = (s: string) => `\x1b[38;2;84;111;255m${s}\x1b[0m`;+const muted = (s: string) => `\x1b[38;5;244m${s}\x1b[0m`;+interface Step {label: string;command: string;@@ -37,21 +43,25 @@ export interface InitEpilogueOptions {* caller's `console.error` adds the one trailing newline). */export function formatInitEpilogue(opts: InitEpilogueOptions): string {const { graphBuilt, nodes, edges } = opts;+ const tty = Boolean(process.stderr.isTTY);- const wordmark = [...WORDMARK_LINES];+ const wordmark = WORDMARK_LINES.map((l) => (tty ? indigo(l) : l));if (graphBuilt && nodes !== undefined && edges !== undefined) {- wordmark[STATS_LINE_INDEX] =- `${wordmark[STATS_LINE_INDEX]} ${nodes.toLocaleString("en-US")} nodes · ${edges.toLocaleString("en-US")} edges`;+ const stats = ` ${nodes.toLocaleString("en-US")} nodes · ${edges.toLocaleString("en-US")} edges`;+ wordmark[STATS_LINE_INDEX] += tty ? muted(stats) : stats;}const steps: Step[] = [...(graphBuilt ? [] : [{ label: "build the graph", command: "graft build" }]),- { label: "commit the map", command: 'git add graft .claude && git commit -m "add graft"' },- { label: "restart your agent", command: "the next session picks up the skill + statusline" },+ { label: "restart your agent", command: "a new session picks up graft automatically" },+ {+ label: "code as usual",+ command: "ask your agent to fix a bug or explain a flow —",+ extra: ["it now answers from the graph"],+ },{- label: "try it",- command: 'graft ask "where is auth handled?"',- extra: ["graft callers <function> · graft viz"],+ label: "explore by hand",+ command: 'graft ask "where is auth handled?" · graft callers <fn> · graft viz',},];@@ -69,5 +79,7 @@ export function formatInitEpilogue(opts: InitEpilogueOptions): string {}});- return [...wordmark, "", ...stepLines].join("\n");+ const closing = `${indent}when it clicks: git add graft .claude && git commit — every teammate's agent gets the map`;++ return [...wordmark, "", ...stepLines, "", closing].join("\n");}diff --git a/src/cli-meta.ts b/src/cli-meta.tsnew file mode 100644index 00000000..01767fc9--- /dev/null+++ b/src/cli-meta.ts@@ -0,0 +1,143 @@+/**+ * `graft version` / `graft --version` / `graft upgrade` support.+ *+ * Split out of cli.ts so the formatting helpers can be unit-tested with+ * injected results instead of hitting the network from tests.+ */+import { existsSync, readFileSync } from "node:fs";+import { execFileSync, spawnSync } from "node:child_process";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const PKG_NAME = "@nanonets/graft";++/** Locates package.json relative to a module URL (works for both `dist/cli.js`+ * running one level under the published package root, and `src/cli.ts` running+ * one level under the repo root via tsx). */+export function resolvePackageJsonPath(moduleUrl: string): string {+ const moduleDir = dirname(fileURLToPath(moduleUrl));+ const candidates = [resolve(moduleDir, "..", "package.json"), resolve(moduleDir, "package.json")];+ for (const c of candidates) {+ if (existsSync(c)) return c;+ }+ return candidates[0];+}++/** Reads the version of the graft package this module was loaded from. */+export function readCurrentVersion(moduleUrl: string): string {+ const raw = readFileSync(resolvePackageJsonPath(moduleUrl), "utf8");+ const pkg = JSON.parse(raw) as { version?: string };+ return pkg.version ?? "0.0.0";+}++/** True when the running module lives under an npx cache dir (e.g.+ * `~/.npm/_npx/<hash>/node_modules/...`) rather than a regular global install. */+export function isRunningViaNpx(moduleUrl: string): boolean {+ return fileURLToPath(moduleUrl).includes("/_npx/");+}++export interface NpmViewResult {+ ok: boolean;+ version?: string;+}++/** `npm view <pkg> version`, offline-safe: any failure (no npm, no network,+ * timeout) resolves to `{ ok: false }` rather than throwing. */+export function getNpmViewVersion(pkgName: string = PKG_NAME, timeoutMs = 2000): NpmViewResult {+ try {+ const res = spawnSync("npm", ["view", pkgName, "version"], {+ encoding: "utf8",+ timeout: timeoutMs,+ windowsHide: true,+ });+ if (res.error || res.signal || res.status !== 0) return { ok: false };+ const version = res.stdout?.trim();+ if (!version) return { ok: false };+ return { ok: true, version };+ } catch {+ return { ok: false };+ }+}++/** Pure formatter for `graft version` — no I/O, easy to unit-test. */+export function formatVersionReport(current: string, latest: NpmViewResult): string {+ const lines = [`graft ${current}`];+ if (!latest.ok || !latest.version) {+ lines.push("latest: unreachable (offline?)");+ } else if (latest.version === current) {+ lines.push(`latest on npm: ${current} ✓ up to date`);+ } else {+ lines.push(`latest on npm: ${latest.version} — run graft upgrade`);+ }+ return lines.join("\n");+}++/** The global npm node_modules dir (handles Homebrew/Windows/volta layouts). */+function globalRoot(): string | null {+ try {+ const root = execFileSync("npm", ["root", "-g"], {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ shell: process.platform === "win32",+ }).trim();+ return root || null;+ } catch {+ return null;+ }+}++/** Reads the version actually sitting in the global install, straight from+ * disk — more reliable right after `npm install -g` than re-querying the+ * registry (which just tells you what "latest" is, not what landed locally). */+export function readGlobalInstalledVersion(pkgName: string = PKG_NAME): string | null {+ const root = globalRoot();+ if (!root) return null;+ const pkgJson = join(root, ...pkgName.split("/"), "package.json");+ if (!existsSync(pkgJson)) return null;+ try {+ const pkg = JSON.parse(readFileSync(pkgJson, "utf8")) as { version?: string };+ return pkg.version ?? null;+ } catch {+ return null;+ }+}++export interface UpgradeResult {+ /** True when `npm install -g` actually ran (false for the npx no-op path). */+ ran: boolean;+ ok: boolean;+ /** Present when ran=true and the install failed. */+ errorMessage?: string;+ oldVersion?: string;+ newVersion?: string;+}++/** Pure formatter for a finished upgrade — no I/O, easy to unit-test. */+export function formatUpgradeReport(result: UpgradeResult): string {+ if (!result.ran) {+ return (+ "running via npx — npx already fetches the latest graft on every run.\n" ++ "For a permanent install: npm install -g @nanonets/graft"+ );+ }+ if (!result.ok) {+ return `✗ npm install -g ${PKG_NAME}@latest failed${result.errorMessage ? `: ${result.errorMessage}` : ""}`;+ }+ return `graft ${result.oldVersion ?? "?"} → ${result.newVersion ?? result.oldVersion ?? "?"}`;+}++/** Runs `npm install -g @nanonets/graft@latest` (inheriting stdio so the user+ * sees npm's own progress/errors), then re-reads the freshly installed+ * version. No-ops with guidance when running via npx. */+export function runUpgrade(moduleUrl: string): UpgradeResult {+ const oldVersion = readCurrentVersion(moduleUrl);+ if (isRunningViaNpx(moduleUrl)) {+ return { ran: false, ok: true, oldVersion };+ }+ const res = spawnSync("npm", ["install", "-g", `${PKG_NAME}@latest`], { stdio: "inherit" });+ if (res.error || (res.status ?? 1) !== 0) {+ return { ran: true, ok: false, oldVersion, errorMessage: res.error?.message };+ }+ const newVersion = readGlobalInstalledVersion(PKG_NAME) ?? getNpmViewVersion(PKG_NAME).version ?? oldVersion;+ return { ran: true, ok: true, oldVersion, newVersion };+}diff --git a/src/cli.ts b/src/cli.tsindex b18f48bd..478cb809 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -27,12 +27,15 @@ import { hostIds } from "./hosts/registry.js";import { contextDirFor } from "./context/node-file.js";import { loadGraphCached } from "./graph/load.js";import { formatInitEpilogue } from "./cli-epilogue.js";+import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, runUpgrade } from "./cli-meta.js";const program = new Command();+const currentVersion = readCurrentVersion(import.meta.url);program.name("graft").description("Build a repo's context graph as linked markdown, and keep it in sync with the code.")+ .version(currentVersion, "-v, --version").option("--dir <path>", "context graph directory (default: <repo>/graft)");function engineFrom(): Graft {@@ -40,6 +43,23 @@ function engineFrom(): Graft {return new Graft({ contextDir: opts.dir });}+program+ .command("version")+ .description("Print the installed version and the latest published on npm")+ .action(() => {+ const latest = getNpmViewVersion();+ console.log(formatVersionReport(currentVersion, latest));+ });++program+ .command("upgrade")+ .description("Upgrade the globally installed graft to the latest version on npm")+ .action(() => {+ const result = runUpgrade(import.meta.url);+ console.log(formatUpgradeReport(result));+ if (result.ran && !result.ok) process.exit(1);+ });+program.command("build").description(diff --git a/test/claude-init.test.ts b/test/claude-init.test.tsindex 6a7729c6..71183adc 100644--- a/test/claude-init.test.ts+++ b/test/claude-init.test.ts@@ -93,25 +93,27 @@ test('formatInitEpilogue: graph built shows stats, wordmark, and the 3-step listconst out = formatInitEpilogue({ graphBuilt: true, nodes: 6398, edges: 10912 });assert.match(out, /\|___\/\s*$/m);assert.ok(out.includes('6,398 nodes · 10,912 edges'));- assert.ok(out.includes('1. commit the map'));- assert.ok(out.includes('2. restart your agent'));- assert.ok(out.includes('3. try it'));+ assert.ok(out.includes('1. restart your agent'));+ assert.ok(out.includes('2. code as usual'));+ assert.ok(out.includes('3. explore by hand'));assert.ok(out.includes('graft ask'));assert.ok(!out.includes('build the graph'));assert.ok(!out.includes('OPENROUTER'));+ assert.ok(out.includes('git add graft'));});test('formatInitEpilogue: graph not built shows "build the graph" as step 1, no stats, same column alignment', () => {const built = formatInitEpilogue({ graphBuilt: true, nodes: 4, edges: 4 });const notBuilt = formatInitEpilogue({ graphBuilt: false });assert.ok(notBuilt.includes('1. build the graph'));- assert.ok(notBuilt.includes('2. commit the map'));- assert.ok(notBuilt.includes('3. restart your agent'));- assert.ok(notBuilt.includes('4. try it'));+ assert.ok(notBuilt.includes('2. restart your agent'));+ assert.ok(notBuilt.includes('3. code as usual'));+ assert.ok(notBuilt.includes('4. explore by hand'));assert.ok(!notBuilt.includes('nodes ·'));+ assert.ok(notBuilt.includes('git add graft'));// the command column (after "restart your agent", the longest label) lines up// identically whether there are 3 or 4 numbered steps.- const col = (text: string, marker: string) => text.split('\n').find((l) => l.includes(marker))!.indexOf('the next session');+ const col = (text: string, marker: string) => text.split('\n').find((l) => l.includes(marker))!.indexOf('a new session');assert.equal(col(built, 'restart your agent'), col(notBuilt, 'restart your agent'));});@@ -124,7 +126,9 @@ test('CLI: graft init epilogue has the wordmark + next steps, and never mentions);assert.equal(res.status, 0, res.stderr);assert.ok(res.stderr.includes('|___/'), 'wordmark present');- assert.ok(res.stderr.includes('commit the map'));+ assert.ok(res.stderr.includes('code as usual'));+ assert.ok(res.stderr.includes('restart your agent'));+ assert.ok(res.stderr.includes('git add graft'));assert.ok(res.stderr.includes('graft ask'));assert.ok(!res.stderr.includes('OPENROUTER'));// --no-build, never built before → "build the graph" is step 1diff --git a/test/cli-meta.test.ts b/test/cli-meta.test.tsnew file mode 100644index 00000000..8b3f0801--- /dev/null+++ b/test/cli-meta.test.ts@@ -0,0 +1,80 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { pathToFileURL } from 'node:url';+import { resolve } from 'node:path';+import {+ formatVersionReport,+ formatUpgradeReport,+ resolvePackageJsonPath,+ readCurrentVersion,+ isRunningViaNpx,+} from '../src/cli-meta.js';++// --- formatVersionReport: pure formatting, injected npm-view results (no network) ---++test('formatVersionReport: up to date', () => {+ const out = formatVersionReport('0.4.4', { ok: true, version: '0.4.4' });+ assert.equal(out, 'graft 0.4.4\nlatest on npm: 0.4.4 ✓ up to date');+});++test('formatVersionReport: newer version available', () => {+ const out = formatVersionReport('0.4.4', { ok: true, version: '0.4.5' });+ assert.equal(out, 'graft 0.4.4\nlatest on npm: 0.4.5 — run graft upgrade');+});++test('formatVersionReport: offline / unreachable', () => {+ const out = formatVersionReport('0.4.4', { ok: false });+ assert.equal(out, 'graft 0.4.4\nlatest: unreachable (offline?)');+});++// --- formatUpgradeReport: pure formatting, injected upgrade results (no network, no spawn) ---++test('formatUpgradeReport: npx no-op suggests a permanent install', () => {+ const out = formatUpgradeReport({ ran: false, ok: true, oldVersion: '0.4.4' });+ assert.match(out, /npx/);+ assert.match(out, /npm install -g @nanonets\/graft/);+});++test('formatUpgradeReport: successful upgrade shows old -> new', () => {+ const out = formatUpgradeReport({ ran: true, ok: true, oldVersion: '0.4.4', newVersion: '0.4.5' });+ assert.equal(out, 'graft 0.4.4 → 0.4.5');+});++test('formatUpgradeReport: failed install surfaces the error', () => {+ const out = formatUpgradeReport({ ran: true, ok: false, oldVersion: '0.4.4', errorMessage: 'ENOENT' });+ assert.match(out, /failed/);+ assert.match(out, /ENOENT/);+});++// --- resolvePackageJsonPath / readCurrentVersion: real filesystem, no network ---++test('resolvePackageJsonPath finds package.json one level above a dist/cli.js-shaped module path', () => {+ const fakeDistCli = pathToFileURL(resolve(process.cwd(), 'dist/cli.js')).href;+ const found = resolvePackageJsonPath(fakeDistCli);+ assert.equal(found, resolve(process.cwd(), 'package.json'));+});++test('resolvePackageJsonPath finds package.json one level above a src/cli.ts-shaped module path', () => {+ const fakeSrcCli = pathToFileURL(resolve(process.cwd(), 'src/cli.ts')).href;+ const found = resolvePackageJsonPath(fakeSrcCli);+ assert.equal(found, resolve(process.cwd(), 'package.json'));+});++test('readCurrentVersion reads the real package.json version', () => {+ const pkg = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8'));+ const v = readCurrentVersion(pathToFileURL(resolve(process.cwd(), 'src/cli.ts')).href);+ assert.equal(v, pkg.version);+});++// --- isRunningViaNpx: pure path heuristic ---++test('isRunningViaNpx detects an npx cache path', () => {+ const npxPath = pathToFileURL('/Users/x/.npm/_npx/abc123/node_modules/@nanonets/graft/dist/cli.js').href;+ assert.equal(isRunningViaNpx(npxPath), true);+});++test('isRunningViaNpx is false for a regular global install', () => {+ const globalPath = pathToFileURL('/usr/local/lib/node_modules/@nanonets/graft/dist/cli.js').href;+ assert.equal(isRunningViaNpx(globalPath), false);+});diff --git a/viewer/style.css b/viewer/style.cssindex 3b9682e5..81e12642 100644--- a/viewer/style.css+++ b/viewer/style.css@@ -2,36 +2,36 @@Visual reference of record: docs/superpowers/specs/2026-07-15-graft-viz-design.md */:root{--bg:#F4F6F6; --panel:#FFFFFF; --panel2:#FBFCFC; --ink:#17191B; --muted:#6B7278;- --border:#E2E6E7; --border2:#EDF0F1; --accent:#0B7A69; --accent-ink:#0B7A69;+ --border:#E2E6E7; --border2:#EDF0F1; --accent:#546FFF; --accent-ink:#546FFF;--chip:#F0F3F3;- --sys:#4A7DF0; --con:#A06BDB; --fil:#D98E2B; --api:#D65C7E;- --k-file:#D98E2B; --k-class:#4A7DF0; --k-fn:#0FA38A; --k-method:#3AA7C9; --k-iface:#A06BDB; --k-type:#D65C7E; --k-enum:#6BAA3F;+ --sys:#4A7DF0; --con:#A06BDB; --fil:#D98E2B; --api:#C95CB8;+ --k-file:#D98E2B; --k-class:#4A7DF0; --k-fn:#4F86C6; --k-method:#3AA7C9; --k-iface:#A06BDB; --k-type:#C95CB8; --k-enum:#B69B3D;--edge:#9AA4A9; --canvas:#F8FAFA;}@media (prefers-color-scheme: dark){:root{--bg:#0E1012; --panel:#15181B; --panel2:#111417; --ink:#E7E9EA; --muted:#8B9298;- --border:#252B30; --border2:#1D2226; --accent:#2FBFA4; --accent-ink:#2FBFA4;+ --border:#252B30; --border2:#1D2226; --accent:#7B8FFF; --accent-ink:#7B8FFF;--chip:#1C2125;- --sys:#6B94F5; --con:#B487E0; --fil:#E0A04A; --api:#E07A97;- --k-file:#E0A04A; --k-class:#6B94F5; --k-fn:#2FBFA4; --k-method:#56B9D8; --k-iface:#B487E0; --k-type:#E07A97; --k-enum:#8CC45E;+ --sys:#6B94F5; --con:#B487E0; --fil:#E0A04A; --api:#D183C9;+ --k-file:#E0A04A; --k-class:#6B94F5; --k-fn:#7EAEDD; --k-method:#56B9D8; --k-iface:#B487E0; --k-type:#D183C9; --k-enum:#D4BB5E;--edge:#4A545B; --canvas:#101315;}}:root[data-theme="dark"]{--bg:#0E1012; --panel:#15181B; --panel2:#111417; --ink:#E7E9EA; --muted:#8B9298;- --border:#252B30; --border2:#1D2226; --accent:#2FBFA4; --accent-ink:#2FBFA4;+ --border:#252B30; --border2:#1D2226; --accent:#7B8FFF; --accent-ink:#7B8FFF;--chip:#1C2125;- --sys:#6B94F5; --con:#B487E0; --fil:#E0A04A; --api:#E07A97;- --k-file:#E0A04A; --k-class:#6B94F5; --k-fn:#2FBFA4; --k-method:#56B9D8; --k-iface:#B487E0; --k-type:#E07A97; --k-enum:#8CC45E;+ --sys:#6B94F5; --con:#B487E0; --fil:#E0A04A; --api:#D183C9;+ --k-file:#E0A04A; --k-class:#6B94F5; --k-fn:#7EAEDD; --k-method:#56B9D8; --k-iface:#B487E0; --k-type:#D183C9; --k-enum:#D4BB5E;--edge:#4A545B; --canvas:#101315;}:root[data-theme="light"]{--bg:#F4F6F6; --panel:#FFFFFF; --panel2:#FBFCFC; --ink:#17191B; --muted:#6B7278;- --border:#E2E6E7; --border2:#EDF0F1; --accent:#0B7A69; --accent-ink:#0B7A69;+ --border:#E2E6E7; --border2:#EDF0F1; --accent:#546FFF; --accent-ink:#546FFF;--chip:#F0F3F3;- --sys:#4A7DF0; --con:#A06BDB; --fil:#D98E2B; --api:#D65C7E;- --k-file:#D98E2B; --k-class:#4A7DF0; --k-fn:#0FA38A; --k-method:#3AA7C9; --k-iface:#A06BDB; --k-type:#D65C7E; --k-enum:#6BAA3F;+ --sys:#4A7DF0; --con:#A06BDB; --fil:#D98E2B; --api:#C95CB8;+ --k-file:#D98E2B; --k-class:#4A7DF0; --k-fn:#4F86C6; --k-method:#3AA7C9; --k-iface:#A06BDB; --k-type:#C95CB8; --k-enum:#B69B3D;--edge:#9AA4A9; --canvas:#F8FAFA;}