Skip to content

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

feat: auto-update graft and the wiring it writes

anirudhkumar-nanonetsffdd75cf85d5
diff --git a/src/claude/hooks.ts b/src/claude/hooks.ts
index 68d51eee..6e056b9c 100644
--- a/src/claude/hooks.ts
+++ b/src/claude/hooks.ts
@@ -6,6 +6,8 @@ import { formatBlastRadius, relevantRetrieval, formatOrientation } from './forma
import { indexFreshness, staleBanner } from '../context/check.js';
import { patchStats, readStats, acquireLock, readSession, writeSession } from './state.js';
import { graftCliPath, claudeScriptPath } from './paths.js';
+import { runUpkeep } from '../upkeep-run.js';
+import { runningVersion } from '../upkeep.js';
import { scopeOf, scopesOfGraph } from '../graph/scopes.js';
/** Prompts shorter than this never trigger retrieval — they are almost always
@@ -216,11 +218,20 @@ export async function main(event: string): Promise<void> {
const dir = projectDir(input);
if (event === 'session-start') {
+ // Before anything is emitted: refresh this repo's wiring if it was written by
+ // an older graft, and pick up any cached "newer version on npm" answer.
+ // background:false — a hook must never touch the network; the CLI and the MCP
+ // server fill that cache, this only reads it.
+ const upkeep = runUpkeep(dir, runningVersion(), { background: false }).lines;
try {
const idx = readFileSync(join(dir, 'graft', 'INDEX.md'), 'utf8');
const banner = staleBanner(indexFreshness(dir)) ?? undefined;
- emit('SessionStart', formatOrientation(idx, undefined, banner));
- } catch { /* no INDEX.md — skip */ }
+ const orientation = formatOrientation(idx, undefined, banner);
+ emit('SessionStart', upkeep.length ? `${upkeep.join('\n')}\n\n${orientation}` : orientation);
+ } catch {
+ // No INDEX.md (never built here). An upgrade nudge is still worth saying.
+ if (upkeep.length) emit('SessionStart', upkeep.join('\n'));
+ }
return;
}
diff --git a/src/claude/shim-template.ts b/src/claude/shim-template.ts
index 5168194b..39c4775c 100644
--- a/src/claude/shim-template.ts
+++ b/src/claude/shim-template.ts
@@ -2,17 +2,22 @@
// 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):
+// Candidates, cheapest first (no subprocess for 1–3):
// 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
+// when 1–3 all miss; 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.
+//
+// Among the candidates that exist we take the HIGHEST VERSION, not the first hit. First-hit
+// silently pinned users to a stale graft forever: `bakedDir` points into one Node install's
+// global node_modules, so switching Node versions (nvm/volta) or moving the install leaves
+// the old directory on disk and still winning, and `npm i -g @nanonets/graft@latest`
+// upgrades a directory the shim never looks at. The upgrade appeared to work and changed
+// nothing — the shim kept loading the version from whenever `graft init` was last run.
function shim(entryFile: string, call: string, bakedDir: string): string {
return `#!/usr/bin/env node
const path = require('path');
@@ -38,20 +43,45 @@ function globalRoot() {
} 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;
+// The version of the package a dist/claude dir belongs to, or null if unreadable.
+function versionOf(distClaude) {
+ try {
+ return JSON.parse(fs.readFileSync(path.join(distClaude, '..', '..', 'package.json'), 'utf8')).version || null;
+ } catch { return null; }
}
-function entry(name) {
- for (const d of candidates()) {
- const f = path.join(d, name);
- if (fs.existsSync(f)) return f;
+// Numeric-dotted compare of the release part; an unreadable version loses to any known one.
+function newer(a, b) {
+ if (!a) return false;
+ if (!b) return true;
+ const p = (v) => String(v).split('-')[0].split('.').map((n) => Number(n) || 0);
+ const pa = p(a), pb = p(b);
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const d = (pa[i] || 0) - (pb[i] || 0);
+ if (d !== 0) return d > 0;
+ }
+ return false;
+}
+
+// The highest-versioned dir in \`dirs\` that actually contains \`name\`, or null.
+function best(dirs, name) {
+ let bestDir = null, bestVer = null;
+ for (const d of dirs) {
+ if (!d || !fs.existsSync(path.join(d, name))) continue;
+ const v = versionOf(d);
+ if (bestDir === null || newer(v, bestVer)) { bestDir = d; bestVer = v; }
}
+ return bestDir;
+}
+
+function entry(name) {
+ // Cheap candidates first, and only shell out to npm when every one of them misses.
+ const cheap = [BAKED, fromPkg(dir), fromPkg(path.join(path.dirname(process.execPath), '..', 'lib'))];
+ const hit = best(cheap, name);
+ if (hit) return path.join(hit, name);
+ const gr = globalRoot();
+ const global = gr && path.join(gr, '@nanonets', 'graft', 'dist', 'claude');
+ if (global && fs.existsSync(path.join(global, name))) return path.join(global, name);
return path.join(dir, 'dist', 'claude', name); // last-ditch; import will no-op if absent
}
diff --git a/src/cli.ts b/src/cli.ts
index d4c5b450..b2ed01ae 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -37,6 +37,7 @@ import { formatNonInteractiveHelp, formatPlan, runPicker } from "./cli-picker.js
import { homedir } from "node:os";
import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, runUpgrade } from "./cli-meta.js";
import { writeBuildConfig } from "./util/state.js";
+import { formatUpdateNudge, maybeRefreshInBackground, readUpdateCache, refreshUpdateCache, writeStamp } from "./upkeep.js";
const program = new Command();
const currentVersion = readCurrentVersion(import.meta.url);
@@ -127,6 +128,33 @@ async function refreshBefore(dir: string, opts: { refresh?: boolean }): Promise<
* as it is on disk, no rebuild. */
const NO_REFRESH_FLAG = ["--no-refresh", "skip the freshness check — answer from the graph as-is"] as const;
+/**
+ * Commands that own the upgrade story themselves (`version`, `upgrade`) or must
+ * not editorialize on stderr at startup (`mcp` runs its own upkeep at boot, and
+ * `_update-check` IS the fetch).
+ */
+const UPKEEP_SKIP = new Set(["version", "upgrade", "_update-check", "mcp"]);
+
+/**
+ * Every other command: top up the cached registry answer in the background and,
+ * if a newer graft is out, say so once on stderr. This is what makes the CLI the
+ * cache filler for the hooks, which are not allowed to touch the network.
+ */
+program.hook("preAction", (_parent, action) => {
+ if (UPKEEP_SKIP.has(action.name())) return;
+ maybeRefreshInBackground();
+ const nudge = formatUpdateNudge(currentVersion, readUpdateCache()?.latest);
+ if (nudge) console.error(nudge);
+});
+
+// Hidden from --help: only ever spawned detached by maybeRefreshInBackground.
+program
+ .command("_update-check", { hidden: true })
+ .description("internal: refresh the cached latest-version answer")
+ .action(() => {
+ refreshUpdateCache();
+ });
+
program
.command("version")
.description("Print the installed version and the latest published on npm")
@@ -694,6 +722,17 @@ function wireTarget(
console.error("· skipped out-of-repo writes (--no-global)");
}
+ // Record WHICH graft wrote this repo's agent files, and under which flags.
+ // Every entry point compares this against the running binary and re-writes
+ // them on a mismatch, so an `npm i -g` upgrade reaches the hooks/skill/rules
+ // too — not just the binary. The flags ride along so a refresh replays the
+ // user's choices (notably --no-global) instead of overriding them.
+ writeStamp(repo, currentVersion, ids, {
+ global: opts.global !== false,
+ mcp: opts.mcp !== false,
+ hooks: opts.hooks !== false,
+ });
+
// 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) {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 9e4d1649..86bb64ba 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -5,6 +5,8 @@
import { createInterface } from 'node:readline';
import { TOOLS, callTool } from './tools.js';
import { mcpInstructions } from './instructions.js';
+import { runUpkeep } from '../upkeep-run.js';
+import { runningVersion } from '../upkeep.js';
function send(msg: object): void {
process.stdout.write(`${JSON.stringify(msg)}\n`);
@@ -24,6 +26,15 @@ function replyError(id: unknown, code: number, message: string): void {
* lookup misses. The caller already knows it.
*/
export function startMcpServer(root: string, dirOverride?: string, version = '0'): void {
+ // The self-maintenance pass, run once at boot. This is the ONLY channel that
+ // reaches hosts with no hook support (Cursor, and any plain MCP client): it
+ // refreshes rule files an older `graft init` wrote, and kicks off the cached
+ // registry check. Both are fail-soft, and the resulting lines ride along in
+ // `instructions` below — stdout is protocol-only, so there is nowhere else to
+ // put them. Never blocks: the registry fetch happens in a detached child.
+ const upkeep = runUpkeep(root, runningVersion()).lines;
+ for (const line of upkeep) console.error(line);
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
rl.on('line', (line) => {
const text = line.trim();
@@ -44,7 +55,7 @@ export function startMcpServer(root: string, dirOverride?: string, version = '0'
capabilities: { tools: {} },
serverInfo: { name: 'graft', version },
// The one channel that survives tool deferral — see ./instructions.ts.
- instructions: mcpInstructions(),
+ instructions: upkeep.length ? `${upkeep.join('\n')}\n\n${mcpInstructions()}` : mcpInstructions(),
});
return;
case 'notifications/initialized':
diff --git a/src/upkeep-run.ts b/src/upkeep-run.ts
new file mode 100644
index 00000000..66c26c8c
--- /dev/null
+++ b/src/upkeep-run.ts
@@ -0,0 +1,71 @@
+/**
+ * The wired-up version of `./upkeep.ts` — one call every entry point makes.
+ *
+ * Split from `upkeep.ts` so that module stays pure and unit-testable (no init
+ * writes, no spawning): this file is the only place that knows how to actually
+ * re-run the wiring, and it is deliberately thin.
+ */
+import { runInit } from './claude/init.js';
+import { runHostsInit } from './hosts/init.js';
+import { graftCliPath } from './claude/paths.js';
+import {
+ formatUpdateNudge,
+ formatWiringRefresh,
+ maybeRefreshInBackground,
+ readUpdateCache,
+ reconcileWiring,
+ type WiringOpts,
+} from './upkeep.js';
+
+export interface UpkeepResult {
+ /** Lines worth showing the agent/user, already formatted. Usually empty. */
+ lines: string[];
+}
+
+/**
+ * Re-write the wiring for exactly the hosts a previous `init` chose here, with
+ * exactly the flags it was given.
+ *
+ * `build: false` matters: this runs at session start and at MCP boot, and a graph
+ * build there would stall the agent's first turn.
+ *
+ * The out-of-repo writes (`~/.codex/hooks.json`, `~/.codex/config.toml`) ARE
+ * included, because nothing else would ever refresh them: no skill, rule file, or
+ * MCP instruction tells an agent to run `graft init`, so leaving them out means a
+ * Codex user upgrades the binary and keeps the old hook config forever. They're
+ * safe to replay — `installCodexHooks` no-ops when `~/.codex` is absent, rewrites
+ * only its own entry (matched on `graft-hooks.cjs`), and reports `unchanged` when
+ * the bytes match. A user who declined them at init time is honoured via
+ * `opts.global`/`opts.hooks`, replayed from the stamp.
+ */
+function rewriteWiring(repo: string, hosts: string[], opts: WiringOpts): void {
+ if (hosts.includes('claude')) runInit(repo, { build: false, cliPath: graftCliPath() });
+ const others = hosts.filter((h) => h !== 'claude');
+ if (others.length)
+ runHostsInit(repo, { agents: others, global: opts.global, mcp: opts.mcp, hooks: opts.hooks });
+}
+
+/**
+ * @param repo the project dir
+ * @param current the running graft's version
+ * @param opts.background false in hook contexts: read the update cache, never
+ * spawn a fetch. Hooks run under a hard timeout and must stay off the network.
+ */
+export function runUpkeep(
+ repo: string,
+ current: string,
+ opts: { background?: boolean; home?: string } = {},
+): UpkeepResult {
+ const lines: string[] = [];
+ try {
+ const refreshed = reconcileWiring(repo, current, { rewrite: rewriteWiring });
+ const refreshLine = formatWiringRefresh(refreshed);
+ if (refreshLine) lines.push(refreshLine);
+ } catch { /* fail-soft: wiring refresh is never worth breaking a session for */ }
+ try {
+ if (opts.background !== false) maybeRefreshInBackground(opts.home);
+ const nudge = formatUpdateNudge(current, readUpdateCache(opts.home)?.latest);
+ if (nudge) lines.push(nudge);
+ } catch { /* same */ }
+ return { lines };
+}
diff --git a/src/upkeep.ts b/src/upkeep.ts
new file mode 100644
index 00000000..443df952
--- /dev/null
+++ b/src/upkeep.ts
@@ -0,0 +1,292 @@
+/**
+ * Self-maintenance: keeping an installed graft, and the wiring it wrote, current.
+ *
+ * Two independent kinds of staleness, both invisible to the user today:
+ *
+ * 1. **Binary staleness** — they installed once and never upgraded. `graft
+ * version` would tell them, but nobody runs it. So we keep a cached,
+ * machine-global registry answer and let every entry point surface a
+ * one-line nudge from it.
+ *
+ * 2. **Wiring staleness** — `graft init` copies hooks, shims, skill text and
+ * rule files INTO the repo. `npm i -g` replaces the binary but touches none
+ * of them, so a repo wired by 0.7 keeps 0.7's prompts and 0.7's hook
+ * timeouts forever (see the comment on `promptAskTimeout`, which exists
+ * only to work around exactly this). A version stamp written next to the
+ * graph lets any entry point notice the skew and re-run the writes.
+ *
+ * Everything here is fail-soft by construction: it runs inside hooks and inside
+ * the MCP server's boot path, where a throw is a broken session, and it must
+ * never block on the network — the registry is only ever read from cache, and
+ * the refresh happens in a detached child.
+ *
+ * Called from all three hosts' entry points so no editor is left out:
+ * • Claude Code — `session-start` hook (src/claude/hooks.ts)
+ * • Cursor/Codex — MCP server boot (src/mcp/server.ts), and any CLI command
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { spawn } from 'node:child_process';
+import { join } from 'node:path';
+import { homedir } from 'node:os';
+import { readJson, writeJsonAtomic, cacheDir } from './util/state.js';
+import { HOSTS } from './hosts/registry.js';
+import { START } from './hosts/sections.js';
+import { getNpmViewVersion, readCurrentVersion } from './cli-meta.js';
+import { graftCliPath } from './claude/paths.js';
+
+/**
+ * The version of the graft package this code was loaded from.
+ *
+ * Resolved from *this* module rather than the caller's: `readCurrentVersion`
+ * looks one level up from the module URL it's given, which lands on the package
+ * root for `dist/upkeep.js` but misses entirely for `dist/claude/hooks.js` and
+ * `dist/mcp/server.js`. Every caller asking here instead of passing its own
+ * `import.meta.url` is what keeps the hook and the MCP server from reading
+ * `0.0.0` and re-initing on every single session.
+ */
+export function runningVersion(): string {
+ try { return readCurrentVersion(import.meta.url); } catch { return '0.0.0'; }
+}
+
+/** How long a registry answer is considered current. A day: graft ships far less
+ * often than that, and this is a nudge, not a security update. */
+export const UPDATE_TTL_MS = 24 * 60 * 60 * 1000;
+
+/* -------------------------------------------------------------------------- */
+/* version comparison */
+/* -------------------------------------------------------------------------- */
+
+/** Numeric-dotted compare of the release part only (`1.2.3-beta.1` → `1.2.3`).
+ * Prerelease ordering doesn't matter here: the only question either caller asks
+ * is "is the thing on npm ahead of what's on disk", and a prerelease that
+ * compares equal simply produces no nudge. */
+export function compareVersions(a: string, b: string): number {
+ const parts = (v: string) => String(v).split('-')[0].split('.').map((n) => Number(n) || 0);
+ const pa = parts(a);
+ const pb = parts(b);
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
+ if (d !== 0) return d < 0 ? -1 : 1;
+ }
+ return 0;
+}
+
+export function isNewer(candidate: string | null | undefined, current: string): boolean {
+ if (!candidate) return false;
+ return compareVersions(candidate, current) > 0;
+}
+
+/* -------------------------------------------------------------------------- */
+/* the cached registry answer (machine-global) */
+/* -------------------------------------------------------------------------- */
+
+export interface UpdateCache {
+ /** Latest version seen on npm, or null when the last fetch failed. */
+ latest: string | null;
+ /** Epoch ms of the last *attempt* — written by the parent before it spawns the
+ * fetch, so a repeatedly-failing fetch can't make every command spawn a child. */
+ checkedAt: number;
+}
+
+/** Machine-global, not per-repo: "what's the latest graft" is one fact, and a
+ * dev with twelve repos should cost the registry one request a day, not twelve. */
+export function updateCachePath(home: string = homedir()): string {
+ return join(home, '.graft', 'update-check.json');
+}
+
+export function readUpdateCache(home?: string): UpdateCache | null {
+ return readJson<UpdateCache>(updateCachePath(home));
+}
+
+function writeUpdateCache(cache: UpdateCache, home?: string): void {
+ try { writeJsonAtomic(updateCachePath(home), cache); } catch { /* unwritable home — skip */ }
+}
+
+/**
+ * The `graft _update-check` command body: hit the registry, store the answer.
+ * Runs in a detached child so nothing user-facing ever waits on the network.
+ */
+export function refreshUpdateCache(home?: string, now = Date.now()): UpdateCache {
+ const res = getNpmViewVersion();
+ const cache: UpdateCache = { latest: res.ok ? (res.version ?? null) : null, checkedAt: now };
+ writeUpdateCache(cache, home);
+ return cache;
+}
+
+/** True when the cached answer is missing or older than the TTL. */
+export function needsRefresh(cache: UpdateCache | null, now = Date.now()): boolean {
+ return !cache || typeof cache.checkedAt !== 'number' || now - cache.checkedAt >= UPDATE_TTL_MS;
+}
+
+/**
+ * Kick off a background registry check if the cache has gone stale. Touches
+ * `checkedAt` first so concurrent callers (and a child that dies) don't spawn a
+ * fetch per invocation. Never waits, never throws.
+ *
+ * Only called from long-lived or already-slow contexts (a CLI command, MCP
+ * boot) — never from a hook, which reads the cache and nothing else.
+ */
+export function maybeRefreshInBackground(home?: string, now = Date.now()): boolean {
+ const cache = readUpdateCache(home);
+ if (!needsRefresh(cache, now)) return false;
+ writeUpdateCache({ latest: cache?.latest ?? null, checkedAt: now }, home);
+ try {
+ const child = spawn(process.execPath, [graftCliPath(), '_update-check'], {
+ detached: true,
+ stdio: 'ignore',
+ });
+ child.unref();
+ return true;
+ } catch {
+ return false; // no spawn (sandbox, ENOMEM) — the nudge just uses the old cache
+ }
+}
+
+/** One line, or nothing. Nothing is the common case — don't spend context on
+ * "you're up to date". */
+export function formatUpdateNudge(current: string, latest: string | null | undefined): string | null {
+ if (!isNewer(latest, current)) return null;
+ return `⬆ graft ${current} → ${latest} available: run \`npm i -g @nanonets/graft@latest\` (restart your agent after).`;
+}
+
+/* -------------------------------------------------------------------------- */
+/* the wiring stamp */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * The subset of `graft init`'s flags a refresh has to replay.
+ *
+ * Without these, an auto-refresh would install things the user explicitly
+ * declined: someone who ran `graft init --no-global` (or `--no-hooks`) said "keep
+ * out of `~/.codex`", and a later session silently writing there would be graft
+ * overriding a decision rather than maintaining one. Absent from an older stamp →
+ * all true, which is what plain `graft init` does.
+ */
+export interface WiringOpts {
+ /** false → never write outside the repo (`--no-global`). */
+ global: boolean;
+ /** false → skip MCP server registration (`--no-mcp`). */
+ mcp: boolean;
+ /** false → skip hook installation (`--no-hooks`). */
+ hooks: boolean;
+}
+
+export const DEFAULT_WIRING_OPTS: WiringOpts = { global: true, mcp: true, hooks: true };
+
+/** An older stamp has no `opts`; a plain `graft init` wired everything. */
+export function wiringOpts(stamp: WiringStamp | null): WiringOpts {
+ return { ...DEFAULT_WIRING_OPTS, ...(stamp?.opts ?? {}) };
+}
+
+export interface WiringStamp {
+ /** The graft version whose `init` wrote this repo's agent files. */
+ version: string;
+ /** Host ids that were wired, so a refresh re-writes exactly those and never
+ * silently adopts an agent the user declined in the picker. */
+ hosts: string[];
+ /** The init flags to replay — see {@link WiringOpts}. */
+ opts?: Partial<WiringOpts>;
+ at: string;
+}
+
+/** Under `graft/.cache/`, beside the other derived state: git-ignored, per-clone,
+ * and cheap to lose — a missing stamp just means one idempotent refresh. */
+export function stampPath(repo: string): string {
+ return join(cacheDir(repo), 'wiring-stamp.json');
+}
+
+export function readStamp(repo: string): WiringStamp | null {
+ return readJson<WiringStamp>(stampPath(repo));
+}
+
+export function writeStamp(
+ repo: string,
+ version: string,
+ hosts: string[],
+ opts: Partial<WiringOpts> = {},
+ at = new Date().toISOString(),
+): void {
+ try {
+ writeJsonAtomic(stampPath(repo), {
+ version,
+ hosts: [...hosts].sort(),
+ opts: { ...DEFAULT_WIRING_OPTS, ...opts },
+ at,
+ } satisfies WiringStamp);
+ } catch { /* unwritable graft/ — a refresh will just be retried next session */ }
+}
+
+/**
+ * Which agents this repo is *already* wired for, read off disk rather than
+ * re-detected. Detection answers "which editors does this machine have"; for a
+ * refresh we need "which files did a previous init actually write" — otherwise
+ * installing Windsurf once would silently add graft rules to every repo.
+ */
+export function wiredHostIds(repo: string): string[] {
+ const ids: string[] = [];
+ if (existsSync(join(repo, '.claude', 'helpers', 'graft-hooks.cjs'))) ids.push('claude');
+ for (const host of HOSTS) {
+ const path = join(repo, host.relPath);
+ if (!existsSync(path)) continue;
+ // A shared file (AGENTS.md, GEMINI.md) counts only if graft's fenced section
+ // is in it — the user may own the file for entirely unrelated reasons.
+ if (host.kind === 'section') {
+ try { if (!readFileSync(path, 'utf8').includes(START)) continue; } catch { continue; }
+ }
+ ids.push(host.id);
+ }
+ return ids;
+}
+
+export interface WiringRefresh {
+ from: string;
+ to: string;
+ hosts: string[];
+ /** True when the refresh included writes outside the repo (`~/.codex/`), so the
+ * caller can say so — a session changing machine-wide config should be visible. */
+ global: boolean;
+}
+
+/**
+ * Re-run init's writes when the stamp and the running binary disagree.
+ *
+ * Deliberately narrow: it refreshes the hosts already wired, replays the flags
+ * that init was given, never builds the graph (this runs at session start — a
+ * rebuild there would stall the agent's first turn), and no-ops when the repo has
+ * no graft wiring at all.
+ */
+export function reconcileWiring(
+ repo: string,
+ current: string,
+ deps: {
+ wired?: (repo: string) => string[];
+ rewrite: (repo: string, hosts: string[], opts: WiringOpts) => void;
+ },
+): WiringRefresh | null {
+ try {
+ const stamp = readStamp(repo);
+ if (stamp && stamp.version === current) return null;
+ // The stamp is the record of *intent* (what the picker chose); disk is the
+ // fallback for repos wired before stamps existed. Union, not just disk:
+ // otherwise a host whose rule file went missing — deleted by hand, lost to a
+ // merge, or clobbered by another tool — is silently dropped from every future
+ // refresh, and that file is precisely what a refresh exists to restore.
+ const onDisk = (deps.wired ?? wiredHostIds)(repo);
+ const hosts = [...new Set([...(stamp?.hosts ?? []), ...onDisk])].sort();
+ if (hosts.length === 0) return null; // never wired here — not our business
+ const opts = wiringOpts(stamp);
+ deps.rewrite(repo, hosts, opts);
+ writeStamp(repo, current, hosts, opts);
+ return { from: stamp?.version ?? 'unwired', to: current, hosts, global: opts.global };
+ } catch {
+ return null; // a refresh is an optimization; never fail the caller over it
+ }
+}
+
+export function formatWiringRefresh(r: WiringRefresh | null): string | null {
+ if (!r) return null;
+ // Name the out-of-repo writes explicitly: those are machine-wide and shared by
+ // every repo, so a user seeing this line should not have to guess what moved.
+ const scope = r.global && r.hosts.includes('agents') ? " (including this machine's ~/.codex config)" : '';
+ return `· graft refreshed this repo's agent wiring${scope} (written by ${r.from}, now ${r.to}): ${r.hosts.join(', ')}.`;
+}
diff --git a/test/claude-shim-resolve.test.ts b/test/claude-shim-resolve.test.ts
new file mode 100644
index 00000000..fd8b571d
--- /dev/null
+++ b/test/claude-shim-resolve.test.ts
@@ -0,0 +1,83 @@
+/**
+ * The shim's resolution behaviour, exercised by actually running it.
+ *
+ * This is the regression test for the "installed graft once, still on the old
+ * version" report: the shim used to take the FIRST candidate that existed, and
+ * the first candidate is the absolute path baked in at `graft init` time. So
+ * `npm i -g @nanonets/graft@latest` upgraded a directory the shim never looked
+ * at, and the user's hooks kept loading whatever version wired the repo. The
+ * shim now takes the highest-versioned candidate instead.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { hooksShim } from '../src/claude/shim-template.js';
+import { tmpRepo } from './helpers.js';
+
+/** A fake installed @nanonets/graft whose hooks entry records that it ran. */
+function fakeInstall(root: string, name: string, version: string): string {
+ const pkg = join(root, name);
+ const distClaude = join(pkg, 'dist', 'claude');
+ mkdirSync(distClaude, { recursive: true });
+ writeFileSync(join(pkg, 'package.json'), JSON.stringify({ name: '@nanonets/graft', version }));
+ // CJS on purpose: no "type" field, so `import()` hands back module.exports and
+ // `m.main(...)` resolves — same shape the real dist has for the shim's call.
+ writeFileSync(
+ join(distClaude, 'hooks.js'),
+ `module.exports.main = () => require('node:fs').writeFileSync(process.env.MARKER, ${JSON.stringify(version)});\n`,
+ );
+ return distClaude;
+}
+
+/** Runs the shim with the given baked dir and project dir; returns the version
+ * of the install that actually got loaded (or null if none did). */
+function runShim(root: string, bakedDir: string, projectDir: string): string | null {
+ const shimPath = join(root, 'graft-hooks.cjs');
+ const marker = join(root, 'loaded.txt');
+ writeFileSync(shimPath, hooksShim(bakedDir));
+ const res = spawnSync(process.execPath, [shimPath, 'session-start'], {
+ encoding: 'utf8',
+ env: { ...process.env, MARKER: marker, CLAUDE_PROJECT_DIR: projectDir },
+ });
+ assert.equal(res.status, 0, `shim exited ${res.status}: ${res.stderr}`);
+ return existsSync(marker) ? readFileSync(marker, 'utf8') : null;
+}
+
+test('an upgraded global install wins over the stale baked path', () => {
+ const root = tmpRepo('shim-upgrade');
+ const stale = fakeInstall(root, 'old-node-install', '0.9.1');
+ fakeInstall(join(root, 'project', 'node_modules', '@nanonets'), 'graft', '0.11.0');
+ // BAKED points at the install that `graft init` ran from — still on disk (an
+ // nvm switch leaves it there), still first in the candidate list, now stale.
+ assert.equal(runShim(root, stale, join(root, 'project')), '0.11.0');
+});
+
+test('the baked path still wins when it is the newest', () => {
+ const root = tmpRepo('shim-baked-newest');
+ const baked = fakeInstall(root, 'current', '0.11.0');
+ fakeInstall(join(root, 'project', 'node_modules', '@nanonets'), 'graft', '0.9.1');
+ assert.equal(runShim(root, baked, join(root, 'project')), '0.11.0');
+});
+
+test('a single candidate is used whatever its version', () => {
+ const root = tmpRepo('shim-single');
+ const only = fakeInstall(root, 'only', '0.9.1');
+ mkdirSync(join(root, 'project'), { recursive: true });
+ assert.equal(runShim(root, only, join(root, 'project')), '0.9.1');
+});
+
+test('an install with an unreadable version loses to a known one', () => {
+ const root = tmpRepo('shim-noversion');
+ const broken = fakeInstall(root, 'broken', '0.0.0');
+ writeFileSync(join(root, 'broken', 'package.json'), 'not json');
+ fakeInstall(join(root, 'project', 'node_modules', '@nanonets'), 'graft', '0.9.1');
+ assert.equal(runShim(root, broken, join(root, 'project')), '0.9.1');
+});
+
+test('no candidate at all exits quietly — a hook must never fail the session', () => {
+ const root = tmpRepo('shim-none');
+ mkdirSync(join(root, 'project'), { recursive: true });
+ assert.equal(runShim(root, join(root, 'nowhere'), join(root, 'project')), null);
+});
diff --git a/test/claude-shim-template.test.ts b/test/claude-shim-template.test.ts
index 0252941c..08157c3c 100644
--- a/test/claude-shim-template.test.ts
+++ b/test/claude-shim-template.test.ts
@@ -6,7 +6,7 @@ import { statuslineShim, hooksShim } from '../src/claude/shim-template.js';
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`, () => {
+ test(`${name} shim parses and knows all four candidates (baked, node_modules, lib, npm root -g)`, () => {
const body = src.replace(/^#!.*\n/, ''); // strip shebang for vm
assert.doesNotThrow(() => new vm.Script(body), 'valid JS');
@@ -21,6 +21,12 @@ for (const [name, src] of [['statusline', statuslineShim(BAKED)], ['hooks', hook
assert.match(src, /execFileSync\('npm', \['root', '-g'\]/);
assert.doesNotMatch(src, /tmpdir/); // no predictable temp cache path
+ // Highest version wins among the candidates, not first-hit — otherwise the
+ // baked path pins the user to whatever graft wired the repo, forever.
+ // Behaviour is exercised for real in claude-shim-resolve.test.ts.
+ assert.match(src, /function best\(dirs, name\)/);
+ assert.match(src, /'package\.json'/); // versionOf reads each candidate's version
+
// Windows-safe dynamic import + best-effort catch
assert.match(src, /pathToFileURL\(entry\(/);
assert.match(src, /\.catch\(\(\) => \{/);
diff --git a/test/upkeep-hooks.test.ts b/test/upkeep-hooks.test.ts
new file mode 100644
index 00000000..00601cad
--- /dev/null
+++ b/test/upkeep-hooks.test.ts
@@ -0,0 +1,121 @@
+/**
+ * The session-start hook's self-maintenance pass, end to end: it must refresh
+ * wiring an older graft wrote, surface a cached upgrade nudge, and — critically —
+ * never touch the network, because it runs inside Claude Code's hook timeout.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { main } from '../src/claude/hooks.js';
+import { readStamp, runningVersion, updateCachePath } from '../src/upkeep.js';
+import { tmpRepo } from './helpers.js';
+
+/** A repo that looks like a previous `graft init` ran here, with no stamp — i.e.
+ * wired by a graft old enough not to have written one. */
+function wiredRepo(tag: string): string {
+ const repo = tmpRepo(tag);
+ mkdirSync(join(repo, '.claude', 'helpers'), { recursive: true });
+ writeFileSync(join(repo, '.claude', 'helpers', 'graft-hooks.cjs'), '// wired by an old graft\n');
+ return repo;
+}
+
+/** A fake home carrying a pre-populated update cache, so nothing has to fetch. */
+function homeWithCache(tag: string, latest: string | null, ageMs = 0): string {
+ const home = tmpRepo(tag);
+ writeFileSync(
+ (mkdirSync(join(home, '.graft'), { recursive: true }), updateCachePath(home)),
+ JSON.stringify({ latest, checkedAt: Date.now() - ageMs }),
+ );
+ return home;
+}
+
+/** Runs the hook in-process with stdin/home/project-dir stubbed, returns stdout. */
+async function runHook(event: string, repo: string, home: string): Promise<string> {
+ const saved = {
+ write: process.stdout.write,
+ stdin: process.env.GRAFT_TEST_STDIN,
+ home: process.env.HOME,
+ profile: process.env.USERPROFILE,
+ dir: process.env.CLAUDE_PROJECT_DIR,
+ };
+ let out = '';
+ process.stdout.write = ((chunk: string) => { out += chunk; return true; }) as typeof process.stdout.write;
+ process.env.GRAFT_TEST_STDIN = JSON.stringify({ cwd: repo, session_id: 'test' });
+ process.env.HOME = home;
+ process.env.USERPROFILE = home;
+ process.env.CLAUDE_PROJECT_DIR = repo;
+ try {
+ await main(event);
+ } finally {
+ process.stdout.write = saved.write;
+ if (saved.stdin === undefined) delete process.env.GRAFT_TEST_STDIN; else process.env.GRAFT_TEST_STDIN = saved.stdin;
+ if (saved.home === undefined) delete process.env.HOME; else process.env.HOME = saved.home;
+ if (saved.profile === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = saved.profile;
+ if (saved.dir === undefined) delete process.env.CLAUDE_PROJECT_DIR; else process.env.CLAUDE_PROJECT_DIR = saved.dir;
+ }
+ return out;
+}
+
+function contextOf(stdout: string): string {
+ if (!stdout) return '';
+ return JSON.parse(stdout).hookSpecificOutput.additionalContext as string;
+}
+
+test('session-start refreshes stale wiring and stamps it', async () => {
+ const repo = wiredRepo('hook-refresh');
+ const ctx = contextOf(await runHook('session-start', repo, homeWithCache('hook-refresh-home', null)));
+
+ assert.match(ctx, /refreshed this repo's agent wiring/);
+ assert.match(ctx, /written by unwired, now /);
+ // The wiring was actually re-written, not just announced.
+ assert.ok(existsSync(join(repo, '.claude', 'settings.json')));
+ assert.ok(existsSync(join(repo, '.claude', 'skills', 'graft', 'SKILL.md')));
+ assert.equal(readStamp(repo)?.version, runningVersion());
+ assert.deepEqual(readStamp(repo)?.hosts, ['claude']);
+});
+
+test('session-start says nothing on a second run — the stamp now matches', async () => {
+ const repo = wiredRepo('hook-idempotent');
+ const home = homeWithCache('hook-idempotent-home', null);
+ await runHook('session-start', repo, home);
+ const ctx = contextOf(await runHook('session-start', repo, home));
+ assert.doesNotMatch(ctx, /refreshed this repo's agent wiring/);
+});
+
+test('session-start surfaces a cached upgrade nudge', async () => {
+ const repo = wiredRepo('hook-nudge');
+ const ctx = contextOf(await runHook('session-start', repo, homeWithCache('hook-nudge-home', '99.0.0')));
+ assert.match(ctx, /graft .* → 99\.0\.0 available/);
+ assert.match(ctx, /npm i -g @nanonets\/graft@latest/);
+});
+
+test('an up-to-date install gets no nudge', async () => {
+ const repo = wiredRepo('hook-current');
+ const ctx = contextOf(await runHook('session-start', repo, homeWithCache('hook-current-home', runningVersion())));
+ assert.doesNotMatch(ctx, /available: run/);
+});
+
+test('a stale cache is used as-is: the hook never fetches', async () => {
+ // Two days old — the CLI and the MCP server refresh this, never the hook: a
+ // hook that shelled out to `npm view` would spend its whole timeout on it.
+ const repo = wiredRepo('hook-stale-cache');
+ const home = homeWithCache('hook-stale-home', '99.0.0', 2 * 24 * 60 * 60 * 1000);
+ const before = Date.now();
+ const ctx = contextOf(await runHook('session-start', repo, home));
+ assert.match(ctx, /99\.0\.0 available/, 'stale answer still shown rather than refetched');
+ assert.ok(Date.now() - before < 2000, 'no network round trip');
+});
+
+test('an unwired repo is left completely alone', async () => {
+ const repo = tmpRepo('hook-unwired');
+ const out = await runHook('session-start', repo, homeWithCache('hook-unwired-home', null));
+ assert.equal(out, '', 'no INDEX.md, no wiring, nothing to say');
+ assert.equal(existsSync(join(repo, '.claude')), false, 'never wires a repo that was not wired');
+});
+
+test('a nudge still lands in a wired repo with no graph built yet', async () => {
+ const repo = wiredRepo('hook-nograph');
+ const ctx = contextOf(await runHook('session-start', repo, homeWithCache('hook-nograph-home', '99.0.0')));
+ assert.match(ctx, /99\.0\.0 available/, 'the no-INDEX.md path still reports upkeep');
+});
diff --git a/test/upkeep.test.ts b/test/upkeep.test.ts
new file mode 100644
index 00000000..cf2f5d92
--- /dev/null
+++ b/test/upkeep.test.ts
@@ -0,0 +1,228 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ DEFAULT_WIRING_OPTS,
+ UPDATE_TTL_MS,
+ compareVersions,
+ formatUpdateNudge,
+ formatWiringRefresh,
+ isNewer,
+ needsRefresh,
+ readStamp,
+ reconcileWiring,
+ runningVersion,
+ stampPath,
+ updateCachePath,
+ wiredHostIds,
+ wiringOpts,
+ writeStamp,
+ type WiringOpts,
+} from '../src/upkeep.js';
+import { tmpRepo } from './helpers.js';
+
+test('compareVersions orders releases numerically, not lexically', () => {
+ assert.equal(compareVersions('0.9.1', '0.10.0'), -1); // the lexical trap
+ assert.equal(compareVersions('0.10.0', '0.9.1'), 1);
+ assert.equal(compareVersions('1.2.3', '1.2.3'), 0);
+ assert.equal(compareVersions('2.0.0', '1.99.99'), 1);
+ // Release part only: a prerelease of the same release compares equal, so it
+ // never produces a nudge in either direction.
+ assert.equal(compareVersions('1.0.0-beta.2', '1.0.0'), 0);
+ // Missing segments are zeros, and garbage degrades to 0 rather than NaN.
+ assert.equal(compareVersions('1.2', '1.2.0'), 0);
+ assert.equal(compareVersions('x.y.z', '0.0.0'), 0);
+});
+
+test('isNewer only fires on a strictly greater candidate', () => {
+ assert.equal(isNewer('0.10.0', '0.9.1'), true);
+ assert.equal(isNewer('0.9.1', '0.9.1'), false);
+ assert.equal(isNewer('0.9.0', '0.9.1'), false);
+ assert.equal(isNewer(null, '0.9.1'), false); // failed fetch
+ assert.equal(isNewer(undefined, '0.9.1'), false); // no cache yet
+});
+
+test('formatUpdateNudge stays silent unless there is something to say', () => {
+ assert.equal(formatUpdateNudge('0.9.1', '0.9.1'), null);
+ assert.equal(formatUpdateNudge('0.9.1', null), null);
+ const line = formatUpdateNudge('0.9.1', '0.11.0');
+ assert.ok(line);
+ assert.match(line, /0\.9\.1 → 0\.11\.0/);
+ assert.match(line, /npm i -g @nanonets\/graft@latest/);
+ assert.equal(line.split('\n').length, 1, 'one line — this rides in an agent context window');
+});
+
+test('needsRefresh treats a missing or malformed cache as stale', () => {
+ const now = 1_700_000_000_000;
+ assert.equal(needsRefresh(null, now), true);
+ assert.equal(needsRefresh({ latest: '1.0.0', checkedAt: undefined as unknown as number }, now), true);
+ assert.equal(needsRefresh({ latest: '1.0.0', checkedAt: now }, now), false);
+ assert.equal(needsRefresh({ latest: '1.0.0', checkedAt: now - UPDATE_TTL_MS + 1 }, now), false);
+ assert.equal(needsRefresh({ latest: '1.0.0', checkedAt: now - UPDATE_TTL_MS }, now), true);
+});
+
+test('the update cache is machine-global, not per-repo', () => {
+ // One dev with twelve repos should cost the registry one request a day.
+ assert.equal(updateCachePath('/home/dev'), join('/home/dev', '.graft', 'update-check.json'));
+});
+
+test('runningVersion resolves this package, not the caller depth', () => {
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };
+ assert.equal(runningVersion(), pkg.version);
+});
+
+test('the stamp round-trips under graft/.cache/', () => {
+ const repo = tmpRepo('upkeep-stamp');
+ assert.equal(readStamp(repo), null);
+ writeStamp(repo, '1.2.3', ['cursor', 'claude'], {}, '2026-01-01T00:00:00.000Z');
+ assert.equal(stampPath(repo), join(repo, 'graft', '.cache', 'wiring-stamp.json'));
+ assert.deepEqual(readStamp(repo), {
+ version: '1.2.3',
+ hosts: ['claude', 'cursor'], // sorted, so two inits in different picker order match
+ opts: { global: true, mcp: true, hooks: true },
+ at: '2026-01-01T00:00:00.000Z',
+ });
+});
+
+test('wiringOpts defaults an older stamp to what plain `graft init` does', () => {
+ assert.deepEqual(wiringOpts(null), DEFAULT_WIRING_OPTS);
+ // A stamp written before flags were recorded: assume the full wiring.
+ assert.deepEqual(wiringOpts({ version: '1.0.0', hosts: ['claude'], at: 'x' }), DEFAULT_WIRING_OPTS);
+ // A partial record still fills the gaps.
+ assert.deepEqual(
+ wiringOpts({ version: '1.0.0', hosts: ['claude'], at: 'x', opts: { global: false } }),
+ { global: false, mcp: true, hooks: true },
+ );
+});
+
+test('a refresh replays the flags init was given, including --no-global', () => {
+ const repo = tmpRepo('upkeep-replay');
+ writeStamp(repo, '1.0.0', ['agents'], { global: false, hooks: false });
+ let seen: WiringOpts | null = null;
+ const r = reconcileWiring(repo, '2.0.0', {
+ wired: () => ['agents'],
+ rewrite: (_repo, _hosts, opts) => { seen = opts; },
+ });
+ // The user said "keep out of ~/.codex" — a later session must not overrule that.
+ assert.deepEqual(seen, { global: false, mcp: true, hooks: false });
+ assert.equal(r?.global, false);
+ assert.deepEqual(readStamp(repo)?.opts, { global: false, mcp: true, hooks: false }, 'and it stays recorded');
+});
+
+test('by default a refresh DOES reach ~/.codex — nothing else ever would', () => {
+ // No skill, rule file, or MCP instruction tells an agent to run `graft init`,
+ // so skipping the out-of-repo writes means a Codex user never gets them.
+ const repo = tmpRepo('upkeep-global');
+ writeStamp(repo, '1.0.0', ['agents']);
+ let seen: WiringOpts | null = null;
+ const r = reconcileWiring(repo, '2.0.0', {
+ wired: () => ['agents'],
+ rewrite: (_repo, _hosts, opts) => { seen = opts; },
+ });
+ assert.deepEqual(seen, DEFAULT_WIRING_OPTS);
+ assert.equal(r?.global, true);
+});
+
+test('wiredHostIds reads what init actually wrote, not what the machine has', () => {
+ const repo = tmpRepo('upkeep-wired');
+ assert.deepEqual(wiredHostIds(repo), [], 'unwired repo');
+
+ mkdirSync(join(repo, '.claude', 'helpers'), { recursive: true });
+ writeFileSync(join(repo, '.claude', 'helpers', 'graft-hooks.cjs'), '// shim');
+ mkdirSync(join(repo, '.cursor', 'rules'), { recursive: true });
+ writeFileSync(join(repo, '.cursor', 'rules', 'graft.mdc'), 'rule');
+ // A shared file graft does NOT own: present, but no fenced graft section.
+ writeFileSync(join(repo, 'AGENTS.md'), '# my own notes\n');
+
+ const ids = wiredHostIds(repo);
+ assert.ok(ids.includes('claude'));
+ assert.ok(ids.includes('cursor'));
+ assert.ok(!ids.includes('agents'), "a user's own AGENTS.md is not graft wiring");
+
+ writeFileSync(join(repo, 'AGENTS.md'), '# my own notes\n\n<!-- graft:start -->\nx\n<!-- graft:end -->\n');
+ assert.ok(wiredHostIds(repo).includes('agents'), 'the fenced section makes it ours');
+});
+
+test('reconcileWiring rewrites once on a version mismatch, then no-ops', () => {
+ const repo = tmpRepo('upkeep-reconcile');
+ const calls: string[][] = [];
+ const rewrite = (_r: string, hosts: string[]) => { calls.push(hosts); };
+ const wired = () => ['claude', 'cursor'];
+
+ // No stamp (fresh clone, or wired by a pre-stamp graft) → refresh.
+ const first = reconcileWiring(repo, '2.0.0', { wired, rewrite });
+ assert.deepEqual(first, { from: 'unwired', to: '2.0.0', hosts: ['claude', 'cursor'], global: true });
+ assert.deepEqual(calls, [['claude', 'cursor']]);
+
+ // Stamp now matches the running binary → nothing happens on every later session.
+ assert.equal(reconcileWiring(repo, '2.0.0', { wired, rewrite }), null);
+ assert.equal(calls.length, 1, 'idempotent: no rewrite per session');
+
+ // A newer binary → one more refresh, reported with the version it came from.
+ const upgraded = reconcileWiring(repo, '2.1.0', { wired, rewrite });
+ assert.deepEqual(upgraded, { from: '2.0.0', to: '2.1.0', hosts: ['claude', 'cursor'], global: true });
+ assert.equal(calls.length, 2);
+ assert.equal(readStamp(repo)?.version, '2.1.0');
+});
+
+test('reconcileWiring restores a host whose file went missing', () => {
+ // The whole point of a refresh is putting the wiring back. Detecting hosts from
+ // disk alone would drop the one host whose file is gone — the one that needs it.
+ const repo = tmpRepo('upkeep-restore');
+ writeStamp(repo, '1.0.0', ['claude', 'cursor']);
+ const calls: string[][] = [];
+ const r = reconcileWiring(repo, '2.0.0', {
+ wired: () => ['claude'], // cursor's graft.mdc is no longer on disk
+ rewrite: (_repo, hosts) => { calls.push(hosts); },
+ });
+ assert.deepEqual(r?.hosts, ['claude', 'cursor']);
+ assert.deepEqual(calls, [['claude', 'cursor']]);
+ assert.deepEqual(readStamp(repo)?.hosts, ['claude', 'cursor'], 'intent survives the refresh');
+});
+
+test('reconcileWiring adopts a host added since the stamp was written', () => {
+ const repo = tmpRepo('upkeep-adopt');
+ writeStamp(repo, '1.0.0', ['claude']);
+ const r = reconcileWiring(repo, '2.0.0', { wired: () => ['claude', 'windsurf'], rewrite: () => {} });
+ assert.deepEqual(r?.hosts, ['claude', 'windsurf']);
+});
+
+test('reconcileWiring leaves a repo that graft never wired alone', () => {
+ const repo = tmpRepo('upkeep-unwired');
+ let rewrote = false;
+ const r = reconcileWiring(repo, '2.0.0', { wired: () => [], rewrite: () => { rewrote = true; } });
+ assert.equal(r, null);
+ assert.equal(rewrote, false);
+ assert.equal(existsSync(stampPath(repo)), false, 'no stamp written for a repo we do not manage');
+});
+
+test('reconcileWiring never throws out into a hook', () => {
+ const repo = tmpRepo('upkeep-throws');
+ const r = reconcileWiring(repo, '2.0.0', {
+ wired: () => ['claude'],
+ rewrite: () => { throw new Error('disk full'); },
+ });
+ assert.equal(r, null, 'a failed refresh is silent, not a broken session');
+});
+
+test('formatWiringRefresh names the versions and the hosts touched', () => {
+ assert.equal(formatWiringRefresh(null), null);
+ const line = formatWiringRefresh({ from: '0.7.0', to: '0.11.0', hosts: ['claude', 'cursor'], global: true });
+ assert.ok(line);
+ assert.match(line, /0\.7\.0/);
+ assert.match(line, /0\.11\.0/);
+ assert.match(line, /claude, cursor/);
+ // Repo-local hosts only: nothing outside the repo moved, so don't claim it did.
+ assert.doesNotMatch(line, /~\/\.codex/);
+});
+
+test('formatWiringRefresh discloses machine-wide writes', () => {
+ const global = formatWiringRefresh({ from: '0.7.0', to: '0.11.0', hosts: ['agents'], global: true });
+ assert.ok(global);
+ assert.match(global, /~\/\.codex/, 'a session changing shared config must say so');
+
+ const local = formatWiringRefresh({ from: '0.7.0', to: '0.11.0', hosts: ['agents'], global: false });
+ assert.ok(local);
+ assert.doesNotMatch(local, /~\/\.codex/);
+});