Skip to content

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

Add --source flag to graft ask: inline span code, trim INDEX card list

anirudhkumar-nanonets23734bd94b27
diff --git a/.claude/skills/graft/SKILL.md b/.claude/skills/graft/SKILL.md
index 7645bb6f..90b5b79c 100644
--- a/.claude/skills/graft/SKILL.md
+++ b/.claude/skills/graft/SKILL.md
@@ -15,13 +15,26 @@ same understanding costs thousands.
**Get context from graft first — two ways, both land here:**
- Ask: `graft ask "<your task, in plain words>"` — returns the relevant nodes,
- ranked, with file:line pointers.
+ ranked, with file:line pointers. Add `--source` to inline the actual code at
+ each span, so the result IS the code you need — no separate file read.
- Or explore as usual: grep / ls / cat inside `graft/`. A grep for any concept,
symbol, or filename hits the node that covers it; `graft/INDEX.md` lists them
all.
-**Then work from the node.** Its summary is the answer; its `covers:` list gives
-the exact file:line. Open a source file only to edit those lines.
+**Then STOP at the node. It is the answer, not a lookup toward the answer.**
-Don't grep or read whole source files to build understanding — graft already
-did.
+- **Explaining / tracing / understanding** (no code change): the node's prose
+ IS your deliverable. Cite files and functions straight from its `covers:`
+ list — `covers:` gives you the exact `file:line` for every symbol, so you can
+ cite precisely **without opening the source at all.** Do NOT open source to
+ "verify," "confirm," or "see the real code" — the node was generated from that
+ source and the spans are authoritative. Opening it costs thousands of tokens
+ and changes nothing in your answer.
+- **Editing:** run `graft ask "<symbol>" --source` to pull the exact span's
+ code inline, and edit straight from that. Only touch the file to apply the
+ change at the named `file:line` — never read the whole file, never open
+ neighbouring files to "get oriented"; the pack already oriented you.
+
+If a node genuinely lacks a detail you need, `graft ask` for a more specific
+node before falling back to source. Reading whole source files to build
+understanding is the thing graft exists to replace — it already did that work.
diff --git a/src/ask/ask.ts b/src/ask/ask.ts
index 91d4d664..1ea98941 100644
--- a/src/ask/ask.ts
+++ b/src/ask/ask.ts
@@ -29,8 +29,16 @@ export interface AskHit {
relation?: Relation;
related?: string[];
score: number;
+ /** The actual source at `pointer`, sliced from disk when `source` is on.
+ * This is what makes `ask` substitutive — the agent reads the span here
+ * instead of opening the file, so no source read happens on top of the query. */
+ code?: string;
}
+/** Max source lines to inline per hit — a definition longer than this is
+ * truncated with a marker, so one giant function can't blow up the pack. */
+const MAX_SPAN_LINES = 80;
+
export interface AskResult {
query: string;
mode: "structural" | "lexical" | "empty";
@@ -236,19 +244,64 @@ function lexical(query: string, corpus: Corpus, limit: number): AskResult {
export interface AskOptions {
contextDir?: string;
limit?: number;
+ /** Inline the source at each `path:Lx-Ly` hit, sliced from `dir`. Turns the
+ * pack from a locator into a retriever so the agent needn't re-open the file. */
+ source?: boolean;
+}
+
+/** Parse a `path:Lx-Ly` pointer into its parts, or null if it isn't one
+ * (concept multi-path lists and raw import strings return null). */
+function parseSpan(pointer: string): { path: string; from: number; to: number } | null {
+ const m = pointer.match(/^(.*):L(\d+)-L(\d+)$/);
+ if (!m) return null;
+ return { path: m[1], from: Number(m[2]), to: Number(m[3]) };
+}
+
+/** Read the source lines [from, to] (1-indexed, inclusive) of `path` under `root`,
+ * capped at {@link MAX_SPAN_LINES}. Returns null if the file can't be read. */
+function sliceSpan(root: string, path: string, from: number, to: number): string | null {
+ try {
+ const lines = readFileSync(join(root, path), "utf8").split("\n");
+ const start = Math.max(1, from);
+ const end = Math.min(lines.length, to);
+ const slice = lines.slice(start - 1, end);
+ if (slice.length > MAX_SPAN_LINES) {
+ const head = slice.slice(0, MAX_SPAN_LINES);
+ head.push(`… (+${slice.length - MAX_SPAN_LINES} more lines; open ${path}:L${start}-L${end})`);
+ return head.join("\n");
+ }
+ return slice.join("\n");
+ } catch {
+ return null;
+ }
+}
+
+/** Attach inlined source to every hit whose pointer is a real `path:span`. */
+function inlineSource(root: string, hits: AskHit[]): void {
+ for (const h of hits) {
+ const s = parseSpan(h.pointer);
+ if (!s) continue;
+ const code = sliceSpan(root, s.path, s.from, s.to);
+ if (code) h.code = code;
+ }
}
/** Answer a query from the graft/ graph at `dir`. Deterministic, $0. */
export function ask(dir: string, query: string, opts: AskOptions = {}): AskResult {
- const outDir = contextDirFor(resolve(dir), opts.contextDir);
+ const root = resolve(dir);
+ const outDir = contextDirFor(root, opts.contextDir);
const limit = opts.limit ?? 8;
const corpus = loadCorpus(outDir);
+ let result: AskResult;
if (corpus.graph) {
const s = structural(query, corpus.graph, limit);
- if (s) return s;
+ result = s ?? lexical(query, corpus, limit);
+ } else {
+ result = lexical(query, corpus, limit);
}
- return lexical(query, corpus, limit);
+ if (opts.source) inlineSource(root, result.hits);
+ return result;
}
/** Render an {@link AskResult} as a compact markdown context pack. */
@@ -262,6 +315,7 @@ export function formatAsk(r: AskResult): string {
for (const h of r.hits) {
const tail = h.snippet ? ` — ${h.snippet}` : "";
lines.push(`- ${h.title} ${h.pointer} (${h.relation})${tail}`);
+ if (h.code) lines.push("", "```", h.code, "```", "");
}
} else {
r.hits.forEach((h, i) => {
@@ -269,6 +323,7 @@ export function formatAsk(r: AskResult): string {
lines.push(` ${h.pointer}`);
if (h.snippet) lines.push(` ${h.snippet}`);
if (h.related?.length) lines.push(` related: ${h.related.join(", ")}`);
+ if (h.code) lines.push("", "```", h.code, "```");
lines.push("");
});
}
diff --git a/src/cli.ts b/src/cli.ts
index 81446d2a..e87422b9 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -102,10 +102,11 @@ program
.argument("<query>", "what you want to understand, in plain words")
.argument("[dir]", "repository root", ".")
.option("-n, --limit <n>", "max results", "8")
+ .option("--source", "inline the source at each file:line hit (retriever mode — the pack IS the answer, no need to re-open files)")
.option("--json", "output the result as JSON")
- .action(async (query: string, dir: string, opts: { limit: string; json?: boolean }) => {
+ .action(async (query: string, dir: string, opts: { limit: string; source?: boolean; json?: boolean }) => {
const engine = engineFrom();
- const r = engine.ask(dir, query, { limit: Number(opts.limit) });
+ const r = engine.ask(dir, query, { limit: Number(opts.limit), source: opts.source });
if (opts.json) {
console.log(JSON.stringify(r, null, 2));
} else {
diff --git a/src/engine.ts b/src/engine.ts
index 3ab6d3f3..74aa240a 100644
--- a/src/engine.ts
+++ b/src/engine.ts
@@ -87,8 +87,8 @@ export class Graft {
* channel. Deterministic and $0: routes structural queries to the wiring
* edges and everything else to a lexical rank over concepts + symbols.
*/
- ask(dir: string, query: string, opts: { limit?: number } = {}): AskResult {
- return ask(dir, query, { contextDir: this.cfg.contextDir, limit: opts.limit });
+ ask(dir: string, query: string, opts: { limit?: number; source?: boolean } = {}): AskResult {
+ return ask(dir, query, { contextDir: this.cfg.contextDir, limit: opts.limit, source: opts.source });
}
/** The OpenRouter API key, or a clear error telling the user how to set it. */
diff --git a/src/graph/cards.ts b/src/graph/cards.ts
index 6905f038..c58e78b6 100644
--- a/src/graph/cards.ts
+++ b/src/graph/cards.ts
@@ -208,16 +208,14 @@ export function writeIndex(outDir: string, files: CardFileInfo[]): void {
}
if (files.length) {
+ const withSymbols = files.filter((f) => f.symbols > 0).length;
lines.push("## Files", "");
lines.push(
- "Per-file wiring cards mirror the source tree. `grep` a symbol or `find` a",
- "filename to land on its card.",
+ `${files.length} per-file wiring cards mirror the source tree under \`graft/\` ` +
+ `(${withSymbols} carry extracted symbols). They are deliberately not enumerated here —`,
+ "`grep` a symbol or `find`/`ls` a filename under `graft/` to land on the card for that file.",
"",
);
- for (const f of files) {
- lines.push(`- [${f.card}](${f.card}) — ${f.symbols} symbol${f.symbols === 1 ? "" : "s"}`);
- }
- lines.push("");
}
writeFileSync(join(outDir, INDEX_FILE), lines.join("\n"));
diff --git a/test/ask.test.ts b/test/ask.test.ts
new file mode 100644
index 00000000..7795897d
--- /dev/null
+++ b/test/ask.test.ts
@@ -0,0 +1,54 @@
+/**
+ * Tests for `graft ask` — specifically the `source` option, which turns the
+ * pack from a locator (pointers only) into a retriever (source inlined at each
+ * span). The retriever behaviour is what makes ask substitutive: the agent
+ * reads the span from the pack instead of opening the file.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { buildGraph } from "../src/graph/build.js";
+import { ask, formatAsk } from "../src/ask/ask.js";
+
+function makeFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-ask-"));
+ writeFileSync(
+ join(dir, "math.ts"),
+ `export function addNumbers(a: number, b: number): number {\n` +
+ ` return a + b;\n` +
+ `}\n`,
+ );
+ return dir;
+}
+
+test("ask without source returns pointers but no inlined code", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir); // $0, structure-only — cards + wiring.json
+ const r = ask(dir, "addNumbers");
+ const hit = r.hits.find((h) => h.title.startsWith("addNumbers"));
+ assert.ok(hit, "should locate the addNumbers symbol");
+ assert.match(hit.pointer, /^math\.ts:L\d+-L\d+$/);
+ assert.equal(hit.code, undefined, "no source inlined without the option");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("ask with source inlines the actual span from disk", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const r = ask(dir, "addNumbers", { source: true });
+ const hit = r.hits.find((h) => h.title.startsWith("addNumbers"));
+ assert.ok(hit, "should locate the addNumbers symbol");
+ assert.ok(hit.code, "source should be inlined");
+ assert.match(hit.code, /return a \+ b;/, "inlined code is the real definition body");
+ // formatAsk renders it as a fenced block so it drops into agent context.
+ assert.match(formatAsk(r), /```[\s\S]*return a \+ b;[\s\S]*```/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});