Skip to content

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

Reach the agent: strength-gated hint, MCP instructions, greppable cards

anirudhkumar-nanonets228a49c322b4
diff --git a/src/claude/format.ts b/src/claude/format.ts
index 727d6e78..eec39b6e 100644
--- a/src/claude/format.ts
+++ b/src/claude/format.ts
@@ -1,6 +1,10 @@
import { basename } from 'node:path';
import type { Stats, SessionState } from './state.js';
import type { GraphV1, EdgeV1 } from '../graph/types.js';
+// The injection gate reuses the federation floors rather than inventing its own:
+// "did we hit a real name, or match broadly enough to trust anyway" is the same
+// question in both places, and one set of calibrated numbers beats two.
+import { HIGH_FLOOR, STRONG_FLOOR } from '../ask/fuse.js';
const C = {
indigo: (s: string) => `\x1b[38;2;84;111;255m${s}\x1b[0m`,
@@ -73,6 +77,10 @@ export interface AskJson {
saved?: { files: number; baselineChars: number };
/** Lexical mode: share (0..1) of the query's distinct terms the top hit matched. */
coverage?: number;
+ /** Lexical mode: the same share over the top hit's NAME field only — "did the
+ * query hit a real symbol, or only words buried in some body?". `ask --json`
+ * has always emitted it; the gate below is what finally reads it. */
+ coverageStrong?: number;
}
function tokensOf(chars: number): number { return Math.round(chars / 4); }
@@ -123,27 +131,65 @@ export function formatRetrieval(ask: AskJson, cap = 5): string | null {
);
}
-/** Coverage below this → skip the pack. A floor, not a classifier: lexical
- * coverage can't reliably rank mid-range prompts, so the floor sits where it
- * only rejects flagrantly off-repo prompts (chatter, greetings, unrelated
- * asks — these probe well under 0.1) and never a genuinely on-repo task. The
- * cost asymmetry justifies leaning low: a wrongly-skipped pack is recoverable
- * (the agent pulls with `graft ask`), a wrongly-injected one is pure noise. */
+/**
+ * Superseded by the two-clause strength gate in {@link relevantRetrieval} (see
+ * {@link STRONG_FLOOR} / {@link HIGH_FLOOR}). Kept exported because the old
+ * single-clause floor is still the documented reference point for why it changed:
+ * it sat at 0.15, and a prompt measuring 0.165 / strong 0.033 cleared it by 0.015
+ * and injected three test files for a question whose answer was elsewhere. The
+ * comment it used to carry justified leaning low — "a wrongly-skipped pack is
+ * recoverable, the agent pulls with `graft ask`" — and that assumption is exactly
+ * what a traced session falsified: the agent did not pull. It grepped 38 times.
+ */
export const INJECT_MIN_COVERAGE = 0.15;
/** How many recently-injected pointers the novelty gate remembers per session. */
const INJECTED_POINTERS_CAP = 40;
-/** The per-prompt injection gate. Returns the pack text to inject, or null to
- * stay silent. Mutates `s` to remember what was shown (caller persists it).
- * Gates, in order:
- * 1. relevance — lexical coverage below {@link INJECT_MIN_COVERAGE} → skip
- * (structural results carry no coverage; the intent match is the signal);
- * 2. novelty — hits whose pointer was already injected this session are
- * dropped, and if none remain the whole pack is skipped. */
+/** How many weak-match nudges one session may spend. A line that shows up every
+ * turn stops being read; two is enough to land the habit without becoming
+ * wallpaper. */
+export const NUDGE_CAP = 2;
+
+/** The line injected instead of a weak pack: names the command, says why, once.
+ * Deliberately not an imperative about graft in general — it's a fact about this
+ * prompt's match quality plus the command that fixes it. */
+export function weakMatchNudge(s: SessionState, strong: number): string | null {
+ const spent = s.nudges ?? 0;
+ if (spent >= NUDGE_CAP) return null;
+ s.nudges = spent + 1;
+ return (
+ `[graft] no strong match for this prompt (name-field match ${strong.toFixed(2)}) — the graph ` +
+ `has more than this probe found. Run \`graft ask "<your task>" --source\` before grepping.`
+ );
+}
+
+/**
+ * The per-prompt injection gate. Returns the text to inject, or null to stay
+ * silent. Mutates `s` to remember what was shown (caller persists it).
+ *
+ * Gate 1 — **strength**. A pack earns its place only if the top hit either landed
+ * on a real symbol NAME (`coverageStrong ≥ STRONG_FLOOR`) or matched the query
+ * broadly enough to trust regardless (`coverage ≥ HIGH_FLOOR`). This is the same
+ * two-clause rule `fuse.ts` already uses to decide whether a whole sub-repo joins
+ * a cross-repo ranking — a cheaper decision than this one, previously held to a
+ * stricter standard. Failing it emits {@link weakMatchNudge} rather than nothing:
+ * silence leaves the agent with no signal at all, and a borderline pack is worse
+ * than either, because it reads as orientation and suppresses the very retrieval
+ * call it should have triggered. Structural results carry neither score — the
+ * resolved intent is itself the relevance signal — so they always pass.
+ *
+ * Gate 2 — **novelty**. Hits whose pointer was already injected this session are
+ * dropped; if none remain, the pack is skipped.
+ */
export function relevantRetrieval(ask: AskJson, s: SessionState, cap = 3): string | null {
if (!(ask.hits ?? []).length) return null;
- if (typeof ask.coverage === 'number' && ask.coverage < INJECT_MIN_COVERAGE) return null;
+ const lexical = typeof ask.coverage === 'number' || typeof ask.coverageStrong === 'number';
+ if (lexical) {
+ const strong = ask.coverageStrong ?? 0;
+ const broad = ask.coverage ?? 0;
+ if (strong < STRONG_FLOOR && broad < HIGH_FLOOR) return weakMatchNudge(s, strong);
+ }
const seen = new Set(s.injectedPointers ?? []);
const fresh = ask.hits.filter((h) => !seen.has(h.pointer));
if (!fresh.length) return null;
diff --git a/src/claude/state.ts b/src/claude/state.ts
index d89fbea4..dbc18c5b 100644
--- a/src/claude/state.ts
+++ b/src/claude/state.ts
@@ -32,10 +32,13 @@ export interface SessionState {
* a hit whose pointer was shown once is never re-injected). Optional so
* session files written before this field still parse. */
injectedPointers?: string[];
+ /** Weak-match nudges spent this session, capped so the line stays signal.
+ * Optional for the same backwards-compatibility reason as above. */
+ nudges?: number;
}
function emptySession(): SessionState {
- return { lastQuery: null, perAgentQuery: {}, graftReads: 0, sourceReads: 0, savedTokens: 0, injectedPointers: [] };
+ return { lastQuery: null, perAgentQuery: {}, graftReads: 0, sourceReads: 0, savedTokens: 0, injectedPointers: [], nudges: 0 };
}
function sessionPath(d: string, id: string): string { return join(cacheDir(d), 'session', `${id}.json`); }
diff --git a/src/cli.ts b/src/cli.ts
index 73677571..733c9d52 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -339,7 +339,7 @@ program
const { resolve } = await import("node:path");
const { startMcpServer } = await import("./mcp/server.js");
const globalOpts = program.opts<{ dir?: string }>();
- startMcpServer(resolve(dir), globalOpts.dir);
+ startMcpServer(resolve(dir), globalOpts.dir, currentVersion);
});
program
diff --git a/src/context/node-file.ts b/src/context/node-file.ts
index 5df841c5..a84ba837 100644
--- a/src/context/node-file.ts
+++ b/src/context/node-file.ts
@@ -25,6 +25,8 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, rmSync
import { join, relative, sep } from "node:path";
import matter from "gray-matter";
import { contentHash, normalizeName } from "../util/id.js";
+// Value-only import of a constant; `write.ts` pulls in nothing from here, so no cycle.
+import { GRAPH_DIR } from "../graph/write.js";
/** A source file a node was derived from, with its content hash at generation time. */
export interface SourceRef {
@@ -128,6 +130,45 @@ export function ensureGitignored(root: string, contextDir: string): void {
try { writeFileSync(path, current + block); } catch { /* best-effort — build already succeeded */ }
}
+/**
+ * Keep the card tree greppable even though it's gitignored, by writing a root
+ * `.ignore` that re-admits it.
+ *
+ * The cards exist so that a `grep <symbol>` lands on a ~150-token card instead of
+ * a whole source file. Making the graph a local cache (and so gitignored) silently
+ * broke that: **ripgrep honours `.gitignore`**, and every ripgrep-backed search
+ * tool inherits the blind spot — verified by a card that names a symbol which
+ * default `rg` will not return and `rg -uu` finds instantly. `.ignore` is read at
+ * higher precedence than `.gitignore`, so re-admitting the tree there restores
+ * search without git ever tracking a byte of it.
+ *
+ * The two negative entries matter as much as the positive one: `.cache/` holds a
+ * multi-MB parse memo and `.graph/` holds `wiring.json`, and dropping either into
+ * every repo-wide search would be worse than the problem being fixed.
+ *
+ * Same contract as {@link ensureGitignored}: idempotent, skips a context dir
+ * outside `root`, and swallows write failures — a build that already succeeded
+ * must not fail over a convenience file.
+ */
+export function ensureSearchable(root: string, contextDir: string): void {
+ const rel = relative(root, contextDir).split(sep).join("/");
+ if (rel === "" || rel.startsWith("..")) return; // outside the repo — nothing to re-admit
+ const dir = rel.replace(/\/+$/, "");
+ const entry = `!${dir}/`;
+ const path = join(root, ".ignore");
+ let current = "";
+ try { current = readFileSync(path, "utf8"); } catch { /* no .ignore yet — we create one */ }
+ // Any mention of the negation means a human (or a previous build) has already
+ // had an opinion here; leave it alone rather than append a second copy.
+ if (current.split("\n").some((l) => l.trim() === entry)) return;
+ const gap = current === "" ? "" : current.endsWith("\n") ? "\n" : "\n\n";
+ const block =
+ `${gap}# graft's cards are gitignored but should stay greppable: ripgrep reads\n` +
+ `# .ignore before .gitignore, so this re-admits the tree to search only.\n` +
+ `${entry}\n${dir}/${CACHE_DIR}/\n${dir}/${GRAPH_DIR}/\n`;
+ try { writeFileSync(path, current + block); } catch { /* best-effort */ }
+}
+
/** Render the generated body (Summary + Related) for a node. */
function renderGenerated(node: ContextNode): string {
const lines = [`## Summary`, ``, node.summary.trim() || "_(no summary)_", ``];
diff --git a/src/graph/build.ts b/src/graph/build.ts
index 1f125e90..af9bc6e6 100644
--- a/src/graph/build.ts
+++ b/src/graph/build.ts
@@ -16,7 +16,7 @@
import { readFileSync } from "node:fs";
import { basename, dirname, relative, resolve, sep } from "node:path";
import { walkDir } from "../ingest/fs.js";
-import { contextDirFor, ensureGitignored } from "../context/node-file.js";
+import { contextDirFor, ensureGitignored, ensureSearchable } from "../context/node-file.js";
import { extractFile, languageOf, type Language, type RawEdge } from "./extract.js";
import { contentHash } from "../util/id.js";
import {
@@ -285,6 +285,10 @@ export async function buildGraph(
// The graph is a local, regenerable cache — make sure git ignores it. Cheap and
// idempotent, so a fresh clone's first build self-ignores.
ensureGitignored(root, outDir);
+ // …and that gitignoring it doesn't hide the cards from search: ripgrep honours
+ // .gitignore, so without this the cards can never be grepped, which is the one
+ // way an agent was supposed to stumble onto them.
+ ensureSearchable(root, outDir);
cardStats = writeCards(graph, outDir);
writeIndex(outDir, cardStats.files);
// Backfill concept nodes with their `covers:` symbol/file:line list (the
diff --git a/src/graph/cards.ts b/src/graph/cards.ts
index c58e78b6..30094704 100644
--- a/src/graph/cards.ts
+++ b/src/graph/cards.ts
@@ -194,6 +194,14 @@ export function writeIndex(outDir: string, files: CardFileInfo[]): void {
'filename here, or run `graft ask "<task>"`. Each node carries prose plus exact',
"`file:line`; open a source file only to edit the named span.",
"",
+ // Whoever reads this file has already decided to look at graft, so this is the
+ // one place a pointer to the richer surface is welcome rather than noise. Stated
+ // as what exists, not as an instruction — see `mcp/instructions.ts` for why.
+ "The same graph is queryable as MCP tools (`graft_ask`, `graft_grep`,",
+ "`graft_callers`, `graft_skeleton`, `graft_map`) where a host exposes them, and",
+ "as the `graft` CLI everywhere else. Edges — who calls what — live only in the",
+ "graph, not in these files: `graft callers <symbol>` is the only way to read them.",
+ "",
];
const concepts = readNodes(outDir).sort((a, b) => a.slug.localeCompare(b.slug));
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
new file mode 100644
index 00000000..24f434bf
--- /dev/null
+++ b/src/mcp/instructions.ts
@@ -0,0 +1,57 @@
+/**
+ * The `instructions` string returned in graft's MCP `initialize` response.
+ *
+ * This is the one piece of graft prose that survives **tool deferral**. When a
+ * host has more tools than its schema budget allows, it sends tool *names* only
+ * and withholds the JSONSchemas until a `ToolSearch`-style lookup fetches them —
+ * measured in a real session: 111 tools deferred, of which graft's six arrived as
+ * six bare strings with no descriptions at all. The MCP spec's `instructions`
+ * field is delivered on a separate track (Claude Code records it as its own
+ * `mcp_instructions_delta` context layer), so it lands whole even then. Other
+ * servers already rely on this — `claude-in-chrome` uses it for exactly the
+ * batch-your-ToolSearch instruction below; graft used to send nothing.
+ *
+ * Two jobs, in this order:
+ * 1. Defuse the deferral tax. One lookup loads all six tools for the whole
+ * session, so the cost is a single round trip, not two calls per use. An
+ * agent that doesn't know this can only assume the worse reading.
+ * 2. Say what each tool is FOR as a decision rule, not a feature summary —
+ * because in a host with no hooks and no skill listing (a plain chat client
+ * with an MCP config), this string plus the tool descriptions are the entire
+ * steering budget graft gets.
+ *
+ * Budget: keep this under ~1,000 characters. Observed sibling servers sit at
+ * 660–984, and nothing proves a longer one survives un-truncated.
+ */
+
+/** Tool names in the order an agent should reach for them, most-used first. */
+const TOOL_ORDER = [
+ 'graft_ask',
+ 'graft_grep',
+ 'graft_callers',
+ 'graft_skeleton',
+ 'graft_map',
+] as const;
+
+/** The `select:` argument that loads every graft tool in one lookup. */
+export function toolSearchQuery(prefix = 'mcp__graft__'): string {
+ return `select:${TOOL_ORDER.map((t) => `${prefix}${t}`).join(',')}`;
+}
+
+export function mcpInstructions(): string {
+ return [
+ 'This repo is indexed by graft: a prebuilt graph of every symbol, its file:line',
+ 'span, and who calls what. Prefer these tools over grep/read — one call usually',
+ 'replaces several file reads.',
+ '',
+ `**If these tools are deferred (names shown, schemas withheld), load them all in ONE lookup:** ToolSearch "${toolSearchQuery()}" — one round trip for the whole session. Never load them one at a time.`,
+ '',
+ '- graft_ask — "how does X work" / "where is Y": ranked hits, code inlined.',
+ '- graft_grep — when you need EVERY occurrence; ask is top-N and misses some.',
+ '- graft_callers — who calls it, what it calls, blast radius before a rename.',
+ '- graft_skeleton — a file\'s whole API in ~200 tokens.',
+ '- graft_map — orientation in an unfamiliar repo.',
+ '',
+ 'Results already reflect uncommitted edits — the graph refreshes before each query.',
+ ].join('\n');
+}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index df7f3845..9e4d1649 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -4,6 +4,7 @@
*/
import { createInterface } from 'node:readline';
import { TOOLS, callTool } from './tools.js';
+import { mcpInstructions } from './instructions.js';
function send(msg: object): void {
process.stdout.write(`${JSON.stringify(msg)}\n`);
@@ -17,7 +18,12 @@ function replyError(id: unknown, code: number, message: string): void {
send({ jsonrpc: '2.0', id, error: { code, message } });
}
-export function startMcpServer(root: string, dirOverride?: string): void {
+/**
+ * `version` is threaded in from the CLI rather than read here: `readCurrentVersion`
+ * resolves package.json relative to the calling module, and from `dist/mcp/` that
+ * lookup misses. The caller already knows it.
+ */
+export function startMcpServer(root: string, dirOverride?: string, version = '0'): void {
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
rl.on('line', (line) => {
const text = line.trim();
@@ -36,7 +42,9 @@ export function startMcpServer(root: string, dirOverride?: string): void {
reply(id, {
protocolVersion: params?.protocolVersion ?? '2024-11-05',
capabilities: { tools: {} },
- serverInfo: { name: 'graft', version: '0' },
+ serverInfo: { name: 'graft', version },
+ // The one channel that survives tool deferral — see ./instructions.ts.
+ instructions: mcpInstructions(),
});
return;
case 'notifications/initialized':
diff --git a/test/claude-format.test.ts b/test/claude-format.test.ts
index 6282e9db..e98bd24b 100644
--- a/test/claude-format.test.ts
+++ b/test/claude-format.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { renderStatusline, incomingEdges, formatBlastRadius, formatRetrieval, formatOrientation, renderSubagent, relevantRetrieval, INJECT_MIN_COVERAGE } from '../src/claude/format.js';
+import { renderStatusline, incomingEdges, formatBlastRadius, formatRetrieval, formatOrientation, renderSubagent, relevantRetrieval, INJECT_MIN_COVERAGE, NUDGE_CAP } from '../src/claude/format.js';
import { emptyStats } from '../src/claude/state.js';
const strip = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, '');
@@ -102,10 +102,44 @@ test('relevantRetrieval injects on good coverage and records pointers', () => {
assert.deepEqual(s.injectedPointers, ['src/pkce.ts:L1-L4', 'src/pkce.ts:L6-L9']);
});
-test('relevantRetrieval skips when coverage is below the floor', () => {
+test('relevantRetrieval nudges instead of injecting when the match is weak both ways', () => {
const s = freshSession();
- assert.equal(relevantRetrieval(gateAsk({ coverage: INJECT_MIN_COVERAGE - 0.01 }), s), null);
- assert.deepEqual(s.injectedPointers, [], 'nothing recorded on skip');
+ const txt = relevantRetrieval(gateAsk({ coverage: 0.2, coverageStrong: 0.05 }), s);
+ assert.match(txt ?? '', /no strong match/, 'a weak pack is replaced by a named command');
+ assert.match(txt ?? '', /graft ask/, 'the nudge names the command to run');
+ assert.deepEqual(s.injectedPointers, [], 'nothing recorded — no pack was shown');
+});
+
+test('relevantRetrieval passes on a NAME hit even when broad coverage is low', () => {
+ // The whole point of the second clause: a short prompt naming one real symbol
+ // has low broad coverage and high strength, and must not be gated out.
+ const txt = relevantRetrieval(gateAsk({ coverage: 0.2, coverageStrong: 0.45 }), freshSession());
+ assert.ok(txt && /verify/.test(strip(txt)), 'strong name match injects');
+});
+
+test('relevantRetrieval: the traced turn-1 regression is now rejected', () => {
+ // Measured from session ce3ca5f4: this exact pair cleared the old 0.15 floor by
+ // 0.015 and injected three test files for a question answered elsewhere.
+ const s = freshSession();
+ const txt = relevantRetrieval(gateAsk({ coverage: 0.1649, coverageStrong: 0.0329 }), s);
+ assert.match(txt ?? '', /no strong match/);
+ assert.match(txt ?? '', /0\.03/, 'the nudge reports the strength it measured');
+ assert.deepEqual(s.injectedPointers, []);
+});
+
+test('relevantRetrieval caps the nudge so it cannot become wallpaper', () => {
+ const s = freshSession();
+ const weak = () => gateAsk({ coverage: 0.1, coverageStrong: 0 });
+ assert.ok(relevantRetrieval(weak(), s), 'first weak prompt nudges');
+ assert.ok(relevantRetrieval(weak(), s), 'second still nudges');
+ assert.equal(relevantRetrieval(weak(), s), null, 'third is silent');
+ assert.equal(s.nudges, NUDGE_CAP);
+});
+
+test('INJECT_MIN_COVERAGE is retained as the superseded reference floor', () => {
+ // Documented history, not live logic: 0.1649 used to clear this and no longer does.
+ assert.equal(INJECT_MIN_COVERAGE, 0.15);
+ assert.ok(0.1649 > INJECT_MIN_COVERAGE, 'the regression case cleared the old floor');
});
test('relevantRetrieval treats missing coverage (structural mode) as relevant', () => {
diff --git a/test/claude-state.test.ts b/test/claude-state.test.ts
index 4d052edd..5f1aa630 100644
--- a/test/claude-state.test.ts
+++ b/test/claude-state.test.ts
@@ -24,7 +24,7 @@ test('stats round-trip and patch merge', () => {
test('session defaults and round-trip', () => {
const d = fresh();
const s = readSession(d, 'abc');
- assert.deepEqual(s, { lastQuery: null, perAgentQuery: {}, graftReads: 0, sourceReads: 0, savedTokens: 0, injectedPointers: [] });
+ assert.deepEqual(s, { lastQuery: null, perAgentQuery: {}, graftReads: 0, sourceReads: 0, savedTokens: 0, injectedPointers: [], nudges: 0 });
s.lastQuery = 'pkce'; s.graftReads = 2;
writeSession(d, 'abc', s);
assert.equal(readSession(d, 'abc').lastQuery, 'pkce');
diff --git a/test/context.test.ts b/test/context.test.ts
index 24ca5a33..85f3a943 100644
--- a/test/context.test.ts
+++ b/test/context.test.ts
@@ -10,7 +10,7 @@ import { tmpdir } from "node:os";
import { execFileSync } from "node:child_process";
import { buildContext } from "../src/context/build.js";
import { checkContext, indexFreshness, staleBanner } from "../src/context/check.js";
-import { contextDirFor, ensureGitignored } from "../src/context/node-file.js";
+import { contextDirFor, ensureGitignored, ensureSearchable } from "../src/context/node-file.js";
import { fakeProviders } from "./helpers.js";
// CLI-spawn helper (same pattern as test/graph-traverse-cli.test.ts) — these tests
@@ -303,3 +303,58 @@ test("ensureGitignored: no-op when the graph dir is outside the repo root", () =
rmSync(dir, { recursive: true, force: true });
}
});
+
+// ensureSearchable — gitignoring the graph must not also hide it from `grep`.
+// ripgrep honours .gitignore, so without this the cards are unreachable by the
+// one mechanism they were designed around.
+test("ensureSearchable: re-admits the card tree while excluding the caches", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ctxsearch-"));
+ try {
+ ensureSearchable(dir, contextDirFor(dir));
+ const ig = readFileSync(join(dir, ".ignore"), "utf8");
+ assert.match(ig, /^!graft\/$/m, "the tree is re-admitted to search");
+ assert.match(ig, /^graft\/\.cache\/$/m, "but not the multi-MB parse memo");
+ assert.match(ig, /^graft\/\.graph\/$/m, "and not wiring.json");
+ assert.match(ig, /ripgrep reads/, "carries the why, for whoever finds this file");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("ensureSearchable: appends to an existing .ignore, and is idempotent", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ctxsearch-"));
+ try {
+ writeFileSync(join(dir, ".ignore"), "vendor/\n");
+ ensureSearchable(dir, contextDirFor(dir));
+ const once = readFileSync(join(dir, ".ignore"), "utf8");
+ assert.match(once, /vendor\//, "existing entries survive");
+ ensureSearchable(dir, contextDirFor(dir));
+ const twice = readFileSync(join(dir, ".ignore"), "utf8");
+ assert.equal(once, twice);
+ assert.equal((twice.match(/^!graft\/$/gm) ?? []).length, 1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("ensureSearchable: leaves a hand-written negation alone", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ctxsearch-"));
+ try {
+ // Someone already had an opinion here — don't append a competing block.
+ writeFileSync(join(dir, ".ignore"), "# mine\n!graft/\n");
+ ensureSearchable(dir, contextDirFor(dir));
+ assert.equal(readFileSync(join(dir, ".ignore"), "utf8"), "# mine\n!graft/\n");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("ensureSearchable: no-op when the graph dir is outside the repo root", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ctxsearch-"));
+ try {
+ ensureSearchable(dir, join(tmpdir(), "somewhere-else-graft"));
+ assert.equal(existsSync(join(dir, ".ignore")), false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/test/mcp-server.test.ts b/test/mcp-server.test.ts
index ef37a931..956ec04d 100644
--- a/test/mcp-server.test.ts
+++ b/test/mcp-server.test.ts
@@ -58,6 +58,28 @@ test('initialize → tools/list → tools/call round-trip', async () => {
assert.match(call.result.content[0].text, /graft build/);
});
+test('initialize carries instructions — the layer that survives tool deferral', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'graft-mcpsrv-instr-'));
+ const rs = await rpc(
+ [{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 't', version: '0' } } }],
+ dir,
+ 1,
+ );
+ const { instructions, serverInfo } = rs[0].result;
+ assert.equal(typeof instructions, 'string');
+ // A host that defers graft's schemas shows the model six bare names and nothing
+ // else, so this string has to carry both the pitch and the recovery instruction.
+ assert.match(instructions, /ONE lookup/, 'tells the agent to batch the schema fetch');
+ assert.match(instructions, /select:mcp__graft__graft_ask,/, 'gives a copy-pasteable query');
+ for (const t of ['graft_ask', 'graft_grep', 'graft_callers', 'graft_skeleton', 'graft_map']) {
+ assert.ok(instructions.includes(t), `names ${t}`);
+ }
+ // Observed sibling servers sit at 660–984 chars; nothing proves a longer one
+ // survives un-truncated, so hold the line here rather than discover it later.
+ assert.ok(instructions.length < 1000, `instructions must stay under 1000 chars, got ${instructions.length}`);
+ assert.match(serverInfo.version, /^\d+\.\d+\.\d+$/, 'real version, not the old hardcoded 0');
+});
+
test('unknown method returns -32601', async () => {
const dir = mkdtempSync(join(tmpdir(), 'graft-mcpsrv2-'));
const rs = await rpc([{ jsonrpc: '2.0', id: 9, method: 'resources/list' }], dir, 1);