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(ai): vendor-neutral multi-provider LLM layer
anirudhkumar-nanonets75ee6ab47b12
diff --git a/.env.example b/.env.exampleindex 4763dd3d..9cfb17bc 100644--- a/.env.example+++ b/.env.example@@ -1,19 +1,45 @@# Graft — configuration#-# Graft calls OpenRouter for extraction and summaries, so an API key is-# required for any LLM-backed step (`init`, `graph --llm`). Get one at:-# https://openrouter.ai/keys-#-# Tier-1 graph structure (`graph`, `check`) is deterministic tree-sitter and+# Graft calls an LLM for concept nodes + per-symbol summaries, so an API key is+# required for the deep pass (`build --deep`). The structural build (`build`,+# `check`, `ask`, `grep`, `map`, traversal) is deterministic tree-sitter and# needs no key.+#+# Graft is vendor-neutral: GRAFT_PROVIDER picks the WIRE FORMAT, not a company.+# Bring your own key from whichever provider you use.++# --- Provider (required for `build --deep`) -----------------------------------+# Wire format / SDK: "openai" (any OpenAI-compatible endpoint) or "anthropic".+# GRAFT_PROVIDER=openai+# Your provider API key.+# GRAFT_API_KEY=+# Model id, as your provider names it.+# GRAFT_MODEL=openai/gpt-4o-mini+# Base URL for the "openai" wire format — this is how you pick a provider.+# Leave unset to hit api.openai.com. Examples:+# OpenRouter: https://openrouter.ai/api/v1+# Fireworks: https://api.fireworks.ai/inference/v1+# Groq: https://api.groq.com/openai/v1+# LiteLLM: http://localhost:4000 (your proxy)+# Ollama: http://localhost:11434/v1+# GRAFT_BASE_URL=https://openrouter.ai/api/v1+#+# Native Anthropic (no base URL needed):+# GRAFT_PROVIDER=anthropic+# GRAFT_API_KEY=sk-ant-...+# GRAFT_MODEL=claude-sonnet-5-# --- OpenRouter (required for LLM steps) --------------------------------------+# --- Deprecated (still honored as a fallback) ---------------------------------+# If GRAFT_API_KEY is unset, these legacy OpenRouter vars are used instead.# OPENROUTER_API_KEY=sk-or-...-# Optional: override the model (default: openai/gpt-4o-mini)-# GRAFT_OPENROUTER_MODEL=openai/gpt-4o-mini-# Optional: override the API base URL (default: https://openrouter.ai/api/v1)# OPENROUTER_BASE_URL=https://openrouter.ai/api/v1+# GRAFT_OPENROUTER_MODEL=openai/gpt-4o-mini# --- Graph location -----------------------------------------------------------# Where the graph lives (default: <repo>/.context)# GRAFT_DIR=.context++# --- Benchmark (bench/) -------------------------------------------------------+# Per-role model overrides for the benchmark harness.+# BENCH_AGENT_MODEL=anthropic/claude-sonnet-5+# BENCH_JUDGE_MODEL=anthropic/claude-opus-4.8diff --git a/README.md b/README.mdindex 3ceb92a3..9f953e33 100644--- a/README.md+++ b/README.md@@ -113,7 +113,7 @@ Graft builds that understanding **once** and writes it into your repo as a folde- **A real graph you can read.** No embeddings, no similarity search, no index to keep warm. The graph is a set of linked files your agent opens, greps, and follows, exactly the way it reads any other file in the repo.- **Grafted into git.** The graph is just files in `graft/`. Commit it, and anyone who clones the repo has it. No database, no server, no setup. Git does the syncing, and a stale graph shows up as a diff in review instead of rotting in some external store.- **The diff lives with the code.** When a change moves things around, you see it in the graph diff in the same pull request, right next to the code that caused it.-- **Your key, your model.** Summaries are written by a model you pick on [OpenRouter](https://openrouter.ai), under your own key. The structural code graph (`graft build`, `graft check`) is deterministic tree-sitter and never calls a model at all.+- **Your provider, your key, your model.** Summaries are written by any provider you choose — OpenAI, Anthropic (native), OpenRouter, Fireworks, Groq, a LiteLLM proxy, or a local model — under your own key. The structural code graph (`graft build`, `graft check`) is deterministic tree-sitter and never calls a model at all.---@@ -171,7 +171,7 @@ When the wiring graph exists, `graft check` validates it too — structural drif## What runs where- **On your machine, no key, no network:** the structural code graph. `graft build` (wiring graph + per-file cards), `graft check`, and `graft ask` are deterministic tree-sitter — they never call a model.-- **Through your OpenRouter key:** the LLM-written parts — `graft build --deep` adds the concept nodes (file summaries + node synthesis) and the per-symbol summaries and cruxes. Set `OPENROUTER_API_KEY` and optionally pick the model with `GRAFT_OPENROUTER_MODEL` (default: `openai/gpt-4o-mini`).+- **Through your provider key:** the LLM-written parts — `graft build --deep` adds the concept nodes (file summaries + node synthesis) and the per-symbol summaries and cruxes. graft is vendor-neutral: set `GRAFT_PROVIDER` (`openai` for any OpenAI-compatible endpoint, or `anthropic` for the native API), your `GRAFT_API_KEY`, `GRAFT_MODEL`, and — for the `openai` wire format — `GRAFT_BASE_URL` to point at OpenRouter, Fireworks, Groq, a LiteLLM proxy, a local server, or OpenAI itself. Or pass `--provider/--model/--api-key/--base-url` on the command line. (`OPENROUTER_API_KEY` still works as a deprecated fallback.)- **No telemetry** and no analytics — the only network calls are the LLM requests you configured.See [`.env.example`](.env.example) for the full list of settings (model, base URL, graph directory).diff --git a/bench/README.md b/bench/README.mdindex f384237e..7b5ac631 100644--- a/bench/README.md+++ b/bench/README.md@@ -32,9 +32,15 @@ average.## Requirements-- `OPENROUTER_API_KEY` — agent (`anthropic/claude-sonnet-5`) and judge- (`anthropic/claude-opus-4.8`) run through OpenRouter. Graph building is keyless.- Override the models with `BENCH_AGENT_MODEL` / `BENCH_JUDGE_MODEL`.+- A provider key — the agent (`anthropic/claude-sonnet-5`) and judge+ (`anthropic/claude-opus-4.8`) run through the same vendor-neutral provider+ layer as the engine. Set `GRAFT_API_KEY` (+ `GRAFT_PROVIDER` / `GRAFT_BASE_URL`),+ or the legacy `OPENROUTER_API_KEY`. Graph building is keyless. Override the+ models with `BENCH_AGENT_MODEL` / `BENCH_JUDGE_MODEL`.+- The committed baseline was recorded via OpenRouter (no extended thinking). If+ you rerun against the **native** `anthropic` provider, note that current Claude+ models enable adaptive thinking by default, which inflates output tokens — so+ those numbers are not directly comparable to the committed baseline.## Rundiff --git a/bench/agent.ts b/bench/agent.tsindex 0084642d..7dc3aea8 100644--- a/bench/agent.ts+++ b/bench/agent.ts@@ -8,12 +8,12 @@* We run a *manual* loop so we can read `usage` off every turn and sum it, so* the reported token cost is exact rather than estimated.*/-import type OpenAI from "openai";import { readFileSync, statSync, readdirSync, realpathSync } from "node:fs";import { resolve, relative, join, isAbsolute, sep } from "node:path";import { SKIP_DIRS, MAX_FILE_BYTES } from "../src/ingest/fs.js";import { ask, formatAsk, skeleton, formatSkeleton } from "../src/ask/ask.js";-import { makeClient, AGENT_MODEL } from "./llm.js";+import { makeChatModel, AGENT_MODEL } from "./llm.js";+import type { ChatModel, Message, ToolSpec } from "../src/ai/llm/types.js";export { AGENT_MODEL };@@ -38,7 +38,7 @@ export interface RunAgentOptions {* front; the agent pays for graph context only when it asks for it. */graft?: { contextDir: string };maxIterations?: number;- client?: OpenAI;+ model?: ChatModel;}const SYSTEM_PROMPT =@@ -110,92 +110,74 @@ function globToRegExp(glob: string): RegExp {return new RegExp("^" + re + "$");}-/** Tool definitions in OpenAI/OpenRouter function-calling format. */-const TOOLS: OpenAI.Chat.Completions.ChatCompletionTool[] = [+/** Tool definitions in provider-neutral form. */+const TOOLS: ToolSpec[] = [{- type: "function",- function: {- name: "read_file",- description: "Read a UTF-8 text file under the root. Optionally limit to a line range.",- parameters: {- type: "object",- properties: {- path: { type: "string", description: "Path relative to the root" },- start_line: { type: "integer", description: "1-based first line (optional)" },- end_line: { type: "integer", description: "1-based last line (optional)" },- },- required: ["path"],+ name: "read_file",+ description: "Read a UTF-8 text file under the root. Optionally limit to a line range.",+ parameters: {+ type: "object",+ properties: {+ path: { type: "string", description: "Path relative to the root" },+ start_line: { type: "integer", description: "1-based first line (optional)" },+ end_line: { type: "integer", description: "1-based last line (optional)" },},+ required: ["path"],},},{- type: "function",- function: {- name: "grep",- description: "Search file contents with a JavaScript regular expression. Returns matching lines as path:line: text.",- parameters: {- type: "object",- properties: {- pattern: { type: "string", description: "Regular expression" },- path: { type: "string", description: "Restrict to this subdirectory or file (optional)" },- ignore_case: { type: "boolean", description: "Case-insensitive match (optional)" },- },- required: ["pattern"],+ name: "grep",+ description: "Search file contents with a JavaScript regular expression. Returns matching lines as path:line: text.",+ parameters: {+ type: "object",+ properties: {+ pattern: { type: "string", description: "Regular expression" },+ path: { type: "string", description: "Restrict to this subdirectory or file (optional)" },+ ignore_case: { type: "boolean", description: "Case-insensitive match (optional)" },},+ required: ["pattern"],},},{- type: "function",- function: {- name: "glob",- description: "List files whose root-relative path matches a glob (e.g. src/**/*.ts).",- parameters: { type: "object", properties: { pattern: { type: "string" } }, required: ["pattern"] },- },+ name: "glob",+ description: "List files whose root-relative path matches a glob (e.g. src/**/*.ts).",+ parameters: { type: "object", properties: { pattern: { type: "string" } }, required: ["pattern"] },},{- type: "function",- function: {- name: "list_dir",- description: "List the entries of a directory under the root.",- parameters: {- type: "object",- properties: { path: { type: "string", description: "Directory relative to the root (default: root)" } },- required: [],- },+ name: "list_dir",+ description: "List the entries of a directory under the root.",+ parameters: {+ type: "object",+ properties: { path: { type: "string", description: "Directory relative to the root (default: root)" } },+ required: [],},},];/** Extra tools for the pull arm: the graft graph as an on-demand service. */-const GRAFT_TOOLS: OpenAI.Chat.Completions.ChatCompletionTool[] = [+const GRAFT_TOOLS: ToolSpec[] = [{- type: "function",- function: {- name: "graft_ask",- description:- "Query this repo's prebuilt context graph in plain words. Returns ranked symbols/concepts with exact file:line spans and the relevant source inlined — the cheapest way to locate and understand code. Prefer it over grep/read_file for orientation; use structural phrasings too ('who calls X').",- parameters: {- type: "object",- properties: {- query: { type: "string", description: "What you want to understand, in plain words" },- limit: { type: "integer", description: "Max results (default 5)" },- full: { type: "boolean", description: "Inline whole definition spans instead of crux excerpts" },- },- required: ["query"],+ name: "graft_ask",+ description:+ "Query this repo's prebuilt context graph in plain words. Returns ranked symbols/concepts with exact file:line spans and the relevant source inlined — the cheapest way to locate and understand code. Prefer it over grep/read_file for orientation; use structural phrasings too ('who calls X').",+ parameters: {+ type: "object",+ properties: {+ query: { type: "string", description: "What you want to understand, in plain words" },+ limit: { type: "integer", description: "Max results (default 5)" },+ full: { type: "boolean", description: "Inline whole definition spans instead of crux excerpts" },},+ required: ["query"],},},{- type: "function",- function: {- name: "graft_skeleton",- description:- "Signatures-only view of one file — every definition's signature + line span, ~10× cheaper than reading the file.",- parameters: {- type: "object",- properties: { file: { type: "string", description: "Repo-relative file path" } },- required: ["file"],- },+ name: "graft_skeleton",+ description:+ "Signatures-only view of one file — every definition's signature + line span, ~10× cheaper than reading the file.",+ parameters: {+ type: "object",+ properties: { file: { type: "string", description: "Repo-relative file path" } },+ required: ["file"],},},];@@ -277,7 +259,7 @@ function runTool(root: string, name: string, input: any, graft?: { contextDir: s}export async function runAgent(opts: RunAgentOptions): Promise<AgentResult> {- const client = opts.client ?? makeClient();+ const model = opts.model ?? makeChatModel(AGENT_MODEL);const root = resolve(opts.root);const maxIterations = opts.maxIterations ?? 15;@@ -287,29 +269,27 @@ export async function runAgent(opts: RunAgentOptions): Promise<AgentResult> {`<graph_context>\n${opts.contextBundle}\n</graph_context>\n\nQuestion: ${opts.question}`: `Question: ${opts.question}`;- // Content is expressed as parts so we can attach Anthropic prompt-caching- // breakpoints (OpenRouter forwards `cache_control` to Anthropic). The system- // + tools + the (possibly large) bundle are a stable head, cached once; a- // breakpoint then slides onto the newest tool result each turn so the entire- // prior transcript is a cache read rather than re-billed at full price —- // which is how Claude Code actually runs, and what makes the token numbers fair.- const cc = { type: "ephemeral" as const };+ // Cache breakpoints (Message.cacheBreakpoint) let the adapter mark a stable+ // prefix as cacheable. The system + tools + the (possibly large) bundle are a+ // stable head, cached once; a breakpoint then slides onto the newest tool+ // result each turn so the entire prior transcript is a cache read rather than+ // re-billed at full price — which is how Claude Code actually runs, and what+ // makes the token numbers fair.const systemText = opts.graft? SYSTEM_PROMPT +" This repo also has a prebuilt context graph: the graft_ask and graft_skeleton tools query it and are much cheaper than grep/read_file for finding and understanding code.": SYSTEM_PROMPT;const tools = opts.graft ? [...TOOLS, ...GRAFT_TOOLS] : TOOLS;- const messages: any[] = [- { role: "system", content: [{ type: "text", text: systemText, cache_control: cc }] },- { role: "user", content: [{ type: "text", text: userText, cache_control: cc }] },+ const messages: Message[] = [+ { role: "system", content: systemText, cacheBreakpoint: true },+ { role: "user", content: userText, cacheBreakpoint: true },];/** Keep the cache breakpoint on the most recent tool result (strip it from older ones). */const slideCacheBreakpoint = () => {const toolMsgs = messages.filter((m) => m.role === "tool");toolMsgs.forEach((m, i) => {- const part = Array.isArray(m.content) ? m.content[m.content.length - 1] : null;- if (part) part.cache_control = i === toolMsgs.length - 1 ? cc : undefined;+ m.cacheBreakpoint = i === toolMsgs.length - 1;});};const tokens = { input: 0, output: 0, cacheRead: 0, cacheCreate: 0, total: 0 };@@ -321,42 +301,27 @@ export async function runAgent(opts: RunAgentOptions): Promise<AgentResult> {const started = Date.now();for (iterations = 1; iterations <= maxIterations; iterations++) {- const resp = await client.chat.completions.create({- model: AGENT_MODEL,- max_tokens: 4096,- messages,- tools,- });- const u: any = resp.usage ?? {};- const cached = u.prompt_tokens_details?.cached_tokens ?? 0;- tokens.cacheRead += cached;- tokens.input += Math.max(0, (u.prompt_tokens ?? 0) - cached); // uncached input only- tokens.output += u.completion_tokens ?? 0;- const choice = resp.choices[0];- stopReason = choice?.finish_reason ?? null;- const msg = choice?.message;- if (!msg) break;+ const resp = await model.create({ messages, tools, maxTokens: 4096 });+ // Usage is already normalized (input = uncached-only) by the adapter.+ tokens.input += resp.usage.input;+ tokens.output += resp.usage.output;+ tokens.cacheRead += resp.usage.cacheRead;+ tokens.cacheCreate += resp.usage.cacheCreate;+ stopReason = resp.stopReason;- messages.push(msg); // preserve the assistant turn (with any tool_calls) for the next request+ messages.push(resp.assistant); // preserve the assistant turn (verbatim replay) for the next request- const toolCallList = msg.tool_calls ?? [];- if (toolCallList.length === 0) {- answer = (msg.content ?? "").trim();+ if (resp.toolCalls.length === 0) {+ answer = resp.text.trim();break;}- for (const tc of toolCallList) {- if (tc.type !== "function") continue;+ for (const tc of resp.toolCalls) {toolCalls++;- let input: any = {};- try {- input = JSON.parse(tc.function.arguments || "{}");- } catch {- /* leave input empty; runTool will error informatively */- }- toolLog.push({ name: tc.function.name, input });- const result = runTool(root, tc.function.name, input, opts.graft);- messages.push({ role: "tool", tool_call_id: tc.id, content: [{ type: "text", text: result }] });+ const input = (tc.args ?? {}) as any; // already parsed by the adapter+ toolLog.push({ name: tc.name, input });+ const result = runTool(root, tc.name, input, opts.graft);+ messages.push({ role: "tool", toolCallId: tc.id, content: result });}slideCacheBreakpoint();}@@ -364,7 +329,7 @@ export async function runAgent(opts: RunAgentOptions): Promise<AgentResult> {if (!answer) {// Loop hit the cap — take the last assistant text we have.for (let i = messages.length - 1; i >= 0; i--) {- if (messages[i].role === "assistant" && typeof messages[i].content === "string" && messages[i].content.trim()) {+ if (messages[i].role === "assistant" && messages[i].content.trim()) {answer = messages[i].content.trim();break;}diff --git a/bench/judge.ts b/bench/judge.tsindex 4458c495..2e0de53b 100644--- a/bench/judge.ts+++ b/bench/judge.ts@@ -10,8 +10,8 @@** Final correctness = judge says correct AND the keyword floor passed.*/-import type OpenAI from "openai";-import { makeClient, JUDGE_MODEL } from "./llm.js";+import { makeChatModel, JUDGE_MODEL } from "./llm.js";+import type { ChatModel } from "../src/ai/llm/types.js";export { JUDGE_MODEL };@@ -28,7 +28,7 @@ export interface JudgeInput {referenceAnswer: string;agentAnswer: string;requiredKeywords: string[];- client?: OpenAI;+ model?: ChatModel;}/** Pull the first {...} JSON object out of a string (models sometimes wrap JSON in prose/fences). */@@ -49,7 +49,7 @@ function extractJson(text: string): any {}export async function judge(input: JudgeInput): Promise<Verdict> {- const client = input.client ?? makeClient();+ const model = input.model ?? makeChatModel(JUDGE_MODEL);const kw = input.requiredKeywords ?? [];const hay = input.agentAnswer.toLowerCase();@@ -65,14 +65,13 @@ export async function judge(input: JudgeInput): Promise<Verdict> {`Grade whether the agent's answer is factually correct and responsive, judged against the reference. ` +`Extra correct detail is fine; contradicting the reference or missing the core fact is not.`;- const resp = await client.chat.completions.create({- model: JUDGE_MODEL,- max_tokens: 1024,+ const resp = await model.create({+ maxTokens: 1024,messages: [{ role: "user", content: prompt }],- response_format: { type: "json_object" },+ responseFormat: { kind: "json" },});- const text = resp.choices[0]?.message?.content ?? "";+ const text = resp.text;const parsed = extractJson(text) ?? { correct: false, score: 0, reasoning: `unparseable judge output: ${text.slice(0, 200)}` };const score = Math.max(0, Math.min(1, Number(parsed.score) || 0));diff --git a/bench/llm.ts b/bench/llm.tsindex 370ef1fe..f6e43202 100644--- a/bench/llm.ts+++ b/bench/llm.ts@@ -1,18 +1,28 @@/**- * LLM plumbing for the benchmark. Routed through OpenRouter (the same key the- * engine uses for extraction) via the OpenAI-compatible SDK, so no separate- * Anthropic API key is needed. Models are still Claude — just served by- * OpenRouter — and overridable via env.+ * LLM plumbing for the benchmark. Routed through the same vendor-neutral+ * provider layer the engine uses (`src/ai/llm`), so the bench runs against+ * whatever provider is configured (`GRAFT_PROVIDER` / `GRAFT_API_KEY` /+ * `GRAFT_BASE_URL`, or the legacy `OPENROUTER_API_KEY`). The default models are+ * OpenRouter-style Claude ids; override per role via env.*/-import OpenAI from "openai";+import { resolveConfig } from "../src/ai/providers.js";+import { createChatModel } from "../src/ai/llm/factory.js";+import type { ChatModel } from "../src/ai/llm/types.js";-export const OPENROUTER_BASE_URL = process.env.OPENROUTER_BASE_URL ?? "https://openrouter.ai/api/v1";export const AGENT_MODEL = process.env.BENCH_AGENT_MODEL ?? "anthropic/claude-sonnet-5";export const JUDGE_MODEL = process.env.BENCH_JUDGE_MODEL ?? "anthropic/claude-opus-4.8";-/** A configured OpenRouter client. Throws if the key is missing (the cold arm can't run without it either). */-export function makeClient(): OpenAI {- const apiKey = process.env.OPENROUTER_API_KEY;- if (!apiKey) throw new Error("OPENROUTER_API_KEY is required (agent + judge run through OpenRouter).");- return new OpenAI({ apiKey, baseURL: OPENROUTER_BASE_URL });+/** A configured transport for `model`. Throws if no provider key is set. */+export function makeChatModel(model: string): ChatModel {+ const cfg = resolveConfig({ model });+ if (!cfg.apiKey) {+ throw new Error("Set GRAFT_API_KEY (or OPENROUTER_API_KEY) — the bench agent + judge need a provider key.");+ }+ return createChatModel({+ provider: cfg.provider,+ apiKey: cfg.apiKey,+ model,+ baseUrl: cfg.baseUrl,+ headers: cfg.headers,+ });}diff --git a/bench/run.ts b/bench/run.tsindex 308818ed..4f83329a 100644--- a/bench/run.ts+++ b/bench/run.ts@@ -28,7 +28,8 @@ import { ask, formatAsk } from "../src/ask/ask.js";import { CORPORA } from "./tasks.js";import { runAgent } from "./agent.js";import { judge } from "./judge.js";-import { makeClient } from "./llm.js";+import { makeChatModel, AGENT_MODEL, JUDGE_MODEL } from "./llm.js";+import { resolveConfig } from "../src/ai/providers.js";import { buildMarkdown, type Row, type Arm } from "./report.js";const here = dirname(fileURLToPath(import.meta.url));@@ -81,11 +82,12 @@ async function pool<T, R>(items: T[], n: number, fn: (item: T) => Promise<R>): Pasync function main() {const args = parseArgs(process.argv.slice(2));- if (!process.env.OPENROUTER_API_KEY) {- console.error("Set OPENROUTER_API_KEY (agent and judge run through OpenRouter).");+ if (!resolveConfig().apiKey) {+ console.error("Set GRAFT_API_KEY (or OPENROUTER_API_KEY) — the agent and judge need a provider key.");process.exit(1);}- const client = makeClient();+ const agentModel = makeChatModel(AGENT_MODEL);+ const judgeModel = makeChatModel(JUDGE_MODEL);const corpora = CORPORA.filter((c) => !args.corpora || args.corpora.includes(c.id));if (corpora.length === 0) {@@ -142,14 +144,14 @@ async function main() {};try {const ar = await runAgent({- client,+ model: agentModel,root: corpus.path,question: task.question,contextBundle: arm === "graph" ? bundles.get(task.id) : undefined,graft: arm === "pull" ? { contextDir: graftDir } : undefined,});const v = await judge({- client,+ model: judgeModel,question: task.question,referenceAnswer: task.referenceAnswer,agentAnswer: ar.answer,diff --git a/bench/selfcheck.ts b/bench/selfcheck.tsindex dbe23a44..4f8a134e 100644--- a/bench/selfcheck.ts+++ b/bench/selfcheck.ts@@ -12,39 +12,30 @@ import assert from "node:assert/strict";import { runAgent } from "./agent.js";import { judge } from "./judge.js";import { buildMarkdown, type Row } from "./report.js";+import type { ChatModel } from "../src/ai/llm/types.js";-const usage = { prompt_tokens: 100, completion_tokens: 50, total_tokens: 150 };+const usage = { input: 100, output: 50, cacheRead: 0, cacheCreate: 0 };-/** Stub that mimics the OpenAI/OpenRouter chat.completions shape our code reads. Judge turns pass `response_format`. */-function makeStubClient() {+/** Stub {@link ChatModel}: agent uses grep then answers; a `json` request is the judge. */+function makeStubModel(): ChatModel {let agentTurn = 0;return {- chat: {- completions: {- create: async (params: any) => {- if (params.response_format) {- // Judge call → JSON verdict.- return {- choices: [{ message: { role: "assistant", content: JSON.stringify({ correct: true, score: 0.9, reasoning: "matches reference" }) }, finish_reason: "stop" }],- usage,- };- }- // Agent call. First turn: use grep. Second turn: final answer.- agentTurn++;- if (agentTurn === 1) {- return {- choices: [{ message: { role: "assistant", content: null, tool_calls: [{ id: "tc_1", type: "function", function: { name: "grep", arguments: JSON.stringify({ pattern: "SECRET_TOKEN" }) } }] }, finish_reason: "tool_calls" }],- usage,- };- }- return {- choices: [{ message: { role: "assistant", content: "The secret token is SECRET_TOKEN, defined in config.ts." }, finish_reason: "stop" }],- usage,- };- },- },+ label: "stub:model",+ async create(req) {+ if (req.responseFormat?.kind === "json") {+ const text = JSON.stringify({ correct: true, score: 0.9, reasoning: "matches reference" });+ return { text, toolCalls: [], usage, stopReason: "stop", assistant: { role: "assistant", content: text } };+ }+ // Agent call. First turn: use grep. Second turn: final answer.+ agentTurn++;+ if (agentTurn === 1) {+ const toolCalls = [{ id: "tc_1", name: "grep", args: { pattern: "SECRET_TOKEN" } }];+ return { text: "", toolCalls, usage, stopReason: "tool_use", assistant: { role: "assistant", content: "", toolCalls } };+ }+ const text = "The secret token is SECRET_TOKEN, defined in config.ts.";+ return { text, toolCalls: [], usage, stopReason: "stop", assistant: { role: "assistant", content: text } };},- } as any;+ };}async function main() {@@ -52,10 +43,10 @@ async function main() {mkdirSync(join(root, "src"), { recursive: true });writeFileSync(join(root, "src", "config.ts"), "export const token = 'SECRET_TOKEN';\n");- const client = makeStubClient();+ const model = makeStubModel();// 1. Agent loop: should call the grep tool once, then answer.- const ar = await runAgent({ client, root, question: "What is the secret token?" });+ const ar = await runAgent({ model, root, question: "What is the secret token?" });assert.equal(ar.toolCalls, 1, "expected exactly one tool call");assert.equal(ar.toolLog[0].name, "grep", "expected the grep tool to run");assert.ok(ar.answer.includes("SECRET_TOKEN"), "answer should contain the fact");@@ -65,7 +56,7 @@ async function main() {// 2. Real tool execution actually found the file (grep ran against the temp repo).const graphAr = await runAgent({- client: makeStubClient(),+ model: makeStubModel(),root,question: "What is the secret token?",contextBundle: "# Context\nSECRET_TOKEN lives in config.ts",@@ -75,7 +66,7 @@ async function main() {// 3. Judge: keyword floor + parsed verdict.const v = await judge({- client,+ model,question: "What is the secret token?",referenceAnswer: "SECRET_TOKEN",agentAnswer: ar.answer,@@ -89,7 +80,7 @@ async function main() {// 3b. Keyword floor overrides an over-generous judge.const vMiss = await judge({- client,+ model,question: "q",referenceAnswer: "SECRET_TOKEN",agentAnswer: "I could not find it.",diff --git a/bench/token-ab.ts b/bench/token-ab.tsindex 99f2c6eb..94abb3f4 100644--- a/bench/token-ab.ts+++ b/bench/token-ab.ts@@ -18,10 +18,11 @@* Tune: edit the CONFIG block, or override via env (REPO, QUESTION, MODEL, MAX_STEPS).*/import "dotenv/config";-import OpenAI from "openai";import { execFileSync } from "node:child_process";import { readFileSync, existsSync } from "node:fs";import { resolve, relative, isAbsolute } from "node:path";+import { makeChatModel } from "./llm.js";+import type { Message, ToolSpec } from "../src/ai/llm/types.js";// ─────────────────────────── CONFIG (edit freely) ───────────────────────────const CONFIG = {@@ -44,17 +45,12 @@ const CONFIG = {};// ─────────────────────────────────────────────────────────────────────────────-const KEY = process.env.OPENROUTER_API_KEY;-if (!KEY) {- console.error("✗ OPENROUTER_API_KEY not set (expected in context-engine/.env).");- process.exit(1);-}if (!existsSync(CONFIG.REPO)) {console.error(`✗ REPO not found: ${CONFIG.REPO}`);process.exit(1);}-const client = new OpenAI({ apiKey: KEY, baseURL: "https://openrouter.ai/api/v1" });+const model = makeChatModel(CONFIG.MODEL);interface Metrics {arm: string;@@ -72,34 +68,28 @@ const SYSTEM ="Be accurate and cite specific files and functions. When you have enough to answer, " +"STOP calling tools and write the final answer as prose. Do not pad.";-const TOOLS: OpenAI.Chat.Completions.ChatCompletionTool[] = [+const TOOLS: ToolSpec[] = [{- type: "function",- function: {- name: "search",- description:- "Regex search across the repo's source (ripgrep). Returns matching file:line: text rows.",- parameters: {- type: "object",- properties: { pattern: { type: "string", description: "regex or literal to search for" } },- required: ["pattern"],- },+ name: "search",+ description:+ "Regex search across the repo's source (ripgrep). Returns matching file:line: text rows.",+ parameters: {+ type: "object",+ properties: { pattern: { type: "string", description: "regex or literal to search for" } },+ required: ["pattern"],},},{- type: "function",- function: {- name: "read_file",- description: "Read a source file (optionally a line range) relative to the repo root.",- parameters: {- type: "object",- properties: {- path: { type: "string", description: "repo-relative path, e.g. src/components/chat/TaskFeed.tsx" },- start_line: { type: "number", description: "1-based start line (optional)" },- end_line: { type: "number", description: "1-based end line (optional)" },- },- required: ["path"],+ name: "read_file",+ description: "Read a source file (optionally a line range) relative to the repo root.",+ parameters: {+ type: "object",+ properties: {+ path: { type: "string", description: "repo-relative path, e.g. src/components/chat/TaskFeed.tsx" },+ start_line: { type: "number", description: "1-based start line (optional)" },+ end_line: { type: "number", description: "1-based end line (optional)" },},+ required: ["path"],},},];@@ -172,51 +162,42 @@ async function runAgent(arm: string, extraContext: string | null): Promise<Metri"=== CONTEXT PACK ===\n" + extraContext,);}- const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [+ const messages: Message[] = [{ role: "system", content: SYSTEM },{ role: "user", content: userParts.join("\n") },];for (let step = 0; step < CONFIG.MAX_STEPS; step++) {- const resp = await client.chat.completions.create({- model: CONFIG.MODEL,- temperature: 0,- messages,- tools: TOOLS,- tool_choice: "auto",- });+ const resp = await model.create({ temperature: 0, maxTokens: 4096, messages, tools: TOOLS });m.llmCalls++;- m.promptTokens += resp.usage?.prompt_tokens ?? 0;- m.completionTokens += resp.usage?.completion_tokens ?? 0;+ m.promptTokens += resp.usage.input + resp.usage.cacheRead;+ m.completionTokens += resp.usage.output;- const msg = resp.choices[0].message;- messages.push(msg as OpenAI.Chat.Completions.ChatCompletionMessageParam);+ messages.push(resp.assistant);- const calls = msg.tool_calls ?? [];- if (calls.length === 0) {- m.answer = msg.content ?? "(empty)";+ if (resp.toolCalls.length === 0) {+ m.answer = resp.text || "(empty)";break;}- for (const call of calls) {- if (call.type !== "function") continue;+ for (const call of resp.toolCalls) {m.toolCalls++;let result = "";try {- const args = JSON.parse(call.function.arguments || "{}");- if (call.function.name === "search") {+ const args = (call.args ?? {}) as any;+ if (call.name === "search") {result = runSearch(String(args.pattern ?? ""));- } else if (call.function.name === "read_file") {+ } else if (call.name === "read_file") {const r = runRead(String(args.path ?? ""), args.start_line, args.end_line);if (existsSync(resolve(CONFIG.REPO, String(args.path ?? "")))) m.filesRead.add(r.resolved);result = r.text;} else {- result = `(unknown tool ${call.function.name})`;+ result = `(unknown tool ${call.name})`;}} catch (e: any) {result = `(tool error: ${e?.message ?? e})`;}- messages.push({ role: "tool", tool_call_id: call.id, content: result });+ messages.push({ role: "tool", toolCallId: call.id, content: result });}if (step === CONFIG.MAX_STEPS - 1) m.answer = "(hit MAX_STEPS without a final answer)";}diff --git a/graft/.graph/wiring.json b/graft/.graph/wiring.jsonindex 8ae57e68..ab706939 100644--- a/graft/.graph/wiring.json+++ b/graft/.graph/wiring.json@@ -1,8 +1,8 @@{"meta": {"version": 1,- "nodeCount": 701,- "edgeCount": 1823,+ "nodeCount": 750,+ "edgeCount": 1924,"languages": ["typescript"]@@ -13,15 +13,18 @@"name": "agent.ts","kind": "file","path": "bench/agent.ts",- "span": "L1-L377",+ "span": "L1-L342","signature": null,"exported": true,"origin": "ast",- "body_hash": "6e18be8d88e168e07712118533702c7422ee76753d4dcf6032ae685a8c106c8a",- "chars": 14646,- "summary_state": "stale",- "summary": "This file implements a benchmark agent that processes questions about a codebase using filesystem tools and a language model.",- "crux": null+ "body_hash": "34a496d38f2dfc14688cb4f0981262d79dacef165bd1a4f9874b94c31e1819e9",+ "chars": 13521,+ "summary_state": "ready",+ "summary": "This file implements a benchmark agent that executes a loop for evaluating the performance of different AI models in answering questions based on a codebase.",+ "crux": {+ "code": "export interface RunAgentOptions {\n /** Directory the filesystem tools are confined to. */\n root: string;\n question: string;\n /** When set (graph/push arm), this bundle is injected before the question. */\n contextBundle?: string;\n /** When set (pull arm), the agent additionally gets graft_ask/graft_skeleton\n * tools over the prebuilt graph at this contextDir — nothing injected up\n * front; the agent pays for graph context only when it asks for it. */\n graft?: { contextDir: string };\n maxIterations?: number;\n model?: ChatModel;",+ "span": "L30-L41"+ }},{"id": "bench/agent.ts#AgentResult",@@ -93,16 +96,16 @@"name": "runAgent","kind": "function","path": "bench/agent.ts",- "span": "L279-L376",+ "span": "L261-L341","signature": "async function runAgent(opts: RunAgentOptions): Promise<AgentResult>","exported": true,"origin": "ast",- "body_hash": "5a040fb6f172fea417b7de9b0ae49367cb64b41e35c49e19bf9b1dbb7198f3a6",- "summary_state": "stale",- "summary": "Manages the execution of the agent's logic, including handling user questions and tool interactions.",+ "body_hash": "18b047787ff99383e6137911724c03da6cc58294bfc727176fb9f8eab9922130",+ "summary_state": "ready",+ "summary": "Manages the execution of the agent, processing user questions and utilizing tools to generate answers while tracking performance metrics.","crux": {- "code": " const resp = await client.chat.completions.create({\n model: AGENT_MODEL,\n max_tokens: 4096,\n messages,\n tools: TOOLS,\n });\n const u: any = resp.usage ?? {};\n const cached = u.prompt_tokens_details?.cached_tokens ?? 0;\n tokens.cacheRead += cached;\n tokens.input += Math.max(0, (u.prompt_tokens ?? 0) - cached); // uncached input only\n tokens.output += u.completion_tokens ?? 0;\n const choice = resp.choices[0];",- "span": "L270-L281"+ "code": "export async function runAgent(opts: RunAgentOptions): Promise<AgentResult> {\n const model = opts.model ?? makeChatModel(AGENT_MODEL);\n const root = resolve(opts.root);\n const maxIterations = opts.maxIterations ?? 15;\n\n const userText = opts.contextBundle\n ? `A knowledge graph of these files was queried for this task and returned the context below. ` +\n `Use it to answer; you may still use the tools to confirm or fill gaps.\\n\\n` +\n `<graph_context>\\n${opts.contextBundle}\\n</graph_context>\\n\\nQuestion: ${opts.question}`\n : `Question: ${opts.question}`;\n\n // Cache breakpoints (Message.cacheBreakpoint) let the adapter mark a stable",+ "span": "L261-L272"}},{@@ -110,16 +113,16 @@"name": "slideCacheBreakpoint","kind": "function","path": "bench/agent.ts",- "span": "L308-L314",+ "span": "L289-L294","signature": "slideCacheBreakpoint = ()","exported": true,"origin": "ast",- "body_hash": "c5c9e42b4e085cfd27d6614a97f5208d50aed8551304862e6eb81c56edab795a",+ "body_hash": "8d5bb7899e04ee3a8acccc0cf663bb7e90af29d67512d6be141896f5ce3f20d5","summary_state": "ready",- "summary": "Maintains the cache state by updating the cache control for the most recent tool result in the message history.",+ "summary": "Maintains the cache breakpoint on the most recent tool result to optimize performance during the agent's execution.","crux": {- "code": " const toolMsgs = messages.filter((m) => m.role === \"tool\");\n toolMsgs.forEach((m, i) => {\n const part = Array.isArray(m.content) ? m.content[m.content.length - 1] : null;\n if (part) part.cache_control = i === toolMsgs.length - 1 ? cc : undefined;\n });",- "span": "L255-L259"+ "code": " const slideCacheBreakpoint = () => {\n const toolMsgs = messages.filter((m) => m.role === \"tool\");\n toolMsgs.forEach((m, i) => {\n m.cacheBreakpoint = i === toolMsgs.length - 1;\n });\n };",+ "span": "L289-L294"}},{@@ -131,26 +134,29 @@"signature": "interface RunAgentOptions","exported": true,"origin": "ast",- "body_hash": "bd60aca99e3b8bb21cd4769b56ce1464502df9ea4eb7c665d53bc6ca0d2e540b",- "summary_state": "stale",- "summary": "Specifies the options for running the agent, including the root directory and the question to be answered.",- "crux": null+ "body_hash": "6bea792855de015a870cd69720098286069460f9aa7be6e51447a2b1fabf320c",+ "summary_state": "ready",+ "summary": "Defines the options for running the agent, including the root directory and the question to be answered.",+ "crux": {+ "code": "export interface RunAgentOptions {\n /** Directory the filesystem tools are confined to. */\n root: string;\n question: string;\n /** When set (graph/push arm), this bundle is injected before the question. */\n contextBundle?: string;\n /** When set (pull arm), the agent additionally gets graft_ask/graft_skeleton\n * tools over the prebuilt graph at this contextDir — nothing injected up\n * front; the agent pays for graph context only when it asks for it. */\n graft?: { contextDir: string };\n maxIterations?: number;\n model?: ChatModel;",+ "span": "L30-L41"+ }},{"id": "bench/agent.ts#runTool","name": "runTool","kind": "function","path": "bench/agent.ts",- "span": "L207-L277",+ "span": "L189-L259","signature": "function runTool(root: string, name: string, input: any, graft?: { contextDir: string }): string","exported": false,"origin": "ast","body_hash": "00cdcb79849a3f634c0ea08fe3d26b8156d8714e7b2c5d51ca645f74337852c4",- "summary_state": "stale",- "summary": "Executes a specified tool (like reading a file or listing a directory) based on the provided input parameters.",+ "summary_state": "ready",+ "summary": "Executes a specified tool with given input, handling various file operations and queries within a defined root directory.","crux": {"code": " if (name === \"read_file\") {\n const file = safePath(root, String(input.path));\n const lines = readFileSync(file, \"utf8\").split(\"\\n\");\n const start = input.start_line ? Math.max(1, input.start_line) : 1;\n const end = input.end_line ? Math.min(lines.length, input.end_line) : Math.min(lines.length, start - 1 + MAX_READ_LINES);\n const slice = lines.slice(start - 1, end);\n const numbered = slice.map((l: string, i: number) => `${start + i}\\t${l}`).join(\"\\n\");\n const more = end < lines.length ? `\\n… (${lines.length - end} more lines)` : \"\";\n return numbered + more || \"(empty file)\";\n }\n if (name === \"list_dir\") {\n const dir = input.path ? safePath(root, String(input.path)) : root;",- "span": "L170-L181"+ "span": "L201-L212"}},{@@ -175,15 +181,18 @@"name": "judge.ts","kind": "file","path": "bench/judge.ts",- "span": "L1-L88",+ "span": "L1-L87","signature": null,"exported": true,"origin": "ast",- "body_hash": "94c222341b066e4f3134b3d9d3f30f31b9ffe7b92967086b07c58f297d349936",- "chars": 3076,+ "body_hash": "bb48a8012b929bc0237f4d900d0ab7aa9a98f96777d72a89ce5305c6c57e6c47",+ "chars": 3035,"summary_state": "ready",- "summary": "This file implements a correctness scoring system that evaluates AI-generated answers against a reference answer using keyword checks and an LLM judge.",- "crux": null+ "summary": "This file implements a correctness scoring system that evaluates AI-generated answers against a reference answer, ensuring both keyword requirements and factual accuracy are met.",+ "crux": {+ "code": " * Final correctness = judge says correct AND the keyword floor passed.",+ "span": "L11-L11"+ }},{"id": "bench/judge.ts#extractJson",@@ -207,13 +216,13 @@"name": "judge","kind": "function","path": "bench/judge.ts",- "span": "L51-L87",+ "span": "L51-L86","signature": "async function judge(input: JudgeInput): Promise<Verdict>","exported": true,"origin": "ast",- "body_hash": "98496fb2f15740ca1a47bcfd39f9a44f0b320a2c53d3c21086fdcb8304f88f43",+ "body_hash": "10c2f17e3f861d21e0f4f9750141ca1e4377a7d82cd6c3541a3a9953c64e5eb4","summary_state": "ready",- "summary": "The judge function evaluates an AI agent's answer against a reference answer, returning a Verdict based on keyword presence and LLM scoring.",+ "summary": "Evaluates an AI agent's answer against a reference answer, returning a verdict that indicates correctness based on both a judge's score and keyword requirements.","crux": {"code": " const keywordPass = kw.every((k) => hay.includes(k.toLowerCase()));\n\n const prompt =\n `You are grading an AI agent's answer to a factual question about a codebase/document set. ` +\n `Respond with ONLY a JSON object of the form {\"correct\": boolean, \"score\": number, \"reasoning\": string} ` +\n `where score is 0.0 (wrong/irrelevant) to 1.0 (fully correct and complete). No prose, no code fences.\\n\\n` +\n `Question:\\n${input.question}\\n\\n` +\n `Reference answer (ground truth):\\n${input.referenceAnswer}\\n\\n` +\n `Agent's answer:\\n${input.agentAnswer}\\n\\n` +\n `Grade whether the agent's answer is factually correct and responsive, judged against the reference. ` +\n `Extra correct detail is fine; contradicting the reference or missing the core fact is not.`;\n","span": "L56-L67"@@ -228,9 +237,9 @@"signature": "interface JudgeInput","exported": true,"origin": "ast",- "body_hash": "d22eb2a46b81a9e2f6f55c9f1409b5afc682ab8028ef88f8522a0397dcb1a2bc",+ "body_hash": "f7eabe8d43f6e4f78138ebd0ec6c33add397b86e67c4032370283f0829abaeb5","summary_state": "ready",- "summary": "The JudgeInput interface defines the structure of input data required for the judging process, including the question and answers.",+ "summary": "Defines the structure for input data required to evaluate an AI agent's answer, including the question, reference answer, and required keywords.","crux": null},{@@ -252,31 +261,31 @@"name": "llm.ts","kind": "file","path": "bench/llm.ts",- "span": "L1-L19",+ "span": "L1-L29","signature": null,"exported": true,"origin": "ast",- "body_hash": "6c0d2a02ac6aa86de94f779355020700a4d9016e2f4b431bf75560e1d3c51229",- "chars": 960,+ "body_hash": "6fc86553ce48879cb28b411747fe3ffaa2ad5c269e5de50d83e4ed8b629cae2b",+ "chars": 1187,"summary_state": "ready",- "summary": "This file configures and provides access to the OpenRouter API for benchmarking LLMs without needing separate API keys.",+ "summary": "This file provides a benchmark setup for LLMs, ensuring that the correct models and configurations are used based on environment variables.","crux": null},{- "id": "bench/llm.ts#makeClient",- "name": "makeClient",+ "id": "bench/llm.ts#makeChatModel",+ "name": "makeChatModel","kind": "function","path": "bench/llm.ts",- "span": "L14-L18",- "signature": "function makeClient(): OpenAI",+ "span": "L16-L28",+ "signature": "function makeChatModel(model: string): ChatModel","exported": true,"origin": "ast",- "body_hash": "1de90a5deaf00c7680162630fe437cfc2cc72204aaabf5150922b9b40da021bf",+ "body_hash": "4fdca5065740a7c03ec37acf343949735d86a191cda73c76439fe81ff5123a9e","summary_state": "ready",- "summary": "Creates an OpenAI client instance, ensuring that the necessary API key is provided for operation.",+ "summary": "Creates a chat model instance while enforcing the requirement of a valid API key for the provider.","crux": {- "code": " if (!apiKey) throw new Error(\"OPENROUTER_API_KEY is required (agent + judge run through OpenRouter).\");\n return new OpenAI({ apiKey, baseURL: OPENROUTER_BASE_URL });",- "span": "L16-L17"+ "code": " if (!cfg.apiKey) {\n throw new Error(\"Set GRAFT_API_KEY (or OPENROUTER_API_KEY) — the bench agent + judge need a provider key.\");",+ "span": "L18-L19"}},{@@ -290,9 +299,12 @@"origin": "ast","body_hash": "17c0be550f9712165177d070f58cbe7a0f60fcb2c1dc5830eb1a4dde97ec12f3","chars": 6985,- "summary_state": "stale",- "summary": "This file provides functionality for aggregating and reporting benchmark results for different agent configurations.",- "crux": null+ "summary_state": "ready",+ "summary": "This file aggregates and reports benchmark results for different agent configurations, providing insights into performance metrics.",+ "crux": {+ "code": "/**\n * Aggregation and reporting. Turns the raw per-trial rows into the summary\n * table that is the actual launch deliverable: per corpus, cold vs graph, with\n * the token / latency / correctness deltas that either back the pitch or don't.\n */",+ "span": "L1-L5"+ }},{"id": "bench/report.ts#aggregate",@@ -321,8 +333,8 @@"exported": true,"origin": "ast","body_hash": "4d3e3333d5561c7885e9445936b562e1748016465e14c964652d98acf70b20d4",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the possible execution arms for the benchmarking process, categorizing the types of agent runs.","crux": null},{@@ -349,11 +361,11 @@"exported": true,"origin": "ast","body_hash": "0157ce2adf00bdbf4d01440165deabc0b633ffe5c7db30c55fa19d25bc03d288",- "summary_state": "stale",- "summary": "Generates a markdown report summarizing benchmark results across different corpora and arms.",+ "summary_state": "ready",+ "summary": "Compiles the overall benchmark results into a markdown format for easy readability and presentation.","crux": {- "code": "export function buildMarkdown(rows: Row[]): string {\n const corpora = [...new Set(rows.map((r) => r.corpus))];\n const lines: string[] = [];\n lines.push(\"# Context Graph Engine — Benchmark Results\", \"\");\n lines.push(\n `Agent: Claude Sonnet 5 · Judge: Claude Opus 4.8 · ${rows.length} agent runs total.`,\n \"\",\n \"Each cell is the mean across all tasks × trials for that corpus/arm. \" +\n \"**Cold** = agent explores with filesystem tools from zero. **Graph** = same agent, \" +\n \"same tools, plus the graph context bundle injected up front.\",\n \"\",\n );",- "span": "L80-L91"+ "code": " const corpora = [...new Set(rows.map((r) => r.corpus))];\n const armOrder: Arm[] = [\"cold\", \"graph\", \"pull\"];\n const lines: string[] = [];\n lines.push(\"# graft — Benchmark Results\", \"\");\n lines.push(\n `Agent: Claude Sonnet 5 · Judge: Claude Opus 4.8 · ${rows.length} agent runs total.`,\n \"\",\n \"Each cell is the mean across all tasks × trials for that subset/arm; Δ is vs cold. \" +\n \"**Cold** = agent explores with filesystem tools from zero. **Graph (push)** = same agent, \" +\n \"same tools, plus a `graft ask --source` bundle injected up front. **Graft (pull)** = same \" +\n \"agent plus graft_ask/graft_skeleton tools over the prebuilt graph — nothing injected; \" +\n \"graph context is paid only when the agent asks for it.\",",+ "span": "L130-L141"}},{@@ -411,9 +423,12 @@"exported": false,"origin": "ast","body_hash": "040824ba07e90ba35a7d1b3628412ec72297da5395737d9c1affb2dca8f9e479",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a formatted metric table comparing performance across different agent arms, highlighting key metrics and deltas.",+ "crux": {+ "code": " lines.push(cells(\"Cost / task ($)\", (a) => a.cost, (v) => v.toFixed(4), pctDelta));\n lines.push(cells(\"Uncached input tokens\", (a) => a.tokensInput, fmt, pctDelta));\n lines.push(cells(\"Total tokens (incl. cached)\", (a) => a.tokensTotal, fmt, pctDelta));\n lines.push(cells(\"Output tokens\", (a) => a.tokensOutput, fmt, pctDelta));\n lines.push(cells(\"Tool calls\", (a) => a.toolCalls, fmt, pctDelta));\n lines.push(cells(\"Wall-clock (s)\", (a) => a.wallMs, (v) => (v / 1000).toFixed(1), pctDelta));\n lines.push(cells(\"Correctness\", (a) => a.correctness, (v) => (v * 100).toFixed(0) + \"%\"));",+ "span": "L105-L111"+ }},{"id": "bench/report.ts#metricTable.cells",@@ -425,9 +440,12 @@"exported": false,"origin": "ast","body_hash": "92c5b466f286a53a3ff7de7e5da8b52695f016703252bbf385df554c730f0b5a",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs individual cells for the metric table, calculating values and formatting them for display.",+ "crux": {+ "code": " const cells = (label: string, value: (a: ArmAgg) => number, render: (v: number) => string, delta?: (c: number, x: number) => string) => {\n const out = [label];\n for (const a of arms) {\n const v = value(agg.get(a)!);\n let cell = render(v);\n if (delta && cold && a !== \"cold\") cell += ` (${delta(value(cold), v)})`;\n out.push(cell);\n }\n return `| ${out.join(\" | \")} |`;\n };",+ "span": "L93-L102"+ }},{"id": "bench/report.ts#pctDelta",@@ -456,8 +474,8 @@"exported": true,"origin": "ast","body_hash": "3ec44fbebb1290b68e6b1d52a189eabfb75f43e416384671a174769265610c30",- "summary_state": "stale",- "summary": "Defines the structure of a benchmark trial row, capturing various metrics related to agent performance.",+ "summary_state": "ready",+ "summary": "Represents a single trial's data, encapsulating all relevant metrics for benchmarking an agent's performance.","crux": null},{@@ -470,26 +488,29 @@"exported": false,"origin": "ast","body_hash": "2fb44808117e96d184dcf795bfc7bc9546c05e3d2e0c6b8a888a51c5a8f581ce",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Evaluates and compares the cost and correctness of two agent configurations, providing a verdict on their performance.",+ "crux": {+ "code": " return cheaper && correctnessHeld\n ? `✅ ${label} is cheaper (${pctDelta(c.cost, g.cost)} cost) and correctness held or improved.`\n : !cheaper && g.correctness > c.correctness + 0.001\n ? `➖ ${label} costs more (${pctDelta(c.cost, g.cost)}) but is more correct (+${((g.correctness - c.correctness) * 100).toFixed(0)} pts) — a quality win, not a cost win.`\n : cheaper\n ? `⚠️ ${label} is cheaper but correctness dropped ${((c.correctness - g.correctness) * 100).toFixed(0)} pts — not a clean win.`\n : `❌ ${label} costs more with no correctness gain here.`;",+ "span": "L120-L126"+ }},{"id": "bench/run.ts","name": "run.ts","kind": "file","path": "bench/run.ts",- "span": "L1-L208",+ "span": "L1-L210","signature": null,"exported": true,"origin": "ast",- "body_hash": "0d18dd7823abcef2c286f792e5362f9d51128c35cfaf8ab1892b6d95823c1e10",- "chars": 8716,- "summary_state": "stale",- "summary": "This file orchestrates the benchmarking process for various corpora and tasks, managing the execution and reporting of results.",+ "body_hash": "fd4445eb0d6d3c1a8b994c7e4be42522c3214612a8499e4f76bfc10d0030f9da",+ "chars": 8902,+ "summary_state": "ready",+ "summary": "Orchestrates benchmarking tasks across different configurations and trials, ensuring efficient execution and result collection.","crux": {- "code": " for (const corpus of corpora) {\n const tasks = args.tasks ? corpus.tasks.slice(0, args.tasks) : corpus.tasks;\n console.log(`\\n=== corpus: ${corpus.id} (${corpus.kind}) — ${tasks.length} tasks × ${args.trials} trials ===`);\n\n // Fresh temp-backed engine; ingest once and reuse for the whole corpus.\n const dbDir = mkdtempSync(join(tmpdir(), \"cge-bench-db-\"));\n tmpDbDirs.push(dbDir);\n const engine = new Graft({ dbPath: join(dbDir, \"graph.db\") });\n\n let agentRoot = corpus.path;\n let docsWorkdir: string | undefined;\n",- "span": "L101-L112"+ "code": "async function main() {\n const args = parseArgs(process.argv.slice(2));\n if (!resolveConfig().apiKey) {\n console.error(\"Set GRAFT_API_KEY (or OPENROUTER_API_KEY) — the agent and judge need a provider key.\");\n process.exit(1);\n }\n const agentModel = makeChatModel(AGENT_MODEL);\n const judgeModel = makeChatModel(JUDGE_MODEL);\n\n const corpora = CORPORA.filter((c) => !args.corpora || args.corpora.includes(c.id));\n if (corpora.length === 0) {\n console.error(`No matching corpora. Available: ${CORPORA.map((c) => c.id).join(\", \")}`);",+ "span": "L83-L94"}},{@@ -497,13 +518,13 @@"name": "Args","kind": "interface","path": "bench/run.ts",- "span": "L38-L44",+ "span": "L39-L45","signature": "interface Args","exported": false,"origin": "ast","body_hash": "081f4c21818443a203a267bb039fb7209a50acf6b714b402af2d010f5c64d06a",- "summary_state": "stale",- "summary": "Defines the structure for command-line arguments used to configure the benchmarking run.",+ "summary_state": "ready",+ "summary": "Defines the structure for command-line arguments to configure the benchmarking process.","crux": null},{@@ -511,16 +532,16 @@"name": "main","kind": "function","path": "bench/run.ts",- "span": "L82-L202",+ "span": "L83-L204","signature": "async function main()","exported": false,"origin": "ast",- "body_hash": "e32e4119f57a31a4f26eb2a0fe5e85e9dc67a607732dc49a21adef2d9f076652",- "summary_state": "stale",- "summary": "Coordinates the overall benchmarking process, including argument parsing, corpus ingestion, and result reporting.",+ "body_hash": "83b0f4f7fa6b94e59c780554192a56982741682e8457195ca287a88ed9515f96",+ "summary_state": "ready",+ "summary": "Coordinates the overall benchmarking process, including argument parsing, corpus handling, and result generation.","crux": {- "code": "async function main() {\n const args = parseArgs(process.argv.slice(2));\n if (!process.env.OPENROUTER_API_KEY) {\n console.error(\"Set OPENROUTER_API_KEY (agent, judge, and graph extraction all run through OpenRouter).\");\n process.exit(1);\n }\n const client = makeClient();\n\n const corpora = CORPORA.filter((c) => !args.corpora || args.corpora.includes(c.id));\n if (corpora.length === 0) {\n console.error(`No matching corpora. Available: ${CORPORA.map((c) => c.id).join(\", \")}`);\n process.exit(1);",- "span": "L84-L95"+ "code": " let done = 0;\n const total = units.length;\n const corpusRows = await pool(units, args.concurrency, async ({ task, arm, trial }) => {\n const base = {\n corpus: corpus.id, taskId: task.id, arm, trial,\n locality: task.locality ?? \"multi-file\",\n };\n try {\n const ar = await runAgent({\n model: agentModel,\n root: corpus.path,\n question: task.question,",+ "span": "L138-L149"}},{@@ -528,16 +549,16 @@"name": "parseArgs","kind": "function","path": "bench/run.ts",- "span": "L46-L66",+ "span": "L47-L67","signature": "function parseArgs(argv: string[]): Args","exported": false,"origin": "ast","body_hash": "d3862150543501db4a56837578adde9a777203260b8e1c1d7f022615973e0c54",- "summary_state": "stale",- "summary": "Parses command-line arguments to extract configuration options for the benchmarking process.",+ "summary_state": "ready",+ "summary": "Parses command-line arguments to set up the benchmarking configuration, ensuring valid options are provided.","crux": {- "code": " const a: Args = { trials: 3, arms: [\"cold\", \"graph\"], concurrency: 6 };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--smoke\") {\n a.corpora = [\"unified-accounts-login-server\"]; // smallest corpus — cheapest plumbing check\n a.tasks = 1;\n a.trials = 1;\n } else if (arg === \"--corpora\" || arg === \"--repos\") a.corpora = argv[++i].split(\",\");\n else if (arg === \"--tasks\") a.tasks = Number(argv[++i]);\n else if (arg === \"--trials\") a.trials = Number(argv[++i]);\n else if (arg === \"--arms\") a.arms = argv[++i].split(\",\") as Array<\"cold\" | \"graph\">;\n else if (arg === \"--concurrency\") a.concurrency = Math.max(1, Number(argv[++i]));",- "span": "L38-L49"+ "code": " const bad = a.arms.filter((x) => !ALL_ARMS.includes(x));\n if (bad.length) {\n console.error(`Unknown arm(s): ${bad.join(\", \")}. Valid: ${ALL_ARMS.join(\", \")}`);\n process.exit(1);\n }\n return a;",+ "span": "L61-L66"}},{@@ -545,7 +566,7 @@"name": "pool","kind": "function","path": "bench/run.ts",- "span": "L69-L80",+ "span": "L70-L81","signature": "async function pool<T, R>(items: T[], n: number, fn: (item: T) => Promise<R>): Promise<R[]>","exported": false,"origin": "ast",@@ -562,7 +583,7 @@"name": "worker","kind": "function","path": "bench/run.ts",- "span": "L72-L77",+ "span": "L73-L78","signature": "async function worker()","exported": false,"origin": "ast",@@ -579,17 +600,17 @@"name": "selfcheck.ts","kind": "file","path": "bench/selfcheck.ts",- "span": "L1-L120",+ "span": "L1-L111","signature": null,"exported": true,"origin": "ast",- "body_hash": "48c97e7ce8b4e7544ec29c2341d1946b75f5b4ac3b2fef414e9f170da6a90fe6",- "chars": 5284,- "summary_state": "stale",- "summary": "This file performs an offline verification of the harness plumbing to ensure control flow works correctly without needing an API key.",+ "body_hash": "858ec7cce92c9105c4e111ae58f1d1a1b1b57372b96768804308009760c9b2f6",+ "chars": 5108,+ "summary_state": "ready",+ "summary": "This file provides an offline verification mechanism for the harness plumbing, ensuring control flow integrity without requiring an API key.","crux": {- "code": "async function main() {\n const root = mkdtempSync(join(tmpdir(), \"cge-selfcheck-\"));\n mkdirSync(join(root, \"src\"), { recursive: true });\n writeFileSync(join(root, \"src\", \"config.ts\"), \"export const token = 'SECRET_TOKEN';\\n\");\n\n const client = makeStubClient();\n\n // 1. Agent loop: should call the grep tool once, then answer.\n const ar = await runAgent({ client, root, question: \"What is the secret token?\" });\n assert.equal(ar.toolCalls, 1, \"expected exactly one tool call\");\n assert.equal(ar.toolLog[0].name, \"grep\", \"expected the grep tool to run\");\n assert.ok(ar.answer.includes(\"SECRET_TOKEN\"), \"answer should contain the fact\");",- "span": "L50-L61"+ "code": "import { mkdtempSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";",+ "span": "L8-L10"}},{@@ -597,32 +618,49 @@"name": "main","kind": "function","path": "bench/selfcheck.ts",- "span": "L50-L114",+ "span": "L41-L105","signature": "async function main()","exported": false,"origin": "ast",- "body_hash": "a36d5aba69d3177e8d2c6eaf9ebdb5d9b03f98356a323e20a99cea25553b4ac4",- "summary_state": "stale",- "summary": "Coordinates the self-check process by setting up a temporary environment, running the agent, and validating the results.",+ "body_hash": "540f18c9d742ad482342877ba58e677f03c119e371af1acb71cb0ffd5e9b3000",+ "summary_state": "ready",+ "summary": "Coordinates the self-check process by setting up the environment, running the agent, and validating the results through assertions.","crux": {- "code": " const ar = await runAgent({ client, root, question: \"What is the secret token?\" });\n assert.equal(ar.toolCalls, 1, \"expected exactly one tool call\");\n assert.equal(ar.toolLog[0].name, \"grep\", \"expected the grep tool to run\");\n assert.ok(ar.answer.includes(\"SECRET_TOKEN\"), \"answer should contain the fact\");\n assert.equal(ar.tokens.total, 300, \"tokens should sum across 2 turns (150 each)\");\n assert.equal(ar.stopReason, \"stop\");\n console.log(`✓ agent loop: ${ar.toolCalls} tool call, ${ar.tokens.total} tokens, answer=\"${ar.answer}\"`);",- "span": "L58-L64"+ "code": " // 1. Agent loop: should call the grep tool once, then answer.\n const ar = await runAgent({ model, root, question: \"What is the secret token?\" });\n assert.equal(ar.toolCalls, 1, \"expected exactly one tool call\");\n assert.equal(ar.toolLog[0].name, \"grep\", \"expected the grep tool to run\");\n assert.ok(ar.answer.includes(\"SECRET_TOKEN\"), \"answer should contain the fact\");\n assert.equal(ar.tokens.total, 300, \"tokens should sum across 2 turns (150 each)\");\n assert.equal(ar.stopReason, \"stop\");\n console.log(`✓ agent loop: ${ar.toolCalls} tool call, ${ar.tokens.total} tokens, answer=\"${ar.answer}\"`);\n\n // 2. Real tool execution actually found the file (grep ran against the temp repo).\n const graphAr = await runAgent({\n model: makeStubModel(),",+ "span": "L48-L59"}},{- "id": "bench/selfcheck.ts#makeStubClient",- "name": "makeStubClient",+ "id": "bench/selfcheck.ts#makeStubModel",+ "name": "makeStubModel","kind": "function","path": "bench/selfcheck.ts",- "span": "L19-L48",- "signature": "function makeStubClient()",+ "span": "L20-L39",+ "signature": "function makeStubModel(): ChatModel",+ "exported": false,+ "origin": "ast",+ "body_hash": "bb35f851e0d597751b735bdb44d0ae399bb408825c1c4f2ec8d3d04036d0ff82",+ "summary_state": "ready",+ "summary": "Creates a stubbed ChatModel that simulates agent behavior for testing purposes, allowing for controlled responses during the agent loop.",+ "crux": {+ "code": " if (req.responseFormat?.kind === \"json\") {\n const text = JSON.stringify({ correct: true, score: 0.9, reasoning: \"matches reference\" });\n return { text, toolCalls: [], usage, stopReason: \"stop\", assistant: { role: \"assistant\", content: text } };\n }\n // Agent call. First turn: use grep. Second turn: final answer.\n agentTurn++;\n if (agentTurn === 1) {\n const toolCalls = [{ id: \"tc_1\", name: \"grep\", args: { pattern: \"SECRET_TOKEN\" } }];\n return { text: \"\", toolCalls, usage, stopReason: \"tool_use\", assistant: { role: \"assistant\", content: \"\", toolCalls } };\n }\n const text = \"The secret token is SECRET_TOKEN, defined in config.ts.\";\n return { text, toolCalls: [], usage, stopReason: \"stop\", assistant: { role: \"assistant\", content: text } };",+ "span": "L25-L36"+ }+ },+ {+ "id": "bench/selfcheck.ts#makeStubModel.create",+ "name": "create",+ "kind": "method",+ "path": "bench/selfcheck.ts",+ "span": "L24-L37",+ "signature": "async create(req)","exported": false,"origin": "ast",- "body_hash": "3ac524103f28630ba8f080c62707872e56d513b46b57b6753cb07c8c6c44f249",+ "body_hash": "2e264ef92e35b9b98b80692d5b985c140e453d412ad8111166c0c3a7d9f15ee1","summary_state": "ready",- "summary": "Creates a stub client that simulates responses for agent and judge interactions during testing.",+ "summary": "Handles requests by returning predefined responses based on the request format, simulating the agent's decision-making process.","crux": {- "code": " if (params.response_format) {\n // Judge call → JSON verdict.\n return {\n choices: [{ message: { role: \"assistant\", content: JSON.stringify({ correct: true, score: 0.9, reasoning: \"matches reference\" }) }, finish_reason: \"stop\" }],\n usage,\n };\n }\n // Agent call. First turn: use grep. Second turn: final answer.\n agentTurn++;\n if (agentTurn === 1) {\n return {\n choices: [{ message: { role: \"assistant\", content: null, tool_calls: [{ id: \"tc_1\", type: \"function\", function: { name: \"grep\", arguments: JSON.stringify({ pattern: \"SECRET_TOKEN\" }) } }] }, finish_reason: \"tool_calls\" }],",+ "code": " if (req.responseFormat?.kind === \"json\") {\n const text = JSON.stringify({ correct: true, score: 0.9, reasoning: \"matches reference\" });\n return { text, toolCalls: [], usage, stopReason: \"stop\", assistant: { role: \"assistant\", content: text } };\n }\n // Agent call. First turn: use grep. Second turn: final answer.\n agentTurn++;\n if (agentTurn === 1) {\n const toolCalls = [{ id: \"tc_1\", name: \"grep\", args: { pattern: \"SECRET_TOKEN\" } }];\n return { text: \"\", toolCalls, usage, stopReason: \"tool_use\", assistant: { role: \"assistant\", content: \"\", toolCalls } };\n }\n const text = \"The secret token is SECRET_TOKEN, defined in config.ts.\";\n return { text, toolCalls: [], usage, stopReason: \"stop\", assistant: { role: \"assistant\", content: text } };","span": "L25-L36"}},@@ -637,11 +675,11 @@"origin": "ast","body_hash": "efb90e69f52adcb08bfe45fb5a983fc676df68befdc455513e2581a24f46807e","chars": 18806,- "summary_state": "stale",- "summary": "This file defines benchmark tasks and their corresponding reference answers for validating code understanding across multiple repositories.",+ "summary_state": "ready",+ "summary": "This file defines benchmark tasks and their associated metadata to ensure verifiable answers for codebase questions.","crux": {- "code": "/** Sibling repo path by default; overridable via BENCH_REPO_<ID_UPPER> (dashes → underscores). */\nfunction repoPath(id: string): string {\n const envKey = \"BENCH_REPO_\" + id.toUpperCase().replace(/-/g, \"_\");\n return process.env[envKey] ?? resolve(parent, id);\n}\n\nexport interface Task {\n id: string;\n question: string;\n referenceAnswer: string;\n /** Case-insensitive substrings the answer must contain (deterministic floor). */\n requiredKeywords: string[];",- "span": "L25-L36"+ "code": "/**\n * The benchmark corpus and task set. This file *is* the benchmark's validity:\n * every task must have a verifiable answer, grounded in the actual source\n * (cited during authoring), not guessed. Tasks carry a `locality` label so the\n * report can split the verdict: multi-file questions are where graph context\n * should help; localized single-file questions are where it is expected to be\n * net overhead — the bench must measure both, not select for the winner.\n *\n * Corpora: graft's own repo (context-engine — always present, self-contained),\n * plus real external repos expected as siblings of this one under the same\n * parent directory (override a path with BENCH_REPO_<ID_UPPER> if needed):\n * - unified-accounts-login-server — the Nanonets unified auth service (Node/Express).",+ "span": "L1-L12"}},{@@ -685,150 +723,183 @@"exported": true,"origin": "ast","body_hash": "5f5e2039755acb77b6a0f6a14f752ef11da6c3b9a3fb124fda4f0fc871246304",- "summary_state": "stale",- "summary": "This interface outlines the structure of a benchmark task, including its ID, question, reference answer, and required keywords.",- "crux": null+ "summary_state": "ready",+ "summary": "The Task interface structures the data for individual benchmark questions, ensuring they include necessary details for validation.",+ "crux": {+ "code": "export interface Task {\n id: string;\n question: string;\n referenceAnswer: string;\n /** Case-insensitive substrings the answer must contain (deterministic floor). */\n requiredKeywords: string[];\n /** \"localized\" = answerable from one file (where graph context is expected to\n * be net overhead — the hono-bench finding this bench must reproduce, not\n * hide). Absent = \"multi-file\", the shape the original corpus was limited to. */\n locality?: \"localized\" | \"multi-file\";\n}",+ "span": "L35-L45"+ }},{"id": "bench/token-ab.ts","name": "token-ab.ts","kind": "file","path": "bench/token-ab.ts",- "span": "L1-L298",+ "span": "L1-L279","signature": null,"exported": true,"origin": "ast",- "body_hash": "95a6cebca2a72bb8d1dff205392380b8e5ac7da123f9ea8802a3e048b80ea03c",- "chars": 11961,- "summary_state": "pending",- "summary": null,- "crux": null+ "body_hash": "b033a023d063cccc329103fbd11d4e1a6ab16c5eb027e1dd85c47a63a7df4ff1",+ "chars": 11343,+ "summary_state": "ready",+ "summary": "This script benchmarks the performance of an agent using two different approaches (COLD and GRAFT) to determine if providing pre-computed context saves tokens during code exploration.",+ "crux": {+ "code": " console.log(\"→ generating graft pack (graft ask --source)…\");\n const { pack, ms: graftMs } = graftPack();\n const packTokEst = Math.round(pack.length / 4); // rough: ~4 chars/token\n console.log(` pack: ${pack.length} chars (~${packTokEst} tok), produced in ${graftMs}ms ($0, local)\\n`);\n\n console.log(\"→ running COLD arm (agent explores the repo itself)…\");\n const cold = await runAgent(\"COLD\", null);\n console.log(` done in ${cold.ms}ms, ${cold.llmCalls} LLM calls\\n`);\n\n console.log(\"→ running GRAFT arm (agent handed the pack up front)…\");\n const graft = await runAgent(\"GRAFT\", pack);\n console.log(` done in ${graft.ms}ms, ${graft.llmCalls} LLM calls\\n`);",+ "span": "L238-L249"+ }},{"id": "bench/token-ab.ts#cost","name": "cost","kind": "function","path": "bench/token-ab.ts",- "span": "L242-L246",+ "span": "L223-L227","signature": "function cost(m: Metrics): string","exported": false,"origin": "ast","body_hash": "f59a853dd420d918b63ac37c796298e8049f644b1c500928290d0fa095245818",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the estimated cost of the agent's operations based on token usage and pricing configuration.",+ "crux": {+ "code": "function cost(m: Metrics): string {\n if (!CONFIG.PRICE_IN_PER_M && !CONFIG.PRICE_OUT_PER_M) return \"—\";\n const c = (m.promptTokens / 1e6) * CONFIG.PRICE_IN_PER_M + (m.completionTokens / 1e6) * CONFIG.PRICE_OUT_PER_M;\n return \"$\" + c.toFixed(4);\n}",+ "span": "L223-L227"+ }},{"id": "bench/token-ab.ts#graftPack","name": "graftPack","kind": "function","path": "bench/token-ab.ts",- "span": "L229-L240",+ "span": "L210-L221","signature": "function graftPack(): { pack: string; ms: number }","exported": false,"origin": "ast","body_hash": "89a547d4352e3d9dbdb8c04f2a91fc04be812e2a0eb44165ee58e2df0f5f4bdf",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a context pack using the graft tool to provide pre-computed information for the agent.",+ "crux": {+ "code": "function graftPack(): { pack: string; ms: number } {\n const t0 = Date.now();\n if (!existsSync(resolve(CONFIG.REPO, \"graft\"))) {\n console.error(`✗ no graft/ index in ${CONFIG.REPO}. Run: cd ${CONFIG.REPO} && graft build`);\n process.exit(1);\n }\n const pack = execFileSync(\"graft\", [\"ask\", CONFIG.QUESTION, CONFIG.REPO, \"--source\"], {\n encoding: \"utf8\",\n maxBuffer: 16 << 20,\n });\n return { pack, ms: Date.now() - t0 };",+ "span": "L210-L220"+ }},{"id": "bench/token-ab.ts#main","name": "main","kind": "function","path": "bench/token-ab.ts",- "span": "L252-L292",+ "span": "L233-L273","signature": "async function main()","exported": false,"origin": "ast","body_hash": "7e15d43e2c0c022b333db8c2727e7eb184209faff2799a4e8f381a8840072c70",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Coordinates the overall execution of the A/B test, including generating the graft pack and running both agent arms.",+ "crux": {+ "code": "async function main() {\n console.log(`\\nREPO: ${CONFIG.REPO}`);\n console.log(`MODEL: ${CONFIG.MODEL}`);\n console.log(`QUESTION: ${CONFIG.QUESTION.slice(0, 100)}…\\n`);\n\n console.log(\"→ generating graft pack (graft ask --source)…\");\n const { pack, ms: graftMs } = graftPack();\n const packTokEst = Math.round(pack.length / 4); // rough: ~4 chars/token\n console.log(` pack: ${pack.length} chars (~${packTokEst} tok), produced in ${graftMs}ms ($0, local)\\n`);\n\n console.log(\"→ running COLD arm (agent explores the repo itself)…\");\n const cold = await runAgent(\"COLD\", null);",+ "span": "L233-L244"+ }},{"id": "bench/token-ab.ts#main.pct","name": "pct","kind": "function","path": "bench/token-ab.ts",- "span": "L272-L272",+ "span": "L253-L253","signature": "pct = (a: number, b: number)","exported": false,"origin": "ast","body_hash": "a696c500df6bf30f9d1c99fa5c77b12fd6b41d1441dcea77cb160f1ce867e1d3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the percentage improvement in token usage between the COLD and GRAFT arms.",+ "crux": {+ "code": " const pct = (a: number, b: number) => (a === 0 ? \"—\" : `${Math.round((1 - b / a) * 100)}%`);",+ "span": "L253-L253"+ }},{"id": "bench/token-ab.ts#Metrics","name": "Metrics","kind": "interface","path": "bench/token-ab.ts",- "span": "L59-L68",+ "span": "L55-L64","signature": "interface Metrics","exported": false,"origin": "ast","body_hash": "4987dcdcf1ce8f9588ca811ca9c4c77d37368a043e39415784c9fde7dcff35d9",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for capturing metrics related to the A/B testing of the agent's performance.",+ "crux": {+ "code": "interface Metrics {\n arm: string;\n llmCalls: number;\n promptTokens: number;\n completionTokens: number;\n toolCalls: number;\n filesRead: Set<string>;\n ms: number;\n answer: string;\n}",+ "span": "L55-L64"+ }},{"id": "bench/token-ab.ts#row","name": "row","kind": "function","path": "bench/token-ab.ts",- "span": "L248-L250",+ "span": "L229-L231","signature": "function row(label: string, a: string | number, b: string | number): string","exported": false,"origin": "ast","body_hash": "b30daa5cdce52d4742bfca9c507fa0e60e335fdf6b67081f373a7e45f29ca92f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a row of metrics for display in the output table comparing the COLD and GRAFT arms.",+ "crux": {+ "code": "function row(label: string, a: string | number, b: string | number): string {\n return `${label.padEnd(22)} ${String(a).padStart(14)} ${String(b).padStart(14)}`;\n}",+ "span": "L229-L231"+ }},{"id": "bench/token-ab.ts#runAgent","name": "runAgent","kind": "function","path": "bench/token-ab.ts",- "span": "L160-L226",+ "span": "L150-L207","signature": "async function runAgent(arm: string, extraContext: string | null): Promise<Metrics>","exported": false,"origin": "ast",- "body_hash": "00a26ff79d6edc7f2dbe2b394bf6370820c026a752b373cae257f32315a7f5b0",- "summary_state": "pending",- "summary": null,- "crux": null+ "body_hash": "10a292dc1b6275704d3e2409727df72702970ae7296002f153f2157ba1fe85a8",+ "summary_state": "ready",+ "summary": "Manages the agent's execution loop, handling user queries and tool calls while tracking performance metrics.",+ "crux": {+ "code": "async function runAgent(arm: string, extraContext: string | null): Promise<Metrics> {\n const m: Metrics = {\n arm, llmCalls: 0, promptTokens: 0, completionTokens: 0, toolCalls: 0,\n filesRead: new Set(), ms: 0, answer: \"\",\n };\n const t0 = Date.now();\n\n const userParts = [`QUESTION:\\n${CONFIG.QUESTION}`];\n if (extraContext) {\n userParts.push(\n \"\\nYou have been given a pre-computed context pack from a code-graph tool below. \" +\n \"Prefer it; only use the search/read_file tools if it is genuinely insufficient.\\n\\n\" +",+ "span": "L150-L161"+ }},{"id": "bench/token-ab.ts#runRead","name": "runRead","kind": "function","path": "bench/token-ab.ts",- "span": "L140-L157",+ "span": "L130-L147","signature": "function runRead(path: string, start?: number, end?: number): { text: string; resolved: string }","exported": false,"origin": "ast","body_hash": "79923e547c1f135e88cdda255eeffeb2faa75a5fc81be8703694c8eb45a090af",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reads a specified source file or a range of lines from it, ensuring it is within the repository's bounds.",+ "crux": {+ "code": "function runRead(path: string, start?: number, end?: number): { text: string; resolved: string } {\n const abs = isAbsolute(path) ? resolve(path) : resolve(CONFIG.REPO, path);\n const rel = relative(CONFIG.REPO, abs);\n if (rel.startsWith(\"..\") || isAbsolute(rel)) return { text: `(refused: ${path} is outside the repo)`, resolved: rel };\n if (!existsSync(abs)) return { text: `(not found: ${rel})`, resolved: rel };\n let content = readFileSync(abs, \"utf8\");\n const allLines = content.split(\"\\n\");\n let lines = allLines;\n if (start || end) {\n const s = Math.max(1, start ?? 1);\n const e = Math.min(allLines.length, end ?? allLines.length);\n lines = allLines.slice(s - 1, e).map((l, i) => `${s + i}\\t${l}`);",+ "span": "L130-L141"+ }},{"id": "bench/token-ab.ts#runSearch","name": "runSearch","kind": "function","path": "bench/token-ab.ts",- "span": "L108-L138",+ "span": "L98-L128","signature": "function runSearch(pattern: string): string","exported": false,"origin": "ast","body_hash": "52208dc37e9ca679f7d182cfbb80de09e29cc2aa62bd0128bcd7c7c72c6747ea",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes a regex search across the repository to find relevant code snippets based on a given pattern.",+ "crux": {+ "code": " const args = [\n \"--no-heading\", \"-n\", \"-S\", \"--max-count\", \"40\",\n \"-g\", \"*.ts\", \"-g\", \"*.tsx\", \"-g\", \"!node_modules\",\n pattern, CONFIG.REPO,\n ];\n let out = \"\";\n try {\n out = execFileSync(\"rg\", args, { encoding: \"utf8\", maxBuffer: 8 << 20 });\n } catch (e: any) {\n // rg exits 1 on \"no matches\"; also handle rg-not-installed by falling back to grep.\n if (e?.code === \"ENOENT\") {\n try {",+ "span": "L99-L110"+ }},{"id": "scripts/build-viewer.mjs",@@ -859,26 +930,80 @@"origin": "ast","body_hash": "2836cb69bc03453bc22abcae91d58de0a06881ee7f975fe86967aedf5d2d6188","chars": 529,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This script provides a non-intrusive notification after installation, ensuring the install process is not interrupted by errors.",+ "crux": {+ "code": " console.log('\\n Graft installed. Run `npx graft init` to enable the Claude Code integration (statusline + hooks + auto-sync).\\n');",+ "span": "L8-L8"+ }},{"id": "src/ai/crux.ts","name": "crux.ts","kind": "file","path": "src/ai/crux.ts",- "span": "L1-L128",+ "span": "L1-L141","signature": null,"exported": true,"origin": "ast",- "body_hash": "e81750029e4c8641cdaf2b4894f595297839e07a73076e4cdac1522515f923a8",- "chars": 5223,+ "body_hash": "81323b622400aadae1fd584ea09c2016ccf1bf4f14654b648ee50b1b13bd4c68",+ "chars": 5437,"summary_state": "ready",- "summary": "This file provides a mechanism to summarize code definitions for better navigation and understanding of a codebase.",+ "summary": "This file defines a system for summarizing code definitions to aid engineers in navigating a codebase.","crux": {- "code": "const SYSTEM_PROMPT = `You explain code definitions for a code graph that helps engineers navigate a codebase.\n\nYou are given ONE source file with 1-based line numbers, and a list of TARGET definitions in it. For every target, return its purpose and the line range of its core logic.\n\nReturn STRICT JSON, exactly:\n{ \"symbols\": [ { \"id\": string, \"summary\": string, \"crux_start\": number, \"crux_end\": number }, ... ] }\n\nRules:\n- Emit exactly one entry per target id given, using that id verbatim.\n- summary: ONE sentence — what the symbol is FOR at the business-logic level. Say what problem it solves or rule it enforces, not what its signature already says.\n- crux_start / crux_end: FILE line numbers (as shown), inside that symbol's own line range. Pick the SINGLE most important contiguous span — the core branch, formula, guard, or state change. Keep it TIGHT: at most ~8 lines, and NEVER the whole function. If you can't narrow it below that, the symbol has no distinct crux — use 0/0.\n- Skip boilerplate, logging, and plumbing. If a symbol has no meaningful crux (trivial getter, data holder, one-line delegation, or logic spread evenly with no focal point), use \"crux_start\": 0 and \"crux_end\": 0.",- "span": "L46-L57"+ "code": "const SYSTEM_PROMPT = `You explain code definitions for a code graph that helps engineers navigate a codebase.\n\nYou are given ONE source file with 1-based line numbers, and a list of TARGET definitions in it. For every target, record its purpose and the line range of its core logic via the record_symbols tool.\n\nRules:\n- Emit exactly one entry per target id given, using that id verbatim.\n- summary: ONE sentence — what the symbol is FOR at the business-logic level. Say what problem it solves or rule it enforces, not what its signature already says.\n- crux_start / crux_end: FILE line numbers (as shown), inside that symbol's own line range. Pick the SINGLE most important contiguous span — the core branch, formula, guard, or state change. Keep it TIGHT: at most ~8 lines, and NEVER the whole function. If you can't narrow it below that, the symbol has no distinct crux — use 0/0.\n- Skip boilerplate, logging, and plumbing. If a symbol has no meaningful crux (trivial getter, data holder, one-line delegation, or logic spread evenly with no focal point), use \"crux_start\": 0 and \"crux_end\": 0.`;\n\nconst RECORD_TOOL = \"record_symbols\";",+ "span": "L46-L56"+ }+ },+ {+ "id": "src/ai/crux.ts#ChatCruxSummarizer",+ "name": "ChatCruxSummarizer",+ "kind": "class",+ "path": "src/ai/crux.ts",+ "span": "L117-L140",+ "signature": "class ChatCruxSummarizer implements CruxSummarizer",+ "exported": true,+ "origin": "ast",+ "body_hash": "322c43e3735b8c1d84abf6b6e0595a71115f667b6081967f25944d639d8ada41",+ "summary_state": "ready",+ "summary": "Implements a summarizer that utilizes a ChatModel to describe code definitions and their purposes in a file.",+ "crux": {+ "code": " async describeFile(input: FileCruxInput): Promise<NodeCrux[]> {\n if (input.nodes.length === 0) return [];\n const res = await this.model.create({\n temperature: 0,\n maxTokens: 8192,\n tools: [\n {\n name: RECORD_TOOL,\n description: \"Record each target definition's purpose and crux line range.\",\n parameters: SYMBOLS_SCHEMA as unknown as Record<string, unknown>,\n },\n ],",+ "span": "L120-L131"+ }+ },+ {+ "id": "src/ai/crux.ts#ChatCruxSummarizer.constructor",+ "name": "constructor",+ "kind": "method",+ "path": "src/ai/crux.ts",+ "span": "L118-L118",+ "signature": "constructor(private model: ChatModel)",+ "exported": true,+ "origin": "ast",+ "body_hash": "01e4b6b8ac3b764e704374f04305b7acdbdfdbf0302ee7b56376849f61358ddb",+ "summary_state": "ready",+ "summary": "Initializes the ChatCruxSummarizer with a specific ChatModel instance for generating summaries.",+ "crux": {+ "code": " constructor(private model: ChatModel) {}",+ "span": "L118-L118"+ }+ },+ {+ "id": "src/ai/crux.ts#ChatCruxSummarizer.describeFile",+ "name": "describeFile",+ "kind": "method",+ "path": "src/ai/crux.ts",+ "span": "L120-L139",+ "signature": "async describeFile(input: FileCruxInput): Promise<NodeCrux[]>",+ "exported": true,+ "origin": "ast",+ "body_hash": "de411bd9d9bd6ad2f065084e2d259b91ae24a9adc01662fa30ef1c6a95cba148",+ "summary_state": "ready",+ "summary": "Processes a file input to generate summaries of its target definitions using the ChatModel.",+ "crux": {+ "code": " if (input.nodes.length === 0) return [];\n const res = await this.model.create({\n temperature: 0,\n maxTokens: 8192,\n tools: [\n {\n name: RECORD_TOOL,\n description: \"Record each target definition's purpose and crux line range.\",\n parameters: SYMBOLS_SCHEMA as unknown as Record<string, unknown>,\n },\n ],\n responseFormat: { kind: \"tool\", name: RECORD_TOOL },",+ "span": "L121-L132"}},{@@ -954,7 +1079,7 @@"name": "numberLines","kind": "function","path": "src/ai/crux.ts",- "span": "L63-L70",+ "span": "L81-L88","signature": "function numberLines(source: string): string","exported": false,"origin": "ast",@@ -966,72 +1091,21 @@"span": "L63-L70"}},- {- "id": "src/ai/crux.ts#OpenRouterCruxSummarizer",- "name": "OpenRouterCruxSummarizer",- "kind": "class",- "path": "src/ai/crux.ts",- "span": "L101-L127",- "signature": "class OpenRouterCruxSummarizer implements CruxSummarizer",- "exported": true,- "origin": "ast",- "body_hash": "20704346ba50c09895e6a19c3574156db46df9e20baa6286bf1bf6a479c2650b",- "summary_state": "ready",- "summary": "Implements the CruxSummarizer interface using OpenAI's chat API for summarization.",- "crux": {- "code": "export class OpenRouterCruxSummarizer implements CruxSummarizer {\n private client: OpenAI;\n private model: string;\n\n constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\") {\n this.client = new OpenAI({\n apiKey,\n baseURL: baseUrl,\n defaultHeaders: { \"X-Title\": \"Context Graph Engine\" },\n });\n this.model = model;\n }",- "span": "L101-L112"- }- },- {- "id": "src/ai/crux.ts#OpenRouterCruxSummarizer.constructor",- "name": "constructor",- "kind": "method",- "path": "src/ai/crux.ts",- "span": "L105-L112",- "signature": "constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\")",- "exported": true,- "origin": "ast",- "body_hash": "11789569c2566d5187db773c70ebb755e57415aafb4b2d35fd3473dfdfda4958",- "summary_state": "ready",- "summary": "Initializes the OpenRouterCruxSummarizer with API key and model.",- "crux": {- "code": " constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\") {\n this.client = new OpenAI({\n apiKey,\n baseURL: baseUrl,\n defaultHeaders: { \"X-Title\": \"Context Graph Engine\" },\n });\n this.model = model;\n }",- "span": "L105-L112"- }- },- {- "id": "src/ai/crux.ts#OpenRouterCruxSummarizer.describeFile",- "name": "describeFile",- "kind": "method",- "path": "src/ai/crux.ts",- "span": "L114-L126",- "signature": "async describeFile(input: FileCruxInput): Promise<NodeCrux[]>",- "exported": true,- "origin": "ast",- "body_hash": "f9db855cb28cb76a21cabb928924cf83d145fc206bce5c340d4615c260653e18",- "summary_state": "ready",- "summary": "Generates summaries for the code definitions in a given file.",- "crux": {- "code": " async describeFile(input: FileCruxInput): Promise<NodeCrux[]> {\n if (input.nodes.length === 0) return [];\n const response = await this.client.chat.completions.create({\n model: this.model,\n temperature: 0,\n response_format: { type: \"json_object\" },\n messages: [\n { role: \"system\", content: SYSTEM_PROMPT },\n { role: \"user\", content: userContent(input) },\n ],\n });\n return parseResults(response.choices[0]?.message?.content ?? \"\");",- "span": "L114-L125"- }- },{"id": "src/ai/crux.ts#parseResults","name": "parseResults","kind": "function","path": "src/ai/crux.ts",- "span": "L84-L98",- "signature": "function parseResults(raw: string): NodeCrux[]",+ "span": "L102-L114",+ "signature": "function parseResults(obj: { symbols?: unknown } | undefined): NodeCrux[]","exported": false,"origin": "ast",- "body_hash": "91399ce86a0308307952e61ac203bef3df08f912fe4bfdab3ef7260ae6830da1",+ "body_hash": "2e56a71c55e7d782e45421811cd9f7efbfcfea990d623f5595e0d2a79b8e41a2","summary_state": "ready",- "summary": "Parses the JSON response from the summarization model into a usable format.",+ "summary": "Transforms the tool's parsed argument object into a structured list of NodeCrux objects for further processing.","crux": {- "code": "function parseResults(raw: string): NodeCrux[] {\n const text = raw.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n const obj = JSON.parse(text) as { symbols?: unknown };\n if (!Array.isArray(obj.symbols)) return [];\n const num = (v: unknown) => (typeof v === \"number\" && Number.isFinite(v) ? Math.trunc(v) : 0);\n return obj.symbols\n .map((s) => s as Record<string, unknown>)\n .filter((s) => typeof s.id === \"string\")\n .map((s) => ({\n id: s.id as string,\n summary: typeof s.summary === \"string\" ? s.summary.trim() : \"\",\n crux_start: num(s.crux_start),",- "span": "L84-L95"+ "code": " .map((s) => s as Record<string, unknown>)\n .filter((s) => typeof s.id === \"string\")\n .map((s) => ({\n id: s.id as string,\n summary: typeof s.summary === \"string\" ? s.summary.trim() : \"\",\n crux_start: num(s.crux_start),\n crux_end: num(s.crux_end),",+ "span": "L106-L112"}},{@@ -1039,7 +1113,7 @@"name": "num","kind": "function","path": "src/ai/crux.ts",- "span": "L88-L88",+ "span": "L104-L104","signature": "num = (v: unknown)","exported": false,"origin": "ast",@@ -1056,7 +1130,7 @@"name": "userContent","kind": "function","path": "src/ai/crux.ts",- "span": "L72-L81",+ "span": "L90-L99","signature": "function userContent(input: FileCruxInput): string","exported": false,"origin": "ast",@@ -1069,132 +1143,756 @@}},{- "id": "src/ai/providers.ts",- "name": "providers.ts",+ "id": "src/ai/llm/anthropic.ts",+ "name": "anthropic.ts","kind": "file",- "path": "src/ai/providers.ts",- "span": "L1-L56",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L1-L156","signature": null,"exported": true,"origin": "ast",- "body_hash": "c0d1294d6fa49f6d06ff9bb137b34ea897f94a67810a839cd5705a1fa5995483",- "chars": 2035,+ "body_hash": "db2b6db5102af2045a3f85933faeac8ef9b0c17bc2fcbfd3b41629622bb9551b",+ "chars": 6162,"summary_state": "ready",- "summary": "This file defines configurations for an AI engine, allowing customization and default settings for its operation.",- "crux": null+ "summary": "This module provides an adapter for the Anthropic Messages API, enabling seamless integration of Claude as a first-class AI provider while handling specific API differences.",+ "crux": {+ "code": " async create(req: ChatRequest): Promise<ChatResponse> {\n const system: Anthropic.TextBlockParam[] = [];\n const messages: Anthropic.MessageParam[] = [];\n\n for (const m of req.messages) {\n if (m.role === \"system\") {\n system.push({ type: \"text\", text: m.content, ...cc(m.cacheBreakpoint) });\n } else if (m.role === \"user\") {\n messages.push({ role: \"user\", content: [{ type: \"text\", text: m.content, ...cc(m.cacheBreakpoint) }] });\n } else if (m.role === \"tool\") {\n // Tool results live in a user turn; coalesce consecutive results together.\n const block: Anthropic.ToolResultBlockParam = {",+ "span": "L47-L58"+ }},{- "id": "src/ai/providers.ts#EngineConfig",- "name": "EngineConfig",- "kind": "interface",- "path": "src/ai/providers.ts",- "span": "L9-L25",- "signature": "interface EngineConfig",+ "id": "src/ai/llm/anthropic.ts#AnthropicChatModel",+ "name": "AnthropicChatModel",+ "kind": "class",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L36-L141",+ "signature": "class AnthropicChatModel implements ChatModel","exported": true,"origin": "ast",- "body_hash": "a7457b873338ce2ea7e53be6eca715bcbfce5cc85dd0d8b770145702027e6836",+ "body_hash": "df44498d6950b1274c70eeb84842639ad0f9d86f1cd2db47b42c9ab20483e8b8","summary_state": "ready",- "summary": "EngineConfig provides a structure for user-defined settings, enabling flexibility in configuring the AI engine's behavior.",- "crux": null+ "summary": "Implements the chat model interface for interacting with the Anthropic API, encapsulating the logic for message handling and API communication.",+ "crux": {+ "code": "export class AnthropicChatModel implements ChatModel {\n readonly label: string;\n private client: Anthropic;\n private model: string;\n\n constructor(opts: AnthropicChatModelOptions) {\n this.model = opts.model;\n this.label = opts.label ?? `${PROVIDER}:${opts.model}`;\n this.client = opts.client ?? new Anthropic({ apiKey: opts.apiKey, baseURL: opts.baseUrl });\n }\n\n async create(req: ChatRequest): Promise<ChatResponse> {",+ "span": "L36-L47"+ }},{- "id": "src/ai/providers.ts#resolveConfig",- "name": "resolveConfig",- "kind": "function",- "path": "src/ai/providers.ts",- "span": "L43-L55",- "signature": "function resolveConfig(config: EngineConfig = {}): ResolvedConfig",+ "id": "src/ai/llm/anthropic.ts#AnthropicChatModel.assistantParam",+ "name": "assistantParam",+ "kind": "method",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L103-L111",+ "signature": "private assistantParam(m: Message): Anthropic.MessageParam","exported": true,"origin": "ast",- "body_hash": "9bc6a9e9d026366226705cba49e3d45fc68ee309ec3106c750983cba9d292bad",+ "body_hash": "d7b6ae0665be6a724f169b18327a7c03f54a374e128df7c8e491db4a6d5824a9","summary_state": "ready",- "summary": "resolveConfig combines user configuration with environment variables and defaults to produce a complete configuration for the AI engine.",+ "summary": "Reconstructs the assistant's response from the original message blocks, preserving the context and structure of the conversation.","crux": {- "code": " contextDir: config.contextDir ?? env.GRAFT_DIR,\n openrouterApiKey: config.openrouterApiKey ?? env.OPENROUTER_API_KEY,\n openrouterModel:\n config.openrouterModel ?? env.GRAFT_OPENROUTER_MODEL ?? DEFAULTS.openrouterModel,\n openrouterBaseUrl:\n config.openrouterBaseUrl ?? env.OPENROUTER_BASE_URL ?? DEFAULTS.openrouterBaseUrl,",- "span": "L46-L51"+ "code": " private assistantParam(m: Message): Anthropic.MessageParam {\n if (m.providerRaw?.provider === PROVIDER) return m.providerRaw.raw as Anthropic.MessageParam;\n const content: Anthropic.ContentBlockParam[] = [];\n if (m.content) content.push({ type: \"text\", text: m.content });\n for (const tc of m.toolCalls ?? []) {\n content.push({ type: \"tool_use\", id: tc.id, name: tc.name, input: tc.args as Record<string, unknown> });\n }\n return { role: \"assistant\", content };\n }",+ "span": "L103-L111"}},{- "id": "src/ai/providers.ts#ResolvedConfig",- "name": "ResolvedConfig",- "kind": "interface",- "path": "src/ai/providers.ts",- "span": "L28-L35",- "signature": "interface ResolvedConfig",+ "id": "src/ai/llm/anthropic.ts#AnthropicChatModel.constructor",+ "name": "constructor",+ "kind": "method",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L41-L45",+ "signature": "constructor(opts: AnthropicChatModelOptions)","exported": true,"origin": "ast",- "body_hash": "7f4ebf13b13a0cf260534237a8b8ee71fb2dfa23c113c63aa860169af6d6ad70",+ "body_hash": "3e283d003830e60bd46c3f3e93e20715e03e65c67ffc8921a869bea7ec390025","summary_state": "ready",- "summary": "ResolvedConfig represents the final configuration after merging user inputs with defaults and environment variables, ensuring all necessary settings are available.",- "crux": null+ "summary": "Initializes an instance of the AnthropicChatModel with the provided options, setting up the necessary API client and model details.",+ "crux": {+ "code": " constructor(opts: AnthropicChatModelOptions) {\n this.model = opts.model;\n this.label = opts.label ?? `${PROVIDER}:${opts.model}`;\n this.client = opts.client ?? new Anthropic({ apiKey: opts.apiKey, baseURL: opts.baseUrl });\n }",+ "span": "L41-L45"+ }},{- "id": "src/ai/summarize.ts",- "name": "summarize.ts",- "kind": "file",- "path": "src/ai/summarize.ts",- "span": "L1-L62",- "signature": null,+ "id": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "name": "create",+ "kind": "method",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L47-L100",+ "signature": "async create(req: ChatRequest): Promise<ChatResponse>","exported": true,"origin": "ast",- "body_hash": "6e67f3866c75d88a8b1d265e510578f3e3014d9cfd8b2469e6e4afbd67977f93",- "chars": 2519,+ "body_hash": "8e00930f455ffe190513110bb5a79beba2b4f145be804594375781abf08f2d1f","summary_state": "ready",- "summary": "This file provides functionality to summarize source code files into plain English for a knowledge graph.",+ "summary": "Handles the creation of chat messages by processing input requests and formatting them for the Anthropic API, ensuring compliance with API requirements.","crux": {- "code": "/**\n * Turns one source-code file into a short prose summary for the knowledge graph.\n *\n * Code repos are deliberately NOT fed through the per-chunk entity extractor:\n * static structure is better served by grep/tree-sitter in the consuming agent,\n * and LLM extraction over raw code produces noisy, duplicated entities. Instead\n * the repo ingest path summarizes each file into plain English (purpose, key\n * exports, dependencies, design decisions) and ingests those summaries — prose\n * the existing extraction pipeline is actually good at.",- "span": "L3-L11"+ "code": " async create(req: ChatRequest): Promise<ChatResponse> {\n const system: Anthropic.TextBlockParam[] = [];\n const messages: Anthropic.MessageParam[] = [];\n\n for (const m of req.messages) {\n if (m.role === \"system\") {\n system.push({ type: \"text\", text: m.content, ...cc(m.cacheBreakpoint) });\n } else if (m.role === \"user\") {\n messages.push({ role: \"user\", content: [{ type: \"text\", text: m.content, ...cc(m.cacheBreakpoint) }] });\n } else if (m.role === \"tool\") {\n // Tool results live in a user turn; coalesce consecutive results together.\n const block: Anthropic.ToolResultBlockParam = {",+ "span": "L47-L58"}},{- "id": "src/ai/summarize.ts#OpenRouterSummarizer",- "name": "OpenRouterSummarizer",- "kind": "class",- "path": "src/ai/summarize.ts",- "span": "L37-L61",- "signature": "class OpenRouterSummarizer implements Summarizer",+ "id": "src/ai/llm/anthropic.ts#AnthropicChatModel.fromResponse",+ "name": "fromResponse",+ "kind": "method",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L113-L140",+ "signature": "private fromResponse(resp: Anthropic.Messages.Message, format: \"text\" | \"json\" | \"tool\"): ChatResponse","exported": true,"origin": "ast",- "body_hash": "d5ccc8425da5d5e01cb9d0371aa4b7f6ddc27ca2f5b33d06315b2141b1ba5f44",+ "body_hash": "2a223c595a5d2911bea9aa89f67baca06067110a28a6dc08b59bcc6c7eafb82b","summary_state": "ready",- "summary": "The OpenRouterSummarizer class implements the Summarizer interface using OpenAI's chat API to generate summaries.",+ "summary": "Transforms the API response into a structured ChatResponse object, extracting relevant information and maintaining the original message format.","crux": {- "code": "export class OpenRouterSummarizer implements Summarizer {\n private client: OpenAI;\n private model: string;\n\n constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\") {\n this.client = new OpenAI({\n apiKey,\n baseURL: baseUrl,\n defaultHeaders: { \"X-Title\": \"Context Graph Engine\" },\n });\n this.model = model;\n }",- "span": "L37-L48"+ "code": " private fromResponse(resp: Anthropic.Messages.Message, format: \"text\" | \"json\" | \"tool\"): ChatResponse {\n let text = \"\";\n let toolCalls: ToolCall[] = [];\n for (const block of resp.content) {\n if (block.type === \"text\") text += block.text;\n else if (block.type === \"tool_use\") toolCalls.push({ id: block.id, name: block.name, args: block.input });\n }\n\n if (format === \"json\") {\n const jsonCall = toolCalls.find((c) => c.name === JSON_TOOL);\n if (jsonCall) text = JSON.stringify(jsonCall.args);\n toolCalls = toolCalls.filter((c) => c.name !== JSON_TOOL);",+ "span": "L113-L124"+ }+ },+ {+ "id": "src/ai/llm/anthropic.ts#AnthropicChatModelOptions",+ "name": "AnthropicChatModelOptions",+ "kind": "interface",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L24-L31",+ "signature": "interface AnthropicChatModelOptions",+ "exported": true,+ "origin": "ast",+ "body_hash": "b52d600691c002121647f5fa47c28559ef5ccbf0622946e02b71705e93734732",+ "summary_state": "ready",+ "summary": "Defines the configuration options required to instantiate an Anthropic chat model, ensuring necessary parameters are provided.",+ "crux": {+ "code": " apiKey: string;\n model: string;\n baseUrl?: string;\n label?: string;\n /** Inject a pre-built client (tests pass a stub; production omits it). */\n client?: Anthropic;\n}",+ "span": "L25-L31"+ }+ },+ {+ "id": "src/ai/llm/anthropic.ts#CacheControl",+ "name": "CacheControl",+ "kind": "type",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L33-L33",+ "signature": "type CacheControl = { cache_control: { type: \"ephemeral\" } } | Record<string, never>;",+ "exported": false,+ "origin": "ast",+ "body_hash": "6e3dd85fab0c1f395bb4e7b31d9c4352352f1c2ac7223b9c7ad2efeb2e633867",+ "summary_state": "ready",+ "summary": "Specifies the cache control settings for ephemeral data management in the chat model.",+ "crux": null+ },+ {+ "id": "src/ai/llm/anthropic.ts#cc",+ "name": "cc",+ "kind": "function",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L34-L34",+ "signature": "cc = (on: boolean | undefined): CacheControl",+ "exported": false,+ "origin": "ast",+ "body_hash": "13cf0b3c8efee32666046570936ac3683be97082f8d0b893e44b4488b18fd86d",+ "summary_state": "ready",+ "summary": "Creates a cache control object based on a boolean flag to manage ephemeral caching behavior.",+ "crux": {+ "code": "const cc = (on: boolean | undefined): CacheControl => (on ? { cache_control: { type: \"ephemeral\" } } : {});",+ "span": "L34-L34"+ }+ },+ {+ "id": "src/ai/llm/anthropic.ts#normalizeUsage",+ "name": "normalizeUsage",+ "kind": "function",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L148-L155",+ "signature": "function normalizeUsage(u: Anthropic.Usage): Usage",+ "exported": false,+ "origin": "ast",+ "body_hash": "5569d4f5086a9681eea0ef8083ef7d39cbca2319f0c62522a8f54e5766c2e2d3",+ "summary_state": "ready",+ "summary": "Normalizes the usage statistics from the Anthropic API response, providing a consistent structure for input and output token counts.",+ "crux": {+ "code": "function normalizeUsage(u: Anthropic.Usage): Usage {\n return {\n input: u.input_tokens ?? 0,\n output: u.output_tokens ?? 0,\n cacheRead: u.cache_read_input_tokens ?? 0,\n cacheCreate: u.cache_creation_input_tokens ?? 0,\n };\n}",+ "span": "L148-L155"+ }+ },+ {+ "id": "src/ai/llm/anthropic.ts#toAnthropicTool",+ "name": "toAnthropicTool",+ "kind": "function",+ "path": "src/ai/llm/anthropic.ts",+ "span": "L143-L145",+ "signature": "function toAnthropicTool(t: ToolSpec): Anthropic.Tool",+ "exported": false,+ "origin": "ast",+ "body_hash": "88a0375d055904d0ba42659ec152984a7d6bb3c46602c0d6d2a9802c75d9df77",+ "summary_state": "ready",+ "summary": "Converts a ToolSpec into the format required by the Anthropic API, facilitating the integration of tools into chat requests.",+ "crux": {+ "code": "function toAnthropicTool(t: ToolSpec): Anthropic.Tool {\n return { name: t.name, description: t.description, input_schema: t.parameters as Anthropic.Tool.InputSchema };\n}",+ "span": "L143-L145"+ }+ },+ {+ "id": "src/ai/llm/factory.ts",+ "name": "factory.ts",+ "kind": "file",+ "path": "src/ai/llm/factory.ts",+ "span": "L1-L40",+ "signature": null,+ "exported": true,+ "origin": "ast",+ "body_hash": "d7d22f3b6af8380ff1073ddd6934eda35b3c6b95a1976223751136c0cd26122a",+ "chars": 1382,+ "summary_state": "ready",+ "summary": "Creates instances of ChatModel based on the specified provider configuration, enabling flexible integration with different chat model APIs.",+ "crux": {+ "code": " switch (cfg.provider) {\n case \"anthropic\":\n return new AnthropicChatModel({ apiKey: cfg.apiKey, model: cfg.model, baseUrl: cfg.baseUrl });\n case \"openai\":\n return new OpenAIChatModel({\n apiKey: cfg.apiKey,\n model: cfg.model,\n baseUrl: cfg.baseUrl,\n headers: cfg.headers,\n });\n default: {\n const _exhaustive: never = cfg.provider;",+ "span": "L24-L35"+ }+ },+ {+ "id": "src/ai/llm/factory.ts#ChatModelConfig",+ "name": "ChatModelConfig",+ "kind": "interface",+ "path": "src/ai/llm/factory.ts",+ "span": "L14-L21",+ "signature": "interface ChatModelConfig",+ "exported": true,+ "origin": "ast",+ "body_hash": "fe601294b311058cbc1f66a5c4d1612166ced8f3a0930b29840c7c58dbe8c26d",+ "summary_state": "ready",+ "summary": "Specifies the configuration required to create a chat model, enforcing necessary parameters for initialization.",+ "crux": null+ },+ {+ "id": "src/ai/llm/factory.ts#createChatModel",+ "name": "createChatModel",+ "kind": "function",+ "path": "src/ai/llm/factory.ts",+ "span": "L23-L39",+ "signature": "function createChatModel(cfg: ChatModelConfig): ChatModel",+ "exported": true,+ "origin": "ast",+ "body_hash": "23778c8e4e0f6b0151bdb1ab4a9f13cd454ba48471450592a7a39235868acfc3",+ "summary_state": "ready",+ "summary": "Creates an instance of a chat model based on the specified provider, handling different implementations accordingly.",+ "crux": {+ "code": " switch (cfg.provider) {\n case \"anthropic\":\n return new AnthropicChatModel({ apiKey: cfg.apiKey, model: cfg.model, baseUrl: cfg.baseUrl });\n case \"openai\":\n return new OpenAIChatModel({\n apiKey: cfg.apiKey,\n model: cfg.model,\n baseUrl: cfg.baseUrl,\n headers: cfg.headers,\n });\n default: {\n const _exhaustive: never = cfg.provider;",+ "span": "L24-L35"+ }+ },+ {+ "id": "src/ai/llm/factory.ts#ProviderKind",+ "name": "ProviderKind",+ "kind": "type",+ "path": "src/ai/llm/factory.ts",+ "span": "L12-L12",+ "signature": "type ProviderKind = \"openai\" | \"anthropic\";",+ "exported": true,+ "origin": "ast",+ "body_hash": "0b615c32dce2df3c8f4ab12d84dec220c5dccf856284b414c95117583ac7046b",+ "summary_state": "ready",+ "summary": "Defines the types of providers for chat models, ensuring compatibility with specific APIs.",+ "crux": null+ },+ {+ "id": "src/ai/llm/openai.ts",+ "name": "openai.ts",+ "kind": "file",+ "path": "src/ai/llm/openai.ts",+ "span": "L1-L175",+ "signature": null,+ "exported": true,+ "origin": "ast",+ "body_hash": "6cb2677125f9a2c8c617fb1aef072fad13b87413d5ec40bebf3e21e0acc784df",+ "chars": 6327,+ "summary_state": "ready",+ "summary": "This module provides an adapter for interacting with various OpenAI-compatible endpoints, allowing users to send chat requests and receive responses while managing caching and formatting options.",+ "crux": {+ "code": " async create(req: ChatRequest): Promise<ChatResponse> {\n const messages = req.messages.map(toChatMessage);\n const tools = req.tools ? req.tools.map(toChatTool) : undefined;\n const params: ChatParams = { model: this.model, messages };\n if (req.temperature !== undefined) params.temperature = req.temperature;\n if (req.maxTokens !== undefined) params.max_tokens = req.maxTokens;\n\n const fmt = req.responseFormat ?? { kind: \"text\" };\n if (fmt.kind === \"json\") {\n // Coerce JSON via a forced synthetic tool — the one structured-output\n // mechanism shared with Anthropic (no reliance on `response_format`).\n params.tools = [",+ "span": "L90-L101"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#ChatMessage",+ "name": "ChatMessage",+ "kind": "type",+ "path": "src/ai/llm/openai.ts",+ "span": "L32-L32",+ "signature": "type ChatMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;",+ "exported": false,+ "origin": "ast",+ "body_hash": "ab4f41436d89ea9d719528cf8858881ddd7b5819bc1d35a581e53e5d054d4646",+ "summary_state": "ready",+ "summary": "Represents a message in the chat, encapsulating the role and content to facilitate communication between users and the AI.",+ "crux": null+ },+ {+ "id": "src/ai/llm/openai.ts#ChatParams",+ "name": "ChatParams",+ "kind": "type",+ "path": "src/ai/llm/openai.ts",+ "span": "L31-L31",+ "signature": "type ChatParams = OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming;",+ "exported": false,+ "origin": "ast",+ "body_hash": "589e332819f8569fb523921b364022d36270aa53171d43a774ac16343e5034cb",+ "summary_state": "ready",+ "summary": "Defines the parameters required for creating a chat completion request, ensuring the correct structure is used for API calls.",+ "crux": null+ },+ {+ "id": "src/ai/llm/openai.ts#normalizeUsage",+ "name": "normalizeUsage",+ "kind": "function",+ "path": "src/ai/llm/openai.ts",+ "span": "L165-L174",+ "signature": "function normalizeUsage(u: OpenAI.Completions.CompletionUsage | undefined): Usage",+ "exported": false,+ "origin": "ast",+ "body_hash": "387c663d9cb9b316e7cd3217c6f98f526fd750364e07ab75c7e455a320d59b4c",+ "summary_state": "ready",+ "summary": "Normalizes usage statistics by calculating uncached input tokens from the OpenAI API response.",+ "crux": {+ "code": "function normalizeUsage(u: OpenAI.Completions.CompletionUsage | undefined): Usage {\n const prompt = u?.prompt_tokens ?? 0;\n const cacheRead = u?.prompt_tokens_details?.cached_tokens ?? 0;\n return {\n input: Math.max(0, prompt - cacheRead),\n output: u?.completion_tokens ?? 0,\n cacheRead,\n cacheCreate: 0,\n };\n}",+ "span": "L165-L174"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#OpenAIChatModel",+ "name": "OpenAIChatModel",+ "kind": "class",+ "path": "src/ai/llm/openai.ts",+ "span": "L73-L162",+ "signature": "class OpenAIChatModel implements ChatModel",+ "exported": true,+ "origin": "ast",+ "body_hash": "575a27dfb2cccd63e9a71e5d67db8d9e47bd57c55ed6327ea4420b9920545efb",+ "summary_state": "ready",+ "summary": "Implements the chat model interface for interacting with OpenAI's chat completions API.",+ "crux": {+ "code": "export class OpenAIChatModel implements ChatModel {\n readonly label: string;\n private client: OpenAI;\n private model: string;\n\n constructor(opts: OpenAIChatModelOptions) {\n this.model = opts.model;\n this.label = opts.label ?? `${PROVIDER}:${opts.model}`;\n this.client =\n opts.client ??\n new OpenAI({\n apiKey: opts.apiKey,",+ "span": "L73-L84"}},{- "id": "src/ai/summarize.ts#OpenRouterSummarizer.constructor",+ "id": "src/ai/llm/openai.ts#OpenAIChatModel.constructor","name": "constructor","kind": "method",+ "path": "src/ai/llm/openai.ts",+ "span": "L78-L88",+ "signature": "constructor(opts: OpenAIChatModelOptions)",+ "exported": true,+ "origin": "ast",+ "body_hash": "b179c8e67ab77c95de1b648919a4329b49a601dd5034aab043a60e6d38d555fc",+ "summary_state": "ready",+ "summary": "Initializes an OpenAIChatModel instance with the specified options, setting up the necessary API client and model parameters for chat interactions.",+ "crux": {+ "code": " constructor(opts: OpenAIChatModelOptions) {\n this.model = opts.model;\n this.label = opts.label ?? `${PROVIDER}:${opts.model}`;\n this.client =\n opts.client ??\n new OpenAI({\n apiKey: opts.apiKey,\n baseURL: opts.baseUrl,\n defaultHeaders: opts.headers,\n });\n }",+ "span": "L78-L88"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#OpenAIChatModel.create",+ "name": "create",+ "kind": "method",+ "path": "src/ai/llm/openai.ts",+ "span": "L90-L115",+ "signature": "async create(req: ChatRequest): Promise<ChatResponse>",+ "exported": true,+ "origin": "ast",+ "body_hash": "1d9f5481b5c893aaf1e904960ce16909b066d969c4fd7ac507b8db1b2ba1ee63",+ "summary_state": "ready",+ "summary": "Creates a chat completion request to the OpenAI API using the provided messages and parameters.",+ "crux": {+ "code": " async create(req: ChatRequest): Promise<ChatResponse> {\n const messages = req.messages.map(toChatMessage);\n const tools = req.tools ? req.tools.map(toChatTool) : undefined;\n const params: ChatParams = { model: this.model, messages };\n if (req.temperature !== undefined) params.temperature = req.temperature;\n if (req.maxTokens !== undefined) params.max_tokens = req.maxTokens;\n\n const fmt = req.responseFormat ?? { kind: \"text\" };\n if (fmt.kind === \"json\") {\n // Coerce JSON via a forced synthetic tool — the one structured-output\n // mechanism shared with Anthropic (no reliance on `response_format`).\n params.tools = [",+ "span": "L90-L101"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse",+ "name": "fromResponse",+ "kind": "method",+ "path": "src/ai/llm/openai.ts",+ "span": "L117-L161",+ "signature": "private fromResponse( resp: OpenAI.Chat.Completions.ChatCompletion, format: \"text\" | \"json\" | \"tool\", ): ChatResponse",+ "exported": true,+ "origin": "ast",+ "body_hash": "bf540f6d0d4bc0d8c22bd5345e2765318f079d7e051b5f3462c35a0a26e0c0a9",+ "summary_state": "ready",+ "summary": "Processes the response from the OpenAI API to extract relevant chat information and tool calls.",+ "crux": {+ "code": " private fromResponse(\n resp: OpenAI.Chat.Completions.ChatCompletion,\n format: \"text\" | \"json\" | \"tool\",\n ): ChatResponse {\n const choice = resp.choices[0];\n const msg = choice?.message;\n const rawCalls = (msg?.tool_calls ?? []).filter(\n (c): c is OpenAI.Chat.Completions.ChatCompletionMessageToolCall & { type: \"function\" } =>\n c.type === \"function\",\n );\n const parse = (s: string): unknown => {\n try {",+ "span": "L117-L128"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse.parse",+ "name": "parse",+ "kind": "function",+ "path": "src/ai/llm/openai.ts",+ "span": "L127-L133",+ "signature": "parse = (s: string): unknown",+ "exported": true,+ "origin": "ast",+ "body_hash": "ebfdf3f91ed448d6e123ac7d414de409848181986b97987b04b61d38b6655af2",+ "summary_state": "ready",+ "summary": "Safely parses a JSON string into an object, handling errors to ensure robust processing of responses from the chat API.",+ "crux": {+ "code": " const parse = (s: string): unknown => {\n try {\n return JSON.parse(s || \"{}\");\n } catch {\n return {};\n }\n };",+ "span": "L127-L133"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#OpenAIChatModelOptions",+ "name": "OpenAIChatModelOptions",+ "kind": "interface",+ "path": "src/ai/llm/openai.ts",+ "span": "L19-L29",+ "signature": "interface OpenAIChatModelOptions",+ "exported": true,+ "origin": "ast",+ "body_hash": "ff7f8380828dd929b11c662c999e0b7ce9c3260df3d4858b3fe7c0496687b299",+ "summary_state": "ready",+ "summary": "Defines the configuration options for the OpenAI chat model, including API key and model type.",+ "crux": {+ "code": "export interface OpenAIChatModelOptions {\n apiKey: string;\n model: string;\n baseUrl?: string;\n /** Stable manifest label; defaults to `openai:<model>`. */\n label?: string;\n /** Extra default headers (e.g. OpenRouter's `X-Title`). */\n headers?: Record<string, string>;\n /** Inject a pre-built client (tests pass a stub; production omits it). */\n client?: OpenAI;\n}",+ "span": "L19-L29"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#textPart",+ "name": "textPart",+ "kind": "function",+ "path": "src/ai/llm/openai.ts",+ "span": "L35-L39",+ "signature": "function textPart(text: string, cache: boolean | undefined)",+ "exported": false,+ "origin": "ast",+ "body_hash": "10133cedc05270e0f828b1306d2a86ac0ae22a3e8fc92821831861ab3103d311",+ "summary_state": "ready",+ "summary": "Constructs a text message part with optional cache control for OpenRouter passthrough.",+ "crux": {+ "code": "function textPart(text: string, cache: boolean | undefined) {\n return cache\n ? [{ type: \"text\" as const, text, cache_control: { type: \"ephemeral\" as const } }]\n : text;\n}",+ "span": "L35-L39"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#toChatMessage",+ "name": "toChatMessage",+ "kind": "function",+ "path": "src/ai/llm/openai.ts",+ "span": "L41-L67",+ "signature": "function toChatMessage(m: Message): ChatMessage",+ "exported": false,+ "origin": "ast",+ "body_hash": "b4eaa6383c6bdcf7b2380a4d1de0a485010eb5e5615d15e970a8c9391e4b48c3",+ "summary_state": "ready",+ "summary": "Transforms a message object into a format suitable for OpenAI's chat API, handling different roles appropriately.",+ "crux": {+ "code": "function toChatMessage(m: Message): ChatMessage {\n switch (m.role) {\n case \"system\":\n return { role: \"system\", content: textPart(m.content, m.cacheBreakpoint) } as ChatMessage;\n case \"user\":\n return { role: \"user\", content: textPart(m.content, m.cacheBreakpoint) } as ChatMessage;\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: m.toolCallId ?? \"\",\n content: textPart(m.content, m.cacheBreakpoint),\n } as ChatMessage;",+ "span": "L41-L52"+ }+ },+ {+ "id": "src/ai/llm/openai.ts#toChatTool",+ "name": "toChatTool",+ "kind": "function",+ "path": "src/ai/llm/openai.ts",+ "span": "L69-L71",+ "signature": "function toChatTool(t: ToolSpec): OpenAI.Chat.Completions.ChatCompletionTool",+ "exported": false,+ "origin": "ast",+ "body_hash": "9bcc919fc8a9b8a5892850e10957c57a1bb03ec575eb982ed9137ddc14f7553e",+ "summary_state": "ready",+ "summary": "Converts a tool specification into a format compatible with OpenAI's chat completion API, enabling the use of external tools in chat interactions.",+ "crux": {+ "code": "function toChatTool(t: ToolSpec): OpenAI.Chat.Completions.ChatCompletionTool {\n return { type: \"function\", function: { name: t.name, description: t.description, parameters: t.parameters } };\n}",+ "span": "L69-L71"+ }+ },+ {+ "id": "src/ai/llm/types.ts",+ "name": "types.ts",+ "kind": "file",+ "path": "src/ai/llm/types.ts",+ "span": "L1-L114",+ "signature": null,+ "exported": true,+ "origin": "ast",+ "body_hash": "8cb0f2a715498ae396ca2f5d6f14711be026346b218e07da0b30909d3cd93c93",+ "chars": 4254,+ "summary_state": "ready",+ "summary": "Defines interfaces and types for a provider-neutral chat transport system that facilitates communication with various language model providers.",+ "crux": {+ "code": "/** A single tool invocation requested by the model. `args` is ALREADY parsed. */\nexport interface ToolCall {\n id: string;\n name: string;\n /** Parsed argument object. Adapters (de)serialize to their wire format. */\n args: unknown;\n}\n\n/** One turn in a conversation, in provider-neutral form. */\nexport interface Message {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n /** Plain-text content. Empty string when a turn is purely tool calls/results. */",+ "span": "L22-L33"+ }+ },+ {+ "id": "src/ai/llm/types.ts#ChatModel",+ "name": "ChatModel",+ "kind": "interface",+ "path": "src/ai/llm/types.ts",+ "span": "L110-L113",+ "signature": "interface ChatModel",+ "exported": true,+ "origin": "ast",+ "body_hash": "189599546411bb1a83083ef8871d3cd5c464e449532e11d3255d20ed5f1facdc",+ "summary_state": "ready",+ "summary": "Defines a connection to a specific model, providing a method to create chat requests and ensuring consistent interaction with the model.",+ "crux": {+ "code": "export interface ChatModel {\n readonly label: string;\n create(req: ChatRequest): Promise<ChatResponse>;\n}",+ "span": "L110-L113"+ }+ },+ {+ "id": "src/ai/llm/types.ts#ChatRequest",+ "name": "ChatRequest",+ "kind": "interface",+ "path": "src/ai/llm/types.ts",+ "span": "L85-L94",+ "signature": "interface ChatRequest",+ "exported": true,+ "origin": "ast",+ "body_hash": "cca0720f5c0bc885c0bebcd0df2faea83445f025bcca11a1e6109dc988136bb6",+ "summary_state": "ready",+ "summary": "Encapsulates a request to the chat model, including messages, tools, and response format, to standardize interactions with the model.",+ "crux": {+ "code": "export interface ChatRequest {\n messages: Message[];\n tools?: ToolSpec[];\n /** Default: `{ kind: \"text\" }`. */\n responseFormat?: ResponseFormat;\n /** Providers that reject it (current Anthropic models) drop it in the adapter. */\n temperature?: number;\n /** Max output tokens. Required by Anthropic; adapters supply a default. */\n maxTokens?: number;\n}",+ "span": "L85-L94"+ }+ },+ {+ "id": "src/ai/llm/types.ts#ChatResponse",+ "name": "ChatResponse",+ "kind": "interface",+ "path": "src/ai/llm/types.ts",+ "span": "L96-L104",+ "signature": "interface ChatResponse",+ "exported": true,+ "origin": "ast",+ "body_hash": "da777026c7875767ace42f299e1881a2d67780936c3392adc7cea722d09ead38",+ "summary_state": "ready",+ "summary": "Represents the response from the chat model, including the assistant's text, tool calls made, and usage statistics, to provide a complete interaction result.",+ "crux": {+ "code": "export interface ChatResponse {\n /** Concatenated assistant text (empty when the turn only made tool calls). */\n text: string;\n toolCalls: ToolCall[];\n usage: Usage;\n stopReason: string | null;\n /** The assistant turn as a neutral message — push straight back into `messages`. */\n assistant: Message;\n}",+ "span": "L96-L104"+ }+ },+ {+ "id": "src/ai/llm/types.ts#Message",+ "name": "Message",+ "kind": "interface",+ "path": "src/ai/llm/types.ts",+ "span": "L31-L52",+ "signature": "interface Message",+ "exported": true,+ "origin": "ast",+ "body_hash": "eaaa8e2638eeaa70f6260926f747620b01a6c2b9ff71c5233c1a49781e0d7287",+ "summary_state": "ready",+ "summary": "Defines a turn in a conversation, allowing for structured communication between users and the assistant, including tool calls and raw provider data.",+ "crux": {+ "code": " role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n /** Plain-text content. Empty string when a turn is purely tool calls/results. */\n content: string;\n /** Assistant turns only: tool calls the model asked for. */\n toolCalls?: ToolCall[];\n /** Tool turns only: the id of the {@link ToolCall} this result answers. */\n toolCallId?: string;\n /**\n * Request a provider cache marker (`cache_control: ephemeral`) on THIS message.\n * The transport only understands this per-message flag; any sliding/rotation\n * policy lives in the caller (see the bench loop).\n */",+ "span": "L32-L43"+ }+ },+ {+ "id": "src/ai/llm/types.ts#ResponseFormat",+ "name": "ResponseFormat",+ "kind": "type",+ "path": "src/ai/llm/types.ts",+ "span": "L68-L71",+ "signature": "type ResponseFormat = | { kind: \"text\" } | { kind: \"json\" } | { kind: \"tool\"; name: string };",+ "exported": true,+ "origin": "ast",+ "body_hash": "61c1f5fab878eba0f3c1dbb15cf272277325c2ca7df4cf36f8986b18c8e673f3",+ "summary_state": "ready",+ "summary": "Specifies the format in which the model must respond, ensuring compatibility across different output types like text, JSON, or tool calls.",+ "crux": {+ "code": "export type ResponseFormat =\n | { kind: \"text\" }\n | { kind: \"json\" }\n | { kind: \"tool\"; name: string };",+ "span": "L68-L71"+ }+ },+ {+ "id": "src/ai/llm/types.ts#ToolCall",+ "name": "ToolCall",+ "kind": "interface",+ "path": "src/ai/llm/types.ts",+ "span": "L23-L28",+ "signature": "interface ToolCall",+ "exported": true,+ "origin": "ast",+ "body_hash": "1ee8861c6f11e6f2c3cd47a765496071720b09f760cda7f0c1c37bde07573913",+ "summary_state": "ready",+ "summary": "Represents a single invocation of a tool requested by the model, encapsulating its ID, name, and parsed arguments.",+ "crux": {+ "code": " id: string;\n name: string;\n /** Parsed argument object. Adapters (de)serialize to their wire format. */\n args: unknown;\n}",+ "span": "L24-L28"+ }+ },+ {+ "id": "src/ai/llm/types.ts#ToolSpec",+ "name": "ToolSpec",+ "kind": "interface",+ "path": "src/ai/llm/types.ts",+ "span": "L55-L59",+ "signature": "interface ToolSpec",+ "exported": true,+ "origin": "ast",+ "body_hash": "6e6b8c516b5772e7989411d4c8707ea5193e65d35b610bb7900579542eefd4d8",+ "summary_state": "ready",+ "summary": "Describes a tool that the model can call, including its name, description, and parameters, facilitating interaction with various tools.",+ "crux": {+ "code": "export interface ToolSpec {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n}",+ "span": "L55-L59"+ }+ },+ {+ "id": "src/ai/llm/types.ts#Usage",+ "name": "Usage",+ "kind": "interface",+ "path": "src/ai/llm/types.ts",+ "span": "L78-L83",+ "signature": "interface Usage",+ "exported": true,+ "origin": "ast",+ "body_hash": "3ac3091408d0a87c468fed20e0867ecbd87f41a6cc83c92047c2dbc0281705b7",+ "summary_state": "ready",+ "summary": "Tracks token usage across providers, normalizing input and output counts to facilitate consistent accounting in multi-provider environments.",+ "crux": {+ "code": "export interface Usage {\n input: number;\n output: number;\n cacheRead: number;\n cacheCreate: number;\n}",+ "span": "L78-L83"+ }+ },+ {+ "id": "src/ai/providers.ts",+ "name": "providers.ts",+ "kind": "file",+ "path": "src/ai/providers.ts",+ "span": "L1-L107",+ "signature": null,+ "exported": true,+ "origin": "ast",+ "body_hash": "ba27e2c6d98b088685946371971e9f82c7a54bba9eaa432d44881880274eb1d6",+ "chars": 3713,+ "summary_state": "ready",+ "summary": "This module provides configuration management for AI model providers, allowing users to specify settings and defaults for various AI services.",+ "crux": {+ "code": "export function resolveConfig(config: EngineConfig = {}): ResolvedConfig {\n const env = process.env;\n const provider = config.provider ?? (env.GRAFT_PROVIDER as ProviderKind | undefined) ?? DEFAULTS.provider;\n\n const explicitKey = config.apiKey ?? env.GRAFT_API_KEY;\n const legacyKey = env.OPENROUTER_API_KEY;\n const apiKey = explicitKey ?? legacyKey;\n const usedLegacyEnv = !explicitKey && !!legacyKey;\n\n const model =\n config.model ?? env.GRAFT_MODEL ?? env.GRAFT_OPENROUTER_MODEL ?? DEFAULT_MODELS[provider];\n",+ "span": "L71-L82"+ }+ },+ {+ "id": "src/ai/providers.ts#EngineConfig",+ "name": "EngineConfig",+ "kind": "interface",+ "path": "src/ai/providers.ts",+ "span": "L17-L39",+ "signature": "interface EngineConfig",+ "exported": true,+ "origin": "ast",+ "body_hash": "95b31c84d9d7b7ea444175d84695a3d2843e13e7eff34b43ca44d07b028caf3d",+ "summary_state": "ready",+ "summary": "Defines the configuration structure for the engine, allowing customization of various parameters for LLM operations.",+ "crux": {+ "code": "export interface EngineConfig {\n /** Where the graph lives. Env: GRAFT_DIR. Default: `<repo>/.context`. */\n contextDir?: string;\n\n /** Wire format / SDK. Env: GRAFT_PROVIDER. Default: `openai`. */\n provider?: ProviderKind;\n /** API key for the chosen provider. Env: GRAFT_API_KEY (legacy: OPENROUTER_API_KEY). */\n apiKey?: string;\n /** Model id. Env: GRAFT_MODEL. Provider-specific default. */\n model?: string;\n /** Base URL for OpenAI-compatible endpoints. Env: GRAFT_BASE_URL. */\n baseUrl?: string;",+ "span": "L17-L28"+ }+ },+ {+ "id": "src/ai/providers.ts#resolveConfig",+ "name": "resolveConfig",+ "kind": "function",+ "path": "src/ai/providers.ts",+ "span": "L71-L106",+ "signature": "function resolveConfig(config: EngineConfig = {}): ResolvedConfig",+ "exported": true,+ "origin": "ast",+ "body_hash": "117056d5880fd89b165cf3e7f29f4b07091927a10522000eeef02b5094487204",+ "summary_state": "ready",+ "summary": "Merges user-provided configuration with environment variables and defaults to produce a complete configuration object.",+ "crux": {+ "code": "export function resolveConfig(config: EngineConfig = {}): ResolvedConfig {\n const env = process.env;\n const provider = config.provider ?? (env.GRAFT_PROVIDER as ProviderKind | undefined) ?? DEFAULTS.provider;\n\n const explicitKey = config.apiKey ?? env.GRAFT_API_KEY;\n const legacyKey = env.OPENROUTER_API_KEY;\n const apiKey = explicitKey ?? legacyKey;\n const usedLegacyEnv = !explicitKey && !!legacyKey;\n\n const model =\n config.model ?? env.GRAFT_MODEL ?? env.GRAFT_OPENROUTER_MODEL ?? DEFAULT_MODELS[provider];\n",+ "span": "L71-L82"+ }+ },+ {+ "id": "src/ai/providers.ts#ResolvedConfig",+ "name": "ResolvedConfig",+ "kind": "interface",+ "path": "src/ai/providers.ts",+ "span": "L42-L55",+ "signature": "interface ResolvedConfig",+ "exported": true,+ "origin": "ast",+ "body_hash": "1a0d128beff62ecd8c534a4ec9497130a718a2c0bd221a0909be5aa2bb0dccd5",+ "summary_state": "ready",+ "summary": "Represents the fully resolved configuration after merging user settings with defaults and environment variables.",+ "crux": {+ "code": "export interface ResolvedConfig {\n contextDir?: string;\n provider: ProviderKind;\n apiKey?: string;\n model: string;\n baseUrl?: string;\n headers?: Record<string, string>;\n /** True when the key came from the deprecated OPENROUTER_* fallback. */\n usedLegacyEnv: boolean;\n chatModel?: ChatModel;\n synthesizer?: Synthesizer;\n summarizer?: Summarizer;",+ "span": "L42-L53"+ }+ },+ {+ "id": "src/ai/summarize.ts",+ "name": "summarize.ts",+ "kind": "file","path": "src/ai/summarize.ts",- "span": "L41-L48",- "signature": "constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\")",+ "span": "L1-L52",+ "signature": null,"exported": true,"origin": "ast",- "body_hash": "11789569c2566d5187db773c70ebb755e57415aafb4b2d35fd3473dfdfda4958",+ "body_hash": "8dbec8d421f079ec67c81701d28ed1eb648b64e074b338538d03b9063941cffd",+ "chars": 2216,"summary_state": "ready",- "summary": "The constructor initializes the OpenRouterSummarizer with an API key and model for making API calls.",+ "summary": "This file provides functionality to summarize source code files into concise prose for a knowledge graph, enhancing documentation and understanding of codebases.","crux": {- "code": " constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\") {\n this.client = new OpenAI({\n apiKey,\n baseURL: baseUrl,\n defaultHeaders: { \"X-Title\": \"Context Graph Engine\" },\n });\n this.model = model;\n }",- "span": "L41-L48"+ "code": "/**\n * Turns one source-code file into a short prose summary for the knowledge graph.\n *\n * Code repos are deliberately NOT fed through the per-chunk entity extractor:\n * static structure is better served by grep/tree-sitter in the consuming agent,\n * and LLM extraction over raw code produces noisy, duplicated entities. Instead\n * the repo ingest path summarizes each file into plain English (purpose, key\n * exports, dependencies, design decisions) and ingests those summaries — prose\n * the existing extraction pipeline is actually good at.",+ "span": "L3-L11"}},{- "id": "src/ai/summarize.ts#OpenRouterSummarizer.summarize",+ "id": "src/ai/summarize.ts#ChatSummarizer",+ "name": "ChatSummarizer",+ "kind": "class",+ "path": "src/ai/summarize.ts",+ "span": "L37-L51",+ "signature": "class ChatSummarizer implements Summarizer",+ "exported": true,+ "origin": "ast",+ "body_hash": "707835ebd4bbe74cc6720d5b77187fe3dfb7dc02e9487e02aea6614b2f1b2616",+ "summary_state": "ready",+ "summary": "Provides a mechanism to summarize source code files into plain English for knowledge management.",+ "crux": {+ "code": " async summarize(code: string, opts: { path: string }): Promise<string> {\n const res = await this.model.create({\n temperature: 0,\n maxTokens: 2048,\n messages: [\n { role: \"system\", content: SYSTEM_PROMPT },\n { role: \"user\", content: userContent(code, opts.path) },\n ],\n });\n return res.text.trim();\n }",+ "span": "L40-L50"+ }+ },+ {+ "id": "src/ai/summarize.ts#ChatSummarizer.constructor",+ "name": "constructor",+ "kind": "method",+ "path": "src/ai/summarize.ts",+ "span": "L38-L38",+ "signature": "constructor(private model: ChatModel)",+ "exported": true,+ "origin": "ast",+ "body_hash": "01e4b6b8ac3b764e704374f04305b7acdbdfdbf0302ee7b56376849f61358ddb",+ "summary_state": "ready",+ "summary": "Initializes the ChatSummarizer with a specific ChatModel for generating summaries.",+ "crux": null+ },+ {+ "id": "src/ai/summarize.ts#ChatSummarizer.summarize","name": "summarize","kind": "method","path": "src/ai/summarize.ts",- "span": "L50-L60",+ "span": "L40-L50","signature": "async summarize(code: string, opts: { path: string }): Promise<string>","exported": true,"origin": "ast",- "body_hash": "b87a1b9c3fa411f6d60e20f3668c506deaf6675277847809f4da00b7bde5d2b7",+ "body_hash": "248e1cc89ec3a53071dcda5ec005a28b9d698f73af74d4be1d356e0c86334a28","summary_state": "ready",- "summary": "The summarize method generates a summary of the provided code by interacting with the OpenAI API.",+ "summary": "Generates a summary of the provided source code using the specified ChatModel.","crux": {- "code": " const response = await this.client.chat.completions.create({\n model: this.model,\n temperature: 0,\n messages: [\n { role: \"system\", content: SYSTEM_PROMPT },\n { role: \"user\", content: userContent(code, opts.path) },\n ],\n });\n return response.choices[0]?.message?.content?.trim() ?? \"\";",- "span": "L51-L59"+ "code": " const res = await this.model.create({\n temperature: 0,\n maxTokens: 2048,\n messages: [\n { role: \"system\", content: SYSTEM_PROMPT },\n { role: \"user\", content: userContent(code, opts.path) },\n ],\n });\n return res.text.trim();",+ "span": "L41-L49"}},{@@ -1233,102 +1931,99 @@"name": "synthesize.ts","kind": "file","path": "src/ai/synthesize.ts",- "span": "L1-L166",+ "span": "L1-L156","signature": null,"exported": true,"origin": "ast",- "body_hash": "0dcf573a7c4d86b68a4826bd3c6bd31f28e8696654d226669b7eb8052c48f9cf",- "chars": 7673,- "summary_state": "stale",- "summary": "This file defines the architecture for synthesizing a graph of nodes from file summaries, enabling a structured representation of a codebase.",- "crux": {- "code": "const SYSTEM_PROMPT = `You build an ARCHITECTURE graph of a codebase from per-file summaries. The reader is an AI agent that will read this graph before working on the code, so it must describe the system at the level a senior engineer would explain it — not file by file.\n\nProduce a CURATED set of nodes of mixed granularity:\n- \"system\" nodes: GROUP files that collaborate as one component (usually a directory or a cohesive set) into a SINGLE node. This should be the most common node type. Prefer one system node over several file nodes.\n- \"file\" nodes: only for a substantial, standalone module that genuinely deserves its own node apart from its system.\n- \"concept\" nodes: cross-cutting ideas, design decisions, or invariants that span multiple files (e.g. \"local-first provider fallback\", \"staleness checking\", \"content-hash provenance\"). Include several — they are the most valuable nodes for an agent.\n\nRules:\n- Strongly prefer FEWER, larger, meaningful nodes. For a repo of N files, aim for well under N nodes. Do NOT emit one node per file, and never a node per incidental identifier (a local interface, helper, or third-party symbol).\n- Merge duplicates and surface-form variants into one node.\n- For each node give: a canonical human-readable name; a type (\"system\" | \"file\" | \"concept\"); a 1-3 sentence summary of its ROLE in the system; \"sources\" = the exact file paths (from the input) it is grounded in (a system lists all its files; a concept lists the files that motivate it); and \"links\" to other nodes you define, each with a relation and a short description of what concretely happens in the code.\n- The relation MUST be one of exactly these verbs (each answers a question a code reviewer asks): \"part_of\" (where does this live?), \"uses\" (what breaks if the target changes?), \"depends_on\" (same, for non-call dependencies), \"produces\" (where does this output come from?), \"configures\" (what changes its behavior without a code change?), \"validates\" (what checks or judges this? tests, drift checks, scoring), \"implements\" (what contract must this honor?). Never invent vague relations like \"influences\", \"supports\", or \"relates_to\" — if none of the verbs fit, drop the link.",- "span": "L39-L50"- }+ "body_hash": "7c6124323d5112abb15f0adea21962e083ea38234a8771832a71a59350fdc362",+ "chars": 7354,+ "summary_state": "ready",+ "summary": "This file defines the architecture for synthesizing a graph of nodes from file summaries, enabling better understanding and navigation of a codebase.",+ "crux": null},{- "id": "src/ai/synthesize.ts#clean",- "name": "clean",- "kind": "function",+ "id": "src/ai/synthesize.ts#ChatSynthesizer",+ "name": "ChatSynthesizer",+ "kind": "class","path": "src/ai/synthesize.ts",- "span": "L101-L123",- "signature": "function clean(nodes: unknown): SynthNode[]",- "exported": false,+ "span": "L128-L154",+ "signature": "class ChatSynthesizer implements Synthesizer",+ "exported": true,"origin": "ast",- "body_hash": "2344d8c4c88dd2126c437bedfed4688859387f3303ae33aae9a056f42ff7bad8",+ "body_hash": "9e2ef8120d3ee1e281cf57ef553ac5ce7ff0768bf5c7b8bbb8bbcb3f91963db0","summary_state": "ready",- "summary": "Normalizes and cleans a raw model response into a structured array of SynthNode objects.",+ "summary": "The ChatSynthesizer class implements the Synthesizer interface to create a structured architecture graph using a chat model.","crux": {- "code": " if (!Array.isArray(nodes)) return [];\n const out: SynthNode[] = [];\n for (const n of nodes as Array<Record<string, unknown>>) {\n if (!n || typeof n.name !== \"string\" || typeof n.type !== \"string\") continue;\n out.push({\n name: n.name,\n type: n.type,\n summary: typeof n.summary === \"string\" ? n.summary : \"\",\n sources: Array.isArray(n.sources) ? (n.sources as unknown[]).filter((s): s is string => typeof s === \"string\") : [],\n links: Array.isArray(n.links)\n ? (n.links as Array<Record<string, unknown>>)\n .filter((l) => l && typeof l.to === \"string\" && typeof l.relation === \"string\")",- "span": "L101-L112"+ "code": " async synthesize(files: FileSummary[]): Promise<SynthNode[]> {\n if (files.length === 0) return [];\n const res = await this.model.create({\n temperature: 0,\n maxTokens: 8192,\n tools: [\n {\n name: RECORD_TOOL,\n description: \"Record the curated architecture-graph nodes and their links.\",\n parameters: NODES_SCHEMA as unknown as Record<string, unknown>,\n },\n ],",+ "span": "L131-L142"}},{- "id": "src/ai/synthesize.ts#FileSummary",- "name": "FileSummary",- "kind": "interface",+ "id": "src/ai/synthesize.ts#ChatSynthesizer.constructor",+ "name": "constructor",+ "kind": "method","path": "src/ai/synthesize.ts",- "span": "L30-L33",- "signature": "interface FileSummary",+ "span": "L129-L129",+ "signature": "constructor(private model: ChatModel)","exported": true,"origin": "ast",- "body_hash": "4c10af76458e184f8d32e13ead75fdbba2b173af7e915f3b6378f895b64bacff",+ "body_hash": "01e4b6b8ac3b764e704374f04305b7acdbdfdbf0302ee7b56376849f61358ddb","summary_state": "ready",- "summary": "Holds the summary information for a single file, including its path and a descriptive summary.",+ "summary": "The constructor initializes the ChatSynthesizer with a specific chat model for generating architecture graphs.","crux": {- "code": " path: string;\n summary: string;",- "span": "L31-L32"+ "code": " constructor(private model: ChatModel) {}",+ "span": "L129-L129"}},{- "id": "src/ai/synthesize.ts#OpenRouterSynthesizer",- "name": "OpenRouterSynthesizer",- "kind": "class",+ "id": "src/ai/synthesize.ts#ChatSynthesizer.synthesize",+ "name": "synthesize",+ "kind": "method","path": "src/ai/synthesize.ts",- "span": "L135-L164",- "signature": "class OpenRouterSynthesizer implements Synthesizer",+ "span": "L131-L153",+ "signature": "async synthesize(files: FileSummary[]): Promise<SynthNode[]>","exported": true,"origin": "ast",- "body_hash": "8281c93146b94be4f6d884607e02a9fe4d3a48537eb10044253dcdbe5394c8ac",+ "body_hash": "609f7bd1a76c0a6c725b29f63c9103244e87c9a9ff423d76dd739a8cc7329427","summary_state": "ready",- "summary": "Implements the Synthesizer interface using OpenRouter's API to generate nodes from file summaries.",+ "summary": "The synthesize method processes file summaries to produce a curated set of SynthNode objects representing the architecture of the codebase.","crux": {- "code": " async synthesize(files: FileSummary[]): Promise<SynthNode[]> {\n if (files.length === 0) return [];\n const response = await this.client.chat.completions.create({\n model: this.model,\n temperature: 0,\n tools: [RECORD_TOOL],\n tool_choice: { type: \"function\", function: { name: \"record_graph\" } },\n messages: [\n { role: \"system\", content: SYSTEM_PROMPT },\n { role: \"user\", content: userContent(files) },\n ],\n });",- "span": "L143-L154"+ "code": " async synthesize(files: FileSummary[]): Promise<SynthNode[]> {\n if (files.length === 0) return [];\n const res = await this.model.create({\n temperature: 0,\n maxTokens: 8192,\n tools: [\n {\n name: RECORD_TOOL,\n description: \"Record the curated architecture-graph nodes and their links.\",\n parameters: NODES_SCHEMA as unknown as Record<string, unknown>,\n },\n ],",+ "span": "L131-L142"}},{- "id": "src/ai/synthesize.ts#OpenRouterSynthesizer.constructor",- "name": "constructor",- "kind": "method",+ "id": "src/ai/synthesize.ts#clean",+ "name": "clean",+ "kind": "function","path": "src/ai/synthesize.ts",- "span": "L139-L142",- "signature": "constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\")",- "exported": true,+ "span": "L101-L123",+ "signature": "function clean(nodes: unknown): SynthNode[]",+ "exported": false,"origin": "ast",- "body_hash": "20d1ed2a31c60772d22eb649c1eb6d3cb646b80d751cce76eb8e71c6cc3018a6",+ "body_hash": "2344d8c4c88dd2126c437bedfed4688859387f3303ae33aae9a056f42ff7bad8","summary_state": "ready",- "summary": "Initializes the OpenRouterSynthesizer with API key, model, and optional base URL for the OpenAI client.",+ "summary": "Normalizes and cleans a raw model response into a structured array of SynthNode objects.","crux": {- "code": " constructor(apiKey: string, model: string, baseUrl = \"https://openrouter.ai/api/v1\") {\n this.client = new OpenAI({ apiKey, baseURL: baseUrl, defaultHeaders: { \"X-Title\": \"Context Graph Engine\" } });\n this.model = model;\n }",- "span": "L138-L141"+ "code": " if (!Array.isArray(nodes)) return [];\n const out: SynthNode[] = [];\n for (const n of nodes as Array<Record<string, unknown>>) {\n if (!n || typeof n.name !== \"string\" || typeof n.type !== \"string\") continue;\n out.push({\n name: n.name,\n type: n.type,\n summary: typeof n.summary === \"string\" ? n.summary : \"\",\n sources: Array.isArray(n.sources) ? (n.sources as unknown[]).filter((s): s is string => typeof s === \"string\") : [],\n links: Array.isArray(n.links)\n ? (n.links as Array<Record<string, unknown>>)\n .filter((l) => l && typeof l.to === \"string\" && typeof l.relation === \"string\")",+ "span": "L101-L112"}},{- "id": "src/ai/synthesize.ts#OpenRouterSynthesizer.synthesize",- "name": "synthesize",- "kind": "method",+ "id": "src/ai/synthesize.ts#FileSummary",+ "name": "FileSummary",+ "kind": "interface","path": "src/ai/synthesize.ts",- "span": "L144-L163",- "signature": "async synthesize(files: FileSummary[]): Promise<SynthNode[]>",+ "span": "L30-L33",+ "signature": "interface FileSummary","exported": true,"origin": "ast",- "body_hash": "f1b94e63417194a18be9062aa3f46838f9c92d65231ceea54d554ecc2aadc767",+ "body_hash": "4c10af76458e184f8d32e13ead75fdbba2b173af7e915f3b6378f895b64bacff","summary_state": "ready",- "summary": "Processes an array of file summaries to produce a structured array of SynthNode objects by interacting with the OpenAI API.",+ "summary": "Holds the summary information for a single file, including its path and a descriptive summary.","crux": {- "code": " if (files.length === 0) return [];\n const response = await this.client.chat.completions.create({\n model: this.model,\n temperature: 0,\n tools: [RECORD_TOOL],\n tool_choice: { type: \"function\", function: { name: \"record_graph\" } },\n messages: [\n { role: \"system\", content: SYSTEM_PROMPT },\n { role: \"user\", content: userContent(files) },\n ],\n });\n const call = response.choices[0]?.message?.tool_calls?.[0];",- "span": "L144-L155"+ "code": " path: string;\n summary: string;",+ "span": "L31-L32"}},{@@ -1407,9 +2102,12 @@"origin": "ast","body_hash": "62d693c39f77019e50437b5285fafe5802b8b077e7aa6545589a3b084f93e552","chars": 32834,- "summary_state": "stale",- "summary": "This file implements a query tool that routes natural language queries to relevant code symbols and returns structured context information.",- "crux": null+ "summary_state": "ready",+ "summary": "This module provides a mechanism to process natural language queries and return structured results from a codebase, enhancing the ability to find relevant code snippets and their relationships.",+ "crux": {+ "code": "function structural(query: string, graph: GraphV1, limit: number): StructuralOutcome {\n const wantsIn = INCOMING.test(query);\n const wantsOut = OUTGOING.test(query);\n if (!wantsIn && !wantsOut) return null;\n\n const { nodes: subjects, tried } = findSubjectNodes(query, graph);\n if (subjects.length === 0) return { fallthroughNote: fallthroughNoteFor(tried) };\n\n const ids = new Set(subjects.map((n) => n.id));\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const outgoing = wantsOut && !wantsIn; // \"what does X call / import\" — else default to callers\n const rels = new Set(outgoing ? OUTGOING_RELS : INCOMING_RELS);",+ "span": "L230-L241"+ }},{"id": "src/ask/ask.ts#ask",@@ -1421,11 +2119,11 @@"exported": true,"origin": "ast","body_hash": "a9f712f1764f9391acc161a721d4c4f944f728cb4d0df2e602126460d3321cd7",- "summary_state": "stale",- "summary": "Processes a query against a code graph, returning structured results based on the query type and context.",+ "summary_state": "ready",+ "summary": "Handles the main logic for processing a query against a directory, returning structured results based on the query type.","crux": {- "code": " const s = structural(query, corpus.graph, limit);\n result = s ?? lexical(query, corpus, limit);",- "span": "L298-L299"+ "code": "export function ask(dir: string, query: string, opts: AskOptions = {}): AskResult {\n const root = resolve(dir);\n const outDir = contextDirFor(root, opts.contextDir);\n const limit = opts.limit ?? 8;\n const corpus = loadCorpus(outDir);\n const graphRank = opts.graphRank ?? true;\n\n let result: AskResult;\n if (corpus.graph) {\n const outcome = structural(query, corpus.graph, limit);\n if (outcome && \"result\" in outcome) {\n result = outcome.result;",+ "span": "L592-L603"}},{@@ -1452,9 +2150,12 @@"exported": true,"origin": "ast","body_hash": "e43e59155824acff2cc2bc06107314506a521eba1579a9a04af4875e4736ed57",- "summary_state": "stale",- "summary": "Defines options for customizing the behavior of the ask function, such as context directory and result limits.",- "crux": null+ "summary_state": "ready",+ "summary": "Defines the options available for configuring the ask function, allowing customization of its behavior.",+ "crux": {+ "code": "export interface AskOptions {\n contextDir?: string;\n limit?: number;\n /** Inline the source at each `path:Lx-Ly` hit, sliced from `dir`. Turns the\n * pack from a locator into a retriever so the agent needn't re-open the file. */\n source?: boolean;\n /** Re-rank lexical hits by graph connectivity (personalized PageRank over the\n * wiring edges), demoting same-word collisions and rescuing strongly-connected\n * neighbours the query didn't name. On by default; set false for pure lexical. */\n graphRank?: boolean;\n /** With `source`: inline each hit's WHOLE definition span (capped at\n * {@link MAX_SPAN_LINES}) instead of the default crux-first slice. The",+ "span": "L489-L500"+ }},{"id": "src/ask/ask.ts#AskResult",@@ -1466,9 +2167,12 @@"exported": true,"origin": "ast","body_hash": "4c4d6302e47ed2207bf8ea2e976f97386aaac0470d987fe0203790fe796593d5",- "summary_state": "stale",- "summary": "Encapsulates the result of a query, including the query string, mode of operation, and the hits found.",- "crux": null+ "summary_state": "ready",+ "summary": "Represents the result of an 'ask' query, encapsulating the query details and the hits found.",+ "crux": {+ "code": "export interface AskResult {\n query: string;\n mode: \"structural\" | \"lexical\" | \"empty\";\n /** For structural mode: the symbol whose neighbours we walked. */\n subject?: string;\n hits: AskHit[];\n note?: string;\n /** Token-saving estimate, set only in `--source` (retriever) mode: the whole\n * size of the distinct files these hits point into, i.e. the baseline cost of\n * reading them instead of this pack. Computed from file sizes stored at build. */\n saved?: { files: number; baselineChars: number };\n /** Lexical mode only: share (0..1) of the query's distinct terms the TOP hit",+ "span": "L45-L56"+ }},{"id": "src/ask/ask.ts#baselineFor",@@ -1480,9 +2184,12 @@"exported": false,"origin": "ast","body_hash": "72fb36d83f07af995f68449fa92d57766850ea34ff5644a0a09dde44e0f19ae2",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the baseline file size and character count for the hits, providing a measure of the cost of reading the full files.",+ "crux": {+ "code": "function baselineFor(hits: AskHit[], graph: GraphV1 | null): AskResult[\"saved\"] | undefined {\n if (!graph) return undefined;\n const size = new Map<string, number>();\n for (const n of graph.nodes)\n if (n.kind === \"file\" && typeof n.chars === \"number\") size.set(n.path, n.chars);\n\n let baselineChars = 0;\n let files = 0;\n for (const path of hitFiles(hits)) {\n const c = size.get(path);\n if (c === undefined) continue;\n baselineChars += c;",+ "span": "L574-L585"+ }},{"id": "src/ask/ask.ts#bm25",@@ -1494,9 +2201,12 @@"exported": false,"origin": "ast","body_hash": "8e22c96440f87456feecde97f0e10c924ef34f8634216d0ae6c3a562a42dc039",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Implements the BM25 scoring algorithm to rank documents based on term frequency and document length.",+ "crux": {+ "code": "function bm25(\n query: Map<string, number>,\n doc: Map<string, number>,\n idf: Map<string, number>,\n dl: number,\n avgdl: number,\n): number {\n const k1 = 1.2;\n const b = 0.75;\n const norm = k1 * (1 - b + (b * dl) / (avgdl || 1));\n let s = 0;\n for (const t of query.keys()) {",+ "span": "L166-L177"+ }},{"id": "src/ask/ask.ts#computeIdf",@@ -1508,9 +2218,12 @@"exported": false,"origin": "ast","body_hash": "5d59d7e73b63c473b62ab741265b168865d8174d1172cc9e534d23147440b4b4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates IDF values from document bags, which are used to weight query matches based on term rarity.",+ "crux": {+ "code": "function computeIdf(docBags: Array<Set<string>>): Map<string, number> {\n const df = new Map<string, number>();\n for (const bag of docBags)\n for (const t of bag) df.set(t, (df.get(t) ?? 0) + 1);\n return idfFromDf(df, docBags.length);\n}",+ "span": "L140-L145"+ }},{"id": "src/ask/ask.ts#computeIdfFromIndex",@@ -1521,10 +2234,13 @@"signature": "function computeIdfFromIndex(index: AskIndex, conceptBags: Array<Set<string>>): Map<string, number>","exported": false,"origin": "ast",- "body_hash": "cc84ad53f5e0dab091309c87c15652d661faec9f4237e267ba1d2acc51bad9b3",- "summary_state": "pending",- "summary": null,- "crux": null+ "body_hash": "cc84ad53f5e0dab091309c87c15652d661faec9f4237e267ba1d2acc51bad9b3",+ "summary_state": "ready",+ "summary": "Calculates IDF values using precomputed index data, optimizing the scoring process for queries.",+ "crux": {+ "code": "function computeIdfFromIndex(index: AskIndex, conceptBags: Array<Set<string>>): Map<string, number> {\n const df = new Map(index.df);\n for (const bag of conceptBags)\n for (const t of bag) df.set(t, (df.get(t) ?? 0) + 1);\n return idfFromDf(df, index.docCount + conceptBags.length);\n}",+ "span": "L154-L159"+ }},{"id": "src/ask/ask.ts#Corpus",@@ -1536,9 +2252,12 @@"exported": false,"origin": "ast","body_hash": "447d1a3c8c6b46c599acb70ea56a6ebad5eefcb17a849187c5aa2b364eb85d5d",- "summary_state": "stale",- "summary": "Defines the structure for a corpus containing concepts and a graph, used for processing queries.",- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for holding concepts and graph data used in processing queries.",+ "crux": {+ "code": "interface Corpus {\n concepts: Array<{ slug: string; name: string; sources: string[]; related: string[]; snippet: string; text: string }>;\n graph: GraphV1 | null;\n /** Build-time token/df sidecar (`.cache/ask-index.json`), or null when absent,\n * unparseable, an unknown version, or stale (checked against `graph.nodes.length`\n * by the caller — see `lexical()`). Null means: fall back to live tokenization. */\n askIndex: AskIndex | null;\n}",+ "span": "L74-L81"+ }},{"id": "src/ask/ask.ts#fallthroughNoteFor",@@ -1550,9 +2269,12 @@"exported": false,"origin": "ast","body_hash": "8894dd2788429383684ba0a325296c7fd8e11865a5fbb7d1fdadc45f4c99ab23",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a note for cases where a structural query falls back to lexical processing, providing user guidance.",+ "crux": {+ "code": "function fallthroughNoteFor(subject: string): string {\n return (\n `structural index: no entries for '${subject}' — showing lexical matches; ` +\n `for exhaustive callers use grep -rn '${subject}'`\n );\n}",+ "span": "L223-L228"+ }},{"id": "src/ask/ask.ts#findSubjectNodes",@@ -1564,9 +2286,12 @@"exported": false,"origin": "ast","body_hash": "0a3f88de2d856cea23e66fd4d8ad75220907ec8ddc44e69a3bf853b37ea113f3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Finds nodes in the graph that match the structural subject of a query, enhancing query resolution.",+ "crux": {+ "code": "function findSubjectNodes(query: string, graph: GraphV1): { nodes: NodeV1[]; tried: string } {\n const words = subjectWords(query).sort((a, b) => b.length - a.length);\n for (const w of words) {\n const nodes = resolveSymbol(graph, w);\n if (nodes.length > 0) return { nodes, tried: w };\n }\n return { nodes: [], tried: words[0] ?? query };\n}",+ "span": "L206-L213"+ }},{"id": "src/ask/ask.ts#firstProse",@@ -1595,11 +2320,11 @@"exported": true,"origin": "ast","body_hash": "413023c3201e82617c165c0ddf39bf37f4e963b7d5c1af202ff4f7132191f8ae",- "summary_state": "stale",- "summary": "Formats the results of a query into a markdown context pack for easy readability and presentation.",+ "summary_state": "ready",+ "summary": "Formats the results of an ask query into a string for presentation, ensuring clarity and usability.","crux": {- "code": "export function formatAsk(r: AskResult): string {\n const head = `graft ask — \"${r.query}\" (${r.mode}${r.note ? `: ${r.note}` : \"\"})`;\n if (r.hits.length === 0) {\n return `${head}\\n\\n${r.note ?? \"no matches.\"}`;\n }\n const lines = [head, \"\"];\n if (r.mode === \"structural\") {\n for (const h of r.hits) {\n const tail = h.snippet ? ` — ${h.snippet}` : \"\";\n lines.push(`- ${h.title} ${h.pointer} (${h.relation})${tail}`);\n if (h.code) lines.push(\"\", \"```\", h.code, \"```\", \"\");\n }",- "span": "L308-L319"+ "code": "export function formatAsk(r: AskResult): string {\n const head = `graft ask — \"${r.query}\" (${r.mode})`;\n // The note prints as its own prominent line(s) right under the header —\n // above every hit — so a loud structural-fallthrough note (or the\n // no-structural-edges / no-lexical-match note) can never be missed by only\n // being embedded inline in the header parenthetical. Only a genuine\n // fallthrough/warning line (from `fallthroughNoteFor`, always prefixed\n // \"structural index:\") gets the ⚠ marker; the benign structural header note\n // (\"callers / references of X\" / \"outgoing edges from X\") prints plain —\n // it's informational, not a warning.\n const noteBlock = r.note\n ? r.note",+ "span": "L693-L704"}},{@@ -1612,9 +2337,12 @@"exported": true,"origin": "ast","body_hash": "959580717569409d09522b36316a884d13fc49702fdd4aa9b55b7d534afdc0fc",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats the skeleton result into a string representation for display or output purposes.",+ "crux": {+ "code": "export function formatSkeleton(r: SkeletonResult): string {\n const head = `graft skeleton — ${r.file}`;\n if (!r.entries.length) return `${head}\\n\\n${r.note ?? \"no definitions.\"}\\n`;\n const lines = r.entries.map((e) => {\n const sig = e.signature ? ` ${e.signature}` : \"\";\n const sum = e.summary ? ` — ${e.summary}` : \"\";\n return `- ${e.span} ${e.kind} ${e.name}${sig}${sum}`;\n });\n return `${head}\\n${lines.join(\"\\n\")}\\n`;\n}",+ "span": "L676-L685"+ }},{"id": "src/ask/ask.ts#hasTerm",@@ -1626,9 +2354,12 @@"exported": false,"origin": "ast","body_hash": "fc67bfbddd84c204744457e940d090b6c90985539a1c4cdf713f69d6a92b5c37",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Checks for the presence of a term in a document's token map, aiding in relevance scoring.",+ "crux": {+ "code": "function hasTerm(f: Map<string, number>, t: string): boolean {\n return f.has(t) || f.has(`${t}s`) || (t.endsWith(\"s\") && f.has(t.slice(0, -1)));\n}",+ "span": "L298-L300"+ }},{"id": "src/ask/ask.ts#hitFiles",@@ -1640,9 +2371,12 @@"exported": false,"origin": "ast","body_hash": "51b7d4fbb4e2ea5979c8e8b308c7158ad764595538ee72714f4aa2f93d5ee89b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts a set of unique file paths from the hits, indicating which files are relevant to the query results.",+ "crux": {+ "code": "function hitFiles(hits: AskHit[]): Set<string> {\n const files = new Set<string>();\n for (const h of hits) {\n const span = parseSpan(h.pointer);\n if (span) { files.add(span.path); continue; }\n for (const p of h.pointer.split(\",\").map((s) => s.trim()))\n if (p && !p.includes(\" \")) files.add(p);\n }\n return files;\n}",+ "span": "L560-L569"+ }},{"id": "src/ask/ask.ts#idfFromDf",@@ -1654,9 +2388,12 @@"exported": false,"origin": "ast","body_hash": "6e08a73cec05cbac1943acd2d2c588c901fb1e84327aced754012931f7bc5ed1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Computes the inverse document frequency (IDF) from document frequency (DF) data, aiding in scoring relevance.",+ "crux": {+ "code": "function idfFromDf(df: Map<string, number>, n: number): Map<string, number> {\n const idf = new Map<string, number>();\n for (const [t, d] of df) idf.set(t, Math.log(1 + n / (1 + d)));\n return idf;\n}",+ "span": "L134-L138"+ }},{"id": "src/ask/ask.ts#inlineSource",@@ -1668,11 +2405,11 @@"exported": false,"origin": "ast","body_hash": "41579c388276225af6b3ceab098eb0d7817f706b0885aeb1a82c4fb27624e9dd",- "summary_state": "stale",- "summary": "Attaches inlined source code to query hits, enhancing the context provided to the user.",+ "summary_state": "ready",+ "summary": "Inlines the source code for the hits found, providing context directly in the results without needing to open files.","crux": {- "code": "function inlineSource(root: string, hits: AskHit[]): void {\n for (const h of hits) {\n const s = parseSpan(h.pointer);\n if (!s) continue;\n const code = sliceSpan(root, s.path, s.from, s.to);\n if (code) h.code = code;\n }",- "span": "L280-L286"+ "code": "function inlineSource(root: string, hits: AskHit[], graph: GraphV1 | null, full: boolean): void {\n const cruxByPointer = new Map<string, string>();\n if (!full && graph) {\n for (const n of graph.nodes)\n if (n.crux?.code) cruxByPointer.set(`${n.path}:${n.span}`, n.crux.code);\n }\n for (const h of hits) {\n const s = parseSpan(h.pointer);\n if (!s) continue;\n const crux = cruxByPointer.get(h.pointer);\n if (crux) {\n h.code = `${crux}\\n… (crux — full definition at ${h.pointer}; rerun with --full)`;",+ "span": "L539-L550"}},{@@ -1685,11 +2422,11 @@"exported": false,"origin": "ast","body_hash": "407d174feaf3c69d35c15459e96cb9c0e184097237970ecf6ec87b0e2a4e6fdd",- "summary_state": "stale",- "summary": "Ranks concepts and symbols based on lexical matching with the query, returning the most relevant results.",+ "summary_state": "ready",+ "summary": "Handles lexical queries by scoring documents based on term matches and relevance, returning structured results.","crux": {- "code": "function lexical(query: string, corpus: Corpus, limit: number): AskResult {\n const q = counts(tokenize(query));\n const scored: AskHit[] = [];\n\n for (const c of corpus.concepts) {\n const nameScore = score(q, counts(tokenize(c.name))) * 3;\n const bodyScore = score(q, counts(tokenize(c.text)));\n const total = nameScore + bodyScore;\n if (total > 0) {\n scored.push({\n kind: \"concept\",\n title: c.name || c.slug,",- "span": "L190-L201"+ "code": "function lexical(query: string, corpus: Corpus, limit: number, graphRank: boolean): AskResult {\n // Binary query terms: a word repeated in a pasted issue body counts once, so a\n // ranty description can't linearly amplify an incidental word.\n const q = new Map([...counts(tokenize(query)).keys()].map((t) => [t, 1]));\n const graph = corpus.graph;\n\n // ── Pass 1: tokenize every scored field once, and collect per-document token\n // bags so IDF can down-weight words that occur across the whole corpus. ──\n const conceptDocs = corpus.concepts.map((c) => ({\n c,\n name: counts(tokenize(c.name)),\n body: counts(tokenize(c.text)),",+ "span": "L325-L336"}},{@@ -1702,9 +2439,12 @@"exported": false,"origin": "ast","body_hash": "79442ce15d0955c8c21add8fdebb6c22462136c2b241e8e60ea75313d1097259",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the length of the body of a lexical document to ensure it meets certain criteria for processing.",+ "crux": {+ "code": " const bodyLen = (m: Map<string, number>) => {\n let s = 0;\n for (const v of m.values()) s += v;\n return s;\n };",+ "span": "L416-L420"+ }},{"id": "src/ask/ask.ts#loadCorpus",@@ -1716,11 +2456,11 @@"exported": false,"origin": "ast","body_hash": "af968cfe7454eca7769fa907cf30435ab4e4d9a38b1df4a924c3e261b1ea058d",- "summary_state": "stale",- "summary": "Loads a corpus from a specified directory, extracting concepts and building a graph for query processing.",+ "summary_state": "ready",+ "summary": "Loads a corpus of concepts and graph data from a specified directory, enabling query processing.","crux": {- "code": " const snippet = firstProse(parsed.content);\n concepts.push({\n slug: String(fm.slug ?? entry.replace(/\\.md$/, \"\")),\n name: String(fm.name ?? \"\"),\n sources,\n related,\n snippet,\n text: `${fm.name ?? \"\"} ${snippet} ${sources.join(\" \")}`,\n });",- "span": "L93-L101"+ "code": "function loadCorpus(outDir: string): Corpus {\n const concepts: Corpus[\"concepts\"] = [];\n if (existsSync(outDir)) {\n for (const entry of readdirSync(outDir)) {\n if (!entry.endsWith(\".md\") || entry === \"INDEX.md\") continue;\n const parsed = matter(readFileSync(join(outDir, entry), \"utf8\"));\n const fm = parsed.data as Record<string, unknown>;\n const sources = Array.isArray(fm.sources)\n ? (fm.sources as Array<{ path: string }>).map((s) => s.path)\n : [];\n const related = Array.isArray(fm.links)\n ? (fm.links as Array<{ to: string }>).map((l) => l.to)",+ "span": "L83-L94"}},{@@ -1733,9 +2473,12 @@"exported": false,"origin": "ast","body_hash": "93bb9c0ed85fc1574471b01dd1590d29f56829f7f848725be080ff45865f5477",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the share of query terms matched by a document, weighted by term rarity for relevance assessment.",+ "crux": {+ "code": "function matchedIdfShare(\n q: Map<string, number>,\n fields: Array<Map<string, number>>,\n idf: Map<string, number>,\n dfltIdf: number,\n): number {\n let matched = 0;\n let total = 0;\n for (const t of q.keys()) {\n const w = idf.get(t) ?? dfltIdf;\n total += w;\n if (fields.some((f) => hasTerm(f, t))) matched += w;",+ "span": "L309-L320"+ }},{"id": "src/ask/ask.ts#parseSpan",@@ -1764,9 +2507,12 @@"exported": false,"origin": "ast","body_hash": "343954821ba1b41301acd0788cd9e648cd4aa44d498a57028a52d290d97de7c5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a footer for the ask results that summarizes the savings in terms of file reading costs.",+ "crux": {+ "code": "function savingsFooter(r: AskResult, body: string): string {\n if (!r.saved || r.saved.baselineChars <= 0) return \"\";\n const pack = toTokens(body.length);\n const base = toTokens(r.saved.baselineChars);\n if (base <= pack) return \"\"; // no saving to claim (tiny files); stay quiet\n const saved = base - pack;\n const pct = Math.round((saved / base) * 100);\n return (\n `\\n\\n[graft] tokens saved ≈ ${saved.toLocaleString()} (${pct}%) — this pack ≈ ` +\n `${pack.toLocaleString()} tok vs reading the ${r.saved.files} source file(s) whole ≈ ` +\n `${base.toLocaleString()} tok. Estimate (baseline = those files read in full).`\n );",+ "span": "L736-L747"+ }},{"id": "src/ask/ask.ts#score",@@ -1778,11 +2524,11 @@"exported": false,"origin": "ast","body_hash": "2072a594183410910a338bd797387b8e6f7d832270aea7037ffad9b397e150d8",- "summary_state": "stale",- "summary": "Calculates a score for a document's token counts against a query, facilitating relevance ranking.",+ "summary_state": "ready",+ "summary": "Calculates a score for a document based on its token counts relative to a query, enhancing relevance ranking.","crux": {- "code": "function score(query: Map<string, number>, doc: Map<string, number>): number {\n let s = 0;\n for (const [t, qn] of query) {\n const dn = doc.get(t);\n if (dn) s += qn * dn;\n }\n return s;",- "span": "L108-L114"+ "code": "function score(\n query: Map<string, number>,\n doc: Map<string, number>,\n idf: Map<string, number>,\n): number {\n let s = 0;\n for (const [t, qn] of query) {\n const dn = doc.get(t);\n if (dn) s += qn * dn * (idf.get(t) ?? 1);\n }\n return s;\n}",+ "span": "L117-L128"}},{@@ -1795,9 +2541,12 @@"exported": true,"origin": "ast","body_hash": "dce0b973c651c9f800712f6a2ab2fb09cb21f9fb943d36f0b15bc6286c02b8f7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts a skeleton representation of a file, providing a summary and context for its contents.",+ "crux": {+ "code": "export function skeleton(dir: string, file: string, opts: { contextDir?: string } = {}): SkeletonResult {\n const outDir = contextDirFor(resolve(dir), opts.contextDir);\n const graph = loadGraphCached(outDir);\n if (!graph) return { file, entries: [], note: \"no wiring graph — run `graft build` first\" };\n\n let defs = graph.nodes.filter((n) => n.kind !== \"file\" && n.path === file);\n if (!defs.length) {\n const matches = new Set(\n graph.nodes.filter((n) => n.path === file || n.path.endsWith(`/${file}`)).map((n) => n.path),\n );\n if (matches.size > 1)\n return { file, entries: [], note: `ambiguous — matches: ${[...matches].sort().join(\", \")}` };",+ "span": "L644-L655"+ }},{"id": "src/ask/ask.ts#skeleton.startLine",@@ -1809,9 +2558,12 @@"exported": true,"origin": "ast","body_hash": "84d2fbc9874f1ef387f00598a55b3d677f8cb91f237fd7763887375557cbde35",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the starting line number from a given span, aiding in the extraction of relevant code sections.",+ "crux": {+ "code": " const startLine = (span: string) => Number(span.match(/^L(\\d+)/)?.[1] ?? 0);",+ "span": "L661-L661"+ }},{"id": "src/ask/ask.ts#SkeletonEntry",@@ -1823,9 +2575,12 @@"exported": true,"origin": "ast","body_hash": "97e65aa8f777a7c35743f802f99b11c49914bb5d94d43fe15bd643fb7ac7c776",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure of a skeleton entry, which represents a piece of information extracted from a file.",+ "crux": {+ "code": "export interface SkeletonEntry {\n name: string;\n kind: string;\n span: string;\n signature: string | null;\n /** First line of the Tier-2 summary, when the node has one. */\n summary?: string;\n}",+ "span": "L626-L633"+ }},{"id": "src/ask/ask.ts#SkeletonResult",@@ -1837,9 +2592,12 @@"exported": true,"origin": "ast","body_hash": "852555fd408bd54eca9e183234e6d6d89e02e58efa4f3c180e93d1641febe36c",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure of the result returned from the skeleton function, encapsulating the extracted information.",+ "crux": {+ "code": "export interface SkeletonResult {\n file: string;\n entries: SkeletonEntry[];\n note?: string;\n}",+ "span": "L635-L639"+ }},{"id": "src/ask/ask.ts#sliceSpan",@@ -1868,11 +2626,11 @@"exported": false,"origin": "ast","body_hash": "882a1b72a392c807907ef0e0f699a41d2f69dacacb713a0597b310d964f5fd30",- "summary_state": "stale",- "summary": "Processes a structural query to find and return relevant callers or callees from the graph based on the query.",+ "summary_state": "ready",+ "summary": "Processes a structural query to find relationships in the graph, returning relevant results or fallthrough notes.","crux": {- "code": " if (!wantsIn && !wantsOut) return null;\n\n const subjects = findSubject(query, graph);\n if (subjects.length === 0) return null;\n\n const ids = new Set(subjects.map((n) => n.id));\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const outgoing = wantsOut && !wantsIn; // \"what does X call / import\" — else default to callers\n const rels = new Set(outgoing ? OUTGOING_RELS : INCOMING_RELS);\n\n const hits: AskHit[] = [];\n const seen = new Set<string>();",- "span": "L148-L159"+ "code": "function structural(query: string, graph: GraphV1, limit: number): StructuralOutcome {\n const wantsIn = INCOMING.test(query);\n const wantsOut = OUTGOING.test(query);\n if (!wantsIn && !wantsOut) return null;\n\n const { nodes: subjects, tried } = findSubjectNodes(query, graph);\n if (subjects.length === 0) return { fallthroughNote: fallthroughNoteFor(tried) };\n\n const ids = new Set(subjects.map((n) => n.id));\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const outgoing = wantsOut && !wantsIn; // \"what does X call / import\" — else default to callers\n const rels = new Set(outgoing ? OUTGOING_RELS : INCOMING_RELS);",+ "span": "L230-L241"}},{@@ -1885,9 +2643,12 @@"exported": false,"origin": "ast","body_hash": "628e17efd7be8fc7e319d1f0a5a1284ead0b1630ed037560382c6b21e362720f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the possible outcomes of a structural query, indicating whether a result was found, a fallthrough note is needed, or if there was no structural intent.",+ "crux": {+ "code": "type StructuralOutcome = { result: AskResult } | { fallthroughNote: string } | null;",+ "span": "L221-L221"+ }},{"id": "src/ask/ask.ts#subjectWords",@@ -1899,9 +2660,12 @@"exported": false,"origin": "ast","body_hash": "18d4993f0e015fe413d7acd6650f40c85effd40e22ed376b19223c939c6a9d0b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Tokenizes a query into words while preserving qualified names, facilitating accurate subject resolution.",+ "crux": {+ "code": "function subjectWords(query: string): string[] {\n return [...new Set(query.split(/[^A-Za-z0-9_.]+/).filter(Boolean))];\n}",+ "span": "L194-L196"+ }},{"id": "src/ask/ask.ts#toTokens",@@ -1913,9 +2677,12 @@"exported": false,"origin": "ast","body_hash": "c309fa8bd0227742b657331eb45be3225e5a5efc56b1967871624df6c83ab954",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Converts a character count into a token count, facilitating the processing of text for queries.",+ "crux": {+ "code": "function toTokens(chars: number): number {\n return Math.round(chars / 4);\n}",+ "span": "L688-L690"+ }},{"id": "src/ask/graphrank.ts",@@ -1928,9 +2695,12 @@"origin": "ast","body_hash": "a8dfba7907ce7fea84669ddf9ca20f14392b7d1edb5b76db0acf522465078cd5","chars": 4125,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This module implements a personalized PageRank algorithm to improve the ranking of code nodes based on their structural relevance rather than just lexical similarity.",+ "crux": {+ "code": " * This module runs personalized PageRank (random-walk-with-restart) over the\n * wiring graph, seeded by the lexical scores. Mass concentrates on nodes that\n * are edge-connected to the matched set; a lexically-matched but structurally\n * isolated node keeps only its own restart mass and sinks. \"Lexical proposes,\n * graph disposes.\" Deterministic, $0, no embeddings — a lexical-seed →\n * graph-rank pipeline, the established alternative to vector search for code.",+ "span": "L10-L15"+ }},{"id": "src/ask/graphrank.ts#PageRankOptions",@@ -1942,8 +2712,8 @@"exported": true,"origin": "ast","body_hash": "214701bc4bff2de310654c772007fffb60595fa79289cec6d08de2bd084e6ebc",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines options for configuring the personalized PageRank algorithm, including restart probability and iteration count.","crux": null},{@@ -1956,9 +2726,12 @@"exported": true,"origin": "ast","body_hash": "9047817eb293e393448f4c82571e0ac123573245583ec00ede7f9c621cda982d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates personalized PageRank scores for nodes in a wiring graph based on provided seeds, enhancing the relevance of code suggestions.",+ "crux": {+ "code": " let rank = new Map(restart);\n for (let i = 0; i < iters; i++) {\n const next = new Map<string, number>();\n // Teleport: every step, alpha of the mass returns to the seed set.\n for (const [id, r] of restart) next.set(id, alpha * r);\n // Dangling mass (nodes with no walk edges) is pooled and returned to the\n // seed set ONCE per iteration — same math as redistributing per node, but\n // O(nodes + seeds) instead of O(dangling × seeds).\n let dangling = 0;\n for (const [id, mass] of rank) {\n const nbrs = adj.get(id);\n if (!nbrs || nbrs.length === 0) {",+ "span": "L70-L81"+ }},{"id": "src/ask/graphrank.ts#personalizedPageRank.link",@@ -1970,8 +2743,8 @@"exported": true,"origin": "ast","body_hash": "b76de11ee0fe0076e0901d2e5abc1ac27dfd56c3a8902d3314b7408902316269",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Creates undirected links between nodes in the graph for the PageRank calculation, ensuring that both directions are considered.","crux": null},{@@ -1985,9 +2758,12 @@"origin": "ast","body_hash": "8250b5189d515c4e4bf1573c4c44c96563e121c944951c5f16029c62da62d854","chars": 5977,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file provides functionality for building and reading a cache of tokenized graph data to optimize query performance.",+ "crux": {+ "code": "/**\n * Build-time sidecar for `graft ask` — `<outDir>/.cache/ask-index.json`.\n *\n * `ask`'s lexical pass tokenizes every symbol node's name/path/body on every\n * query; at 32k nodes that re-tokenization is ~45% of query time (profiled).\n * `graft build` writes this sidecar once, with the token→count bags per node\n * plus the corpus-wide document frequencies, so a query just reads counts\n * instead of re-splitting every node's text. It's a derived cache, not\n * checked-in graph data, so it lives under the gitignored `.cache/` dir\n * (see `CACHE_DIR` in `context/node-file.ts`) rather than `.graph/`.\n *\n * `tokenize`/`counts` live here (not duplicated in `ask.ts`) so build-time and",+ "span": "L1-L12"+ }},{"id": "src/ask/index-file.ts#AskIndex",@@ -1999,9 +2775,12 @@"exported": true,"origin": "ast","body_hash": "a6e5978285b47baf6dc2f857106f65dccb472c8262d8c673600206666af5f7ed",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Represents the overall structure of the ask index, including document frequencies and average body length for efficient querying.",+ "crux": {+ "code": "export interface AskIndex {\n version: 1;\n avgBodyLen: number;\n df: [string, number][];\n docCount: number;\n docs: AskIndexDoc[];\n}",+ "span": "L63-L69"+ }},{"id": "src/ask/index-file.ts#AskIndexDoc",@@ -2013,9 +2792,12 @@"exported": true,"origin": "ast","body_hash": "4e6b189863bc6614aef60491ea5931414251bad599c5c38783ad4c875a080dda",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for storing token bags associated with a single document in the index.",+ "crux": {+ "code": "export interface AskIndexDoc {\n id: string;\n name: [string, number][];\n path: [string, number][];\n body: [string, number][];\n}",+ "span": "L54-L59"+ }},{"id": "src/ask/index-file.ts#askIndexPath",@@ -2027,9 +2809,12 @@"exported": true,"origin": "ast","body_hash": "b16433d7a4366a73ec33bb76fb8e13cdd0039de0c6a783a8b9605f355a7c0dfb",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates the absolute file path for the ask index sidecar based on the output directory.",+ "crux": {+ "code": "export function askIndexPath(outDir: string): string {\n return join(outDir, CACHE_DIR, ASK_INDEX_FILE);\n}",+ "span": "L76-L78"+ }},{"id": "src/ask/index-file.ts#bagLen",@@ -2041,9 +2826,12 @@"exported": false,"origin": "ast","body_hash": "fa14c4dc1e7bf2f6a06307dbb18890b7973992df221f4b26c67d04db640beb0c",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the total count of tokens in a document's field, representing its length.",+ "crux": {+ "code": "function bagLen(p: [string, number][]): number {\n let s = 0;\n for (const [, c] of p) s += c;\n return s;\n}",+ "span": "L85-L89"+ }},{"id": "src/ask/index-file.ts#counts",@@ -2055,9 +2843,12 @@"exported": true,"origin": "ast","body_hash": "55edb54385b8591bd6442f62f998d9d774eda8c15abd3e368e4b3a8086c84112",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Counts the frequency of each token in a given array, facilitating the creation of term-frequency maps for documents.",+ "crux": {+ "code": "export function counts(tokens: string[]): Map<string, number> {\n const m = new Map<string, number>();\n for (const t of tokens) m.set(t, (m.get(t) ?? 0) + 1);\n return m;\n}",+ "span": "L47-L51"+ }},{"id": "src/ask/index-file.ts#pairs",@@ -2069,9 +2860,12 @@"exported": false,"origin": "ast","body_hash": "0b366a6cb13cf1c9f4cdc8bcccf3bc270b8793f08059c793dbd93ccf1dbf5fe6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Converts a Map of token counts into a sorted array format suitable for JSON serialization.",+ "crux": {+ "code": "function pairs(m: Map<string, number>): [string, number][] {\n return [...m.entries()];\n}",+ "span": "L80-L82"+ }},{"id": "src/ask/index-file.ts#readAskIndex",@@ -2083,9 +2877,12 @@"exported": true,"origin": "ast","body_hash": "4aa57e86253c4dd7399383853778796baa43ba33801164808b86841d16d7612d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reads and validates the ask index from a file, ensuring data integrity before use in queries.",+ "crux": {+ "code": "export function readAskIndex(outDir: string): AskIndex | null {\n const path = askIndexPath(outDir);\n if (!existsSync(path)) return null;\n try {\n const raw = JSON.parse(readFileSync(path, \"utf8\"));\n if (\n !raw ||\n typeof raw !== \"object\" ||\n raw.version !== 1 ||\n typeof raw.docCount !== \"number\" ||\n typeof raw.avgBodyLen !== \"number\" ||\n !Array.isArray(raw.df) ||",+ "span": "L138-L149"+ }},{"id": "src/ask/index-file.ts#tokenize",@@ -2097,9 +2894,12 @@"exported": true,"origin": "ast","body_hash": "d97d4f8b5422d7b236c0966ab1b1b82002c4691a389eff29fd97e93460269f21",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Tokenizes input text into lowercased subword tokens, ensuring consistent tokenization for both build-time and query-time processes.",+ "crux": {+ "code": "export function tokenize(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\") // camelCase → camel Case\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1 && !STOP.has(t));\n}",+ "span": "L38-L44"+ }},{"id": "src/ask/index-file.ts#writeAskIndex",@@ -2111,9 +2911,12 @@"exported": true,"origin": "ast","body_hash": "9e974a952bf81fe17aa6371841f24af344d8d32ceb67eee3dd6a19d85125e0cb",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Writes the tokenized representation of graph nodes and their frequencies to a JSON file, creating a cache for future queries.",+ "crux": {+ "code": "export function writeAskIndex(outDir: string, graph: GraphV1): string {\n const nodes = [...graph.nodes].sort((a, b) => a.id.localeCompare(b.id));\n const docs: AskIndexDoc[] = [];\n const df = new Map<string, number>();\n\n for (const n of nodes) {\n const name = counts(tokenize(n.name));\n const path = counts(tokenize(n.path));\n const body = counts(\n tokenize(`${n.signature ?? \"\"} ${n.summary ?? \"\"} ${n.body_text ?? \"\"}`),\n );\n docs.push({ id: n.id, name: pairs(name), path: pairs(path), body: pairs(body) });",+ "span": "L98-L109"+ }},{"id": "src/claude/format.ts",@@ -2126,8 +2929,8 @@"origin": "ast","body_hash": "de278daec7071243ac381603d43817c6589406a1c8d03cef4d0bcf58b4b1d902","chars": 7803,- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "This file contains functions and types for formatting and rendering status information related to a graph-based system.","crux": null},{@@ -2140,8 +2943,8 @@"exported": true,"origin": "ast","body_hash": "5758ae8e52d077f5662df3a37af9e59745a3b1b16a7e4bb50a2e62d047bff2fc",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure for a JSON object used in retrieval queries, encapsulating query details and hit information.","crux": null},{@@ -2154,9 +2957,12 @@"exported": true,"origin": "ast","body_hash": "13d408559074290e5bd519a136440f0021106ece96bde4eb9130807b43436421",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the percentage of enriched items based on the ready count and total count, returning a formatted string if there are any enriched items.",+ "crux": {+ "code": " const pct = s.totalCount ? Math.round((s.readyCount / s.totalCount) * 100) : 0;\n return C.indigo(`${pct}% enriched`);",+ "span": "L15-L16"+ }},{"id": "src/claude/format.ts#formatBlastRadius",@@ -2168,9 +2974,12 @@"exported": true,"origin": "ast","body_hash": "060f1af7d88ad5d2667bc25431982a15e05986ab706b647d4881429fc22cf210",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a string that describes the blast radius for a given file, listing dependencies and their relationships, up to a specified cap.",+ "crux": {+ "code": " const items = edges.slice(0, cap).map((e) => {\n const n = byId.get(e.source);\n const label = n ? `${n.name} (${basename(n.path)})` : e.source;\n return ` • ${e.relation} ← ${label}`;\n });\n const more = edges.length > cap ? `\\n • +${edges.length - cap} more` : '';\n return `[graft] blast radius for ${basename(filePath)} — who depends on it:\\n${items.join('\\n')}${more}`;",+ "span": "L68-L74"+ }},{"id": "src/claude/format.ts#formatOrientation",@@ -2182,9 +2991,12 @@"exported": true,"origin": "ast","body_hash": "0da076da5c6f3cacf6a7e8d372517b658ae7cd073d52740909684ba5b5aff6f0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a formatted string representing the orientation of the repository map, limited to a specified byte budget.",+ "crux": {+ "code": " return `[graft] repo map (graft/INDEX.md):\\n${indexMd.slice(0, budgetBytes)}`;",+ "span": "L166-L166"+ }},{"id": "src/claude/format.ts#formatRetrieval",@@ -2196,9 +3008,12 @@"exported": true,"origin": "ast","body_hash": "0e749b34c587c31ea6261a491f49e90e0985ed5171ee2f205dcad3466177572c",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats the retrieval results into a string, including details about tokens saved and the estimated size of the retrieval pack.",+ "crux": {+ "code": " `${body}\\n[graft] tokens saved ≈ ${saved.toLocaleString()} (${pct}%) — this pack ≈ ` +\n `${tokensOf(body.length).toLocaleString()} tok vs reading the ${ask.saved!.files} file(s) whole ≈ ` +\n `${base.toLocaleString()} tok (estimate).`",+ "span": "L128-L130"+ }},{"id": "src/claude/format.ts#freshnessSegment",@@ -2210,9 +3025,12 @@"exported": true,"origin": "ast","body_hash": "4017743e4d027d64db4d0d99f078e8b0f6694409539df5e72ea2951c08e00881",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a status message indicating the freshness of the data, highlighting if the data is syncing or stale.",+ "crux": {+ "code": " if (s.syncing) return C.amber('syncing…');\n if (s.dirty && s.staleCount > 0) return C.amber(`⚠ ${s.staleCount} stale`);\n if (s.dirty) return C.amber('⚠ stale');\n return C.indigo('✓ synced');",+ "span": "L20-L23"+ }},{"id": "src/claude/format.ts#incomingEdges",@@ -2224,9 +3042,12 @@"exported": true,"origin": "ast","body_hash": "df33e0b502eac5f85c753c6d6ba884e232e75ccbc8296eb1c2f74df403786114",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Finds all incoming edges for nodes in a graph that correspond to a specified file path, returning those edges that target the nodes.",+ "crux": {+ "code": " if (!ids.size) return [];\n return (w.edges ?? []).filter((e) => ids.has(e.target) && !ids.has(e.source));",+ "span": "L60-L61"+ }},{"id": "src/claude/format.ts#nodeIdsInFile",@@ -2238,9 +3059,12 @@"exported": false,"origin": "ast","body_hash": "4364752508d77072bf49b2e9f5b788665932916b6c0c081c7d2825f4190d593d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Retrieves a set of node IDs from a graph that correspond to a specified file path, filtering based on path matches.",+ "crux": {+ "code": " nodes.filter((n) => n.path && (filePath === n.path || filePath.endsWith(`/${n.path}`)))\n .map((n) => n.id),",+ "span": "L53-L54"+ }},{"id": "src/claude/format.ts#relevantRetrieval",@@ -2252,9 +3076,12 @@"exported": true,"origin": "ast","body_hash": "117b69b5bb5a2058d37856fe1429241e2e5b0e00dd3bc87ad2adbb52286f1f4e",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines if a retrieval pack should be injected based on relevance and novelty, returning the formatted text or null if not applicable.",+ "crux": {+ "code": " if (typeof ask.coverage === 'number' && ask.coverage < INJECT_MIN_COVERAGE) return null;\n const seen = new Set(s.injectedPointers ?? []);\n const fresh = ask.hits.filter((h) => !seen.has(h.pointer));\n if (!fresh.length) return null;\n const txt = formatRetrieval({ ...ask, hits: fresh }, cap);\n if (!txt) return null;\n s.injectedPointers = [...(s.injectedPointers ?? []), ...fresh.slice(0, cap).map((h) => h.pointer)]\n .slice(-INJECTED_POINTERS_CAP);\n return txt;",+ "span": "L154-L162"+ }},{"id": "src/claude/format.ts#renderStatusline",@@ -2266,9 +3093,12 @@"exported": true,"origin": "ast","body_hash": "2879019a5dec5846bba4fadb443068e54af2abb162af24c233c02cab01a82815",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs a status line for displaying the current state of the system, including node and edge counts, enrichment status, and session information.",+ "crux": {+ "code": " const top = [C.muted('◤ ') + C.indigo('graft'), C.text(`${stats.nodeCount} nodes / ${stats.edgeCount} edges`)];\n const enr = enrichedSegment(stats);\n if (enr) top.push(enr);\n top.push(freshnessSegment(stats));",+ "span": "L34-L37"+ }},{"id": "src/claude/format.ts#renderSubagent",@@ -2280,9 +3110,12 @@"exported": true,"origin": "ast","body_hash": "654ed5b50e9a47279bcc15b69c0b45df6e6b5d5684f33520fd7dda9600392de0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a string representation of a subagent's status, including its query if available, for display purposes.",+ "crux": {+ "code": " const tail = q ? SEP + C.muted('graft: ') + C.text(q) : '';\n return C.muted('◤ ') + C.indigo(agentName) + tail;",+ "span": "L171-L172"+ }},{"id": "src/claude/format.ts#retrievalBody",@@ -2294,9 +3127,12 @@"exported": false,"origin": "ast","body_hash": "2e68851469a8165204e9fbaf2dab76cbb78d5671cd5437b3a40498acc95a92fd",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs a formatted string representation of retrieval hits, including pointers and snippets, for display purposes.",+ "crux": {+ "code": " const blocks = hits.map((h, i) => {\n const ptr = (h.pointer ?? '').split(',')[0].trim();\n const snip = (h.snippet ?? '').replace(/\\s+/g, ' ').trim().slice(0, 140);\n let b = ` ${i + 1}. ${h.title} — ${ptr}`;\n if (snip) b += `\\n ${snip}`;\n if (h.code) b += `\\n\\`\\`\\`\\n${h.code}\\n\\`\\`\\``;\n return b;\n });\n // Two pack shapes: with inlined code the pack is substitutive (read here, don't\n // re-open); without code it is pointers-only — locators the agent may follow,\n // pulling spans itself via `graft ask --source` (push→pull: per-prompt injected\n // tokens are always fresh full-price input, so the pack stays tiny).",+ "span": "L92-L103"+ }},{"id": "src/claude/format.ts#retrievalTokensSaved",@@ -2308,9 +3144,12 @@"exported": true,"origin": "ast","body_hash": "fcfb9a5c94f35b59d228ea34edb8435c2f110e25c5a12ad572ec47646166d99a",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the number of tokens saved by using a retrieval pack instead of reading files in full, based on the hits and baseline size.",+ "crux": {+ "code": " return base > pack ? base - pack : 0;",+ "span": "L116-L116"+ }},{"id": "src/claude/format.ts#tokensOf",@@ -2322,8 +3161,8 @@"exported": false,"origin": "ast","body_hash": "a72a89f1099c37bae9e03a82e42ac3c2040789815176e99511f9bd5e31cbbe32",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Calculates the number of tokens based on character count, facilitating token management in retrieval processes.","crux": null},{@@ -2337,9 +3176,12 @@"origin": "ast","body_hash": "efe4393aec6f4ab0854042b1300e8e1af899d820e6819fd0ad2d2374d321ffee","chars": 5118,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles various events related to the Graft system, including session management and user prompts.",+ "crux": {+ "code": "export async function main(event: string): Promise<void> {\n const input = readStdin();\n const dir = projectDir(input);\n\n if (event === 'session-start') {\n try {\n const idx = readFileSync(join(dir, 'graft', 'INDEX.md'), 'utf8');\n emit('SessionStart', formatOrientation(idx));\n } catch { /* no INDEX.md — skip */ }\n return;\n }\n",+ "span": "L75-L86"+ }},{"id": "src/claude/hooks.ts#checkStaleCount",@@ -2351,9 +3193,12 @@"exported": false,"origin": "ast","body_hash": "d805c2f6af0f8a76196f80902c408ebe14fd46fb43a79b3944af2bd3c11e1d6a",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Counts the number of changes in the graft graph to determine if it is stale.",+ "crux": {+ "code": " const r = graftJson(dir, ['check', '.', '--json']);\n const g = r?.graph ?? {};\n return (g.changed?.length ?? 0) + (g.added?.length ?? 0) + (g.removed?.length ?? 0);",+ "span": "L43-L45"+ }},{"id": "src/claude/hooks.ts#emit",@@ -2365,9 +3210,12 @@"exported": false,"origin": "ast","body_hash": "9f7384f6c6c8562520fdc78864670fe66220557504ab0c21cc4cc2278194c2f1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Outputs a JSON object to standard output for event tracking.",+ "crux": {+ "code": " process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: eventName, additionalContext } }));\n}",+ "span": "L48-L49"+ }},{"id": "src/claude/hooks.ts#graftJson",@@ -2379,9 +3227,12 @@"exported": false,"origin": "ast","body_hash": "baa979b59d9ba8afbfe243a41e387c5833b409120746db26dc3ad30ff9eb9bd6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes a command to retrieve JSON output from the graft CLI, handling errors gracefully.",+ "crux": {+ "code": " const out = execFileSync(process.execPath, [graftCliPath(), ...args],\n { cwd: dir, encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'] });\n return JSON.parse(out);\n } catch (e: any) {\n // `graft check` exits non-zero when the graph is stale (by design) but still\n // prints valid JSON to stdout; recover it from the thrown error before giving up.\n if (e && typeof e.stdout === 'string' && e.stdout.trim()) {\n try { return JSON.parse(e.stdout); } catch { /* not JSON — fall through */ }\n }\n return null;\n }",+ "span": "L30-L40"+ }},{"id": "src/claude/hooks.ts#handlePostEdit",@@ -2393,9 +3244,12 @@"exported": false,"origin": "ast","body_hash": "afa0ad391dd4412cd4df9af9ce59983fa67796d316afeabef1275abc9889284d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles post-edit events by updating stats and emitting relevant information.",+ "crux": {+ "code": " patchStats(dir, { dirty: true, staleCount: checkStaleCount(dir), lastFile: basename(file) });\n const w = readWiring(dir);\n if (w) { const br = formatBlastRadius(w, file); if (br) emit('PostToolUse', br); }",+ "span": "L54-L56"+ }},{"id": "src/claude/hooks.ts#handleStop",@@ -2407,9 +3261,12 @@"exported": false,"origin": "ast","body_hash": "ef731173b05a469942f641ab924f540a6fdfede444916092a16464150b10bd7b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles the stop event by syncing state if necessary.",+ "crux": {+ "code": " if (stats?.dirty && acquireLock(dir)) {\n patchStats(dir, { syncing: true });\n const child = spawn(process.execPath, [syncRun, dir], { detached: true, stdio: 'ignore' });\n child.unref();\n }",+ "span": "L68-L72"+ }},{"id": "src/claude/hooks.ts#main",@@ -2421,9 +3278,12 @@"exported": true,"origin": "ast","body_hash": "901ece3648f4b605795b2ce8281dddfa50fa719fa435ee878522505fea74991c",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Main entry point for handling various events and orchestrating the application logic.",+ "crux": {+ "code": " if (event === 'session-start') {\n try {\n const idx = readFileSync(join(dir, 'graft', 'INDEX.md'), 'utf8');\n emit('SessionStart', formatOrientation(idx));\n } catch { /* no INDEX.md — skip */ }\n return;\n }\n\n if (event === 'post-edit') { await handlePostEdit(input, dir); return; }\n\n if (event === 'stop') { handleStop(dir); return; }\n",+ "span": "L79-L90"+ }},{"id": "src/claude/hooks.ts#projectDir",@@ -2435,9 +3295,12 @@"exported": false,"origin": "ast","body_hash": "4aa298cb59c252e2c2abe9c18294279b32f78eb55de1a883efd34affdf49cef8",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the project directory based on environment variables or input parameters.",+ "crux": {+ "code": " return process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();\n}",+ "span": "L22-L23"+ }},{"id": "src/claude/hooks.ts#readStdin",@@ -2449,9 +3312,12 @@"exported": false,"origin": "ast","body_hash": "a0c855d260852d9ede8e16aa40adaf829ecc549c5c7ea5f23a128754abc363a0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reads input from standard input, handling test seams and parsing JSON.",+ "crux": {+ "code": " const raw = seam !== undefined ? seam : safeReadFd0();\n try { return JSON.parse(raw); } catch { return {}; }",+ "span": "L16-L17"+ }},{"id": "src/claude/hooks.ts#safeReadFd0",@@ -2463,8 +3329,8 @@"exported": false,"origin": "ast","body_hash": "7594a29f0e0cf58a56f3730cad00dc40d449de18fc2baf18deb20d6457a63c15",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Safely reads from the standard input file descriptor, returning an empty string on failure.","crux": null},{@@ -2477,9 +3343,12 @@"exported": true,"origin": "ast","body_hash": "b87aa3e7ba9049438b7750b8dc3767fc4a2630e3a347e20900d1beaea543df04",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Checks if a given file is part of the graft project structure.",+ "crux": {+ "code": " const rel = file.startsWith(dir) ? file.slice(dir.length) : file;\n return rel.replace(/^[/\\\\]+/, '').replace(/\\\\/g, '/').startsWith('graft/');",+ "span": "L25-L26"+ }},{"id": "src/claude/init.ts",@@ -2492,9 +3361,12 @@"origin": "ast","body_hash": "7a686f132722453ee18c4715e4ab563f1577ac41811b01cced574de075a452ee","chars": 2251,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Initializes the Claude environment by setting up necessary directories, configuration files, and shims for the application.",+ "crux": {+ "code": "export function runInit(dir: string, opts: { build?: boolean; cliPath?: string } = {}): InitResult {\n const helpersDir = join(dir, '.claude', 'helpers');\n mkdirSync(helpersDir, { recursive: true });\n\n const settingsPath = join(dir, '.claude', 'settings.json');\n let existing: Record<string, any> = {};\n try { existing = JSON.parse(readFileSync(settingsPath, 'utf8')); } catch { /* none/invalid → start fresh */ }\n const { merged, warnings } = mergeGraftSettings(existing);\n writeFileSync(settingsPath, `${JSON.stringify(merged, null, 2)}\\n`);\n\n const sl = join(helpersDir, 'graft-statusline.cjs');\n const hk = join(helpersDir, 'graft-hooks.cjs');",+ "span": "L17-L28"+ }},{"id": "src/claude/init.ts#InitResult",@@ -2506,8 +3378,8 @@"exported": true,"origin": "ast","body_hash": "452d62ae1f5e60a539835b2fe9892f24cb79cb4b002808473397cfd0f3e729cc",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure of the result returned by the runInit function, encapsulating settings, shims, skill, warnings, and build status.","crux": null},{@@ -2520,9 +3392,12 @@"exported": true,"origin": "ast","body_hash": "8b5756f072c04e6fcef32d10f1a29a8b5c0d4f5e68d7642cfcb1ab43aef61fb0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Initializes the Claude environment by setting up necessary directories, merging settings, creating shims, and optionally building the project.",+ "crux": {+ "code": "export function runInit(dir: string, opts: { build?: boolean; cliPath?: string } = {}): InitResult {\n const helpersDir = join(dir, '.claude', 'helpers');\n mkdirSync(helpersDir, { recursive: true });\n\n const settingsPath = join(dir, '.claude', 'settings.json');\n let existing: Record<string, any> = {};\n try { existing = JSON.parse(readFileSync(settingsPath, 'utf8')); } catch { /* none/invalid → start fresh */ }\n const { merged, warnings } = mergeGraftSettings(existing);\n writeFileSync(settingsPath, `${JSON.stringify(merged, null, 2)}\\n`);\n\n const sl = join(helpersDir, 'graft-statusline.cjs');\n const hk = join(helpersDir, 'graft-hooks.cjs');",+ "span": "L17-L28"+ }},{"id": "src/claude/paths.ts",@@ -2535,9 +3410,12 @@"origin": "ast","body_hash": "d4bde8a45859c88921abd6fd06c700199bf1feaf2e5487e8e0e217cf9dab5026","chars": 1188,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This module provides utility functions to resolve paths for the graft CLI and related scripts, ensuring correct path resolution regardless of the installation context.",+ "crux": {+ "code": "export function graftCliPath(): string {\n return join(CLAUDE_DIR, '..', 'cli.js');\n}\n\n/** Absolute path to this package's `dist/claude` dir. Baked into the generated shims at\n * init time as their primary resolution candidate, so the statusline/hooks find graft\n * without runtime guesswork — correct regardless of how Node was installed. */\nexport function claudeDistDir(): string {\n return CLAUDE_DIR;\n}\n\n/** Absolute path to a sibling script in the claude dir (e.g. `sync-run.js`). */",+ "span": "L11-L22"+ }},{"id": "src/claude/paths.ts#claudeDistDir",@@ -2549,9 +3427,12 @@"exported": true,"origin": "ast","body_hash": "fa79e92f3473e4dc31dd9f505b0f76a76d1e8ba6820f39e1ebd23c217569fd64",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Returns the absolute path to the package's distribution directory, facilitating consistent access to resources without guesswork.",+ "crux": {+ "code": " return CLAUDE_DIR;",+ "span": "L19-L19"+ }},{"id": "src/claude/paths.ts#claudeScriptPath",@@ -2563,9 +3444,12 @@"exported": true,"origin": "ast","body_hash": "168a58f498382a3a3b70191e87465ccd36d98fe67c050aedefa722e4601a4233",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs the absolute path to a sibling script in the claude directory, enabling dynamic script resolution.",+ "crux": {+ "code": " return join(CLAUDE_DIR, name);",+ "span": "L24-L24"+ }},{"id": "src/claude/paths.ts#graftCliPath",@@ -2577,9 +3461,12 @@"exported": true,"origin": "ast","body_hash": "a89543a44c198c7ed91348d71ac004dae93303828aa241c0950ff982e7e14324",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Provides the absolute path to the graft CLI, ensuring it can be located regardless of the installation context.",+ "crux": {+ "code": " return join(CLAUDE_DIR, '..', 'cli.js');",+ "span": "L12-L12"+ }},{"id": "src/claude/settings-merge.ts",@@ -2592,9 +3479,12 @@"origin": "ast","body_hash": "eda59409ff8c470e7d3726a6740ba19e36e511ab40c67234aa794fabd9eacb8d","chars": 2653,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Merges existing settings with new graft configurations, ensuring proper command hooks and permissions are set while avoiding conflicts.",+ "crux": {+ "code": "export function mergeGraftSettings(existing: Json): { merged: Json; warnings: string[] } {\n const merged: Json = { ...(existing ?? {}) };\n const warnings: string[] = [];\n\n if (!merged.statusLine) merged.statusLine = { type: 'command', command: SL_CMD };\n else if (merged.statusLine.command !== SL_CMD)\n warnings.push('Existing statusLine left untouched (a session allows only one). To use Graft, point it at .claude/helpers/graft-statusline.cjs.');\n\n if (!merged.subagentStatusLine) merged.subagentStatusLine = { type: 'command', command: SL_CMD };\n else if (merged.subagentStatusLine.command !== SL_CMD)\n warnings.push('Existing subagentStatusLine left untouched.');\n",+ "span": "L22-L33"+ }},{"id": "src/claude/settings-merge.ts#graftBlocks",@@ -2606,9 +3496,12 @@"exported": false,"origin": "ast","body_hash": "b63b7e0ffcf1d915291072b9cef941ddc0f0a242052a955287c2c49bd21d38ed",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a mapping of events to their corresponding Graft command hooks for processing user actions.",+ "crux": {+ "code": " PostToolUse: { matcher: 'Write|Edit|MultiEdit', hooks: [{ type: 'command', command: hookCmd('post-edit'), timeout: 10000 }] },\n UserPromptSubmit: { hooks: [{ type: 'command', command: hookCmd('prompt'), timeout: 8000 }] },\n SessionStart: { hooks: [{ type: 'command', command: hookCmd('session-start'), timeout: 8000 }] },",+ "span": "L12-L14"+ }},{"id": "src/claude/settings-merge.ts#hookCmd",@@ -2620,9 +3513,12 @@"exported": false,"origin": "ast","body_hash": "e9298ddcd47ce700591a4d358b92ada2ac0b935b5830b3f73352c9de90fee469",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a command string to execute a specified hook in the Graft environment.",+ "crux": {+ "code": " return `node \"\\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" ${arg}`;",+ "span": "L8-L8"+ }},{"id": "src/claude/settings-merge.ts#isGraftHookEntry",@@ -2634,9 +3530,12 @@"exported": false,"origin": "ast","body_hash": "99d3b618293eccfb74c0e88c5671c484a54355792596c8b6c2856f8cb432814e",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Checks if a given entry is a Graft hook by inspecting its command reference.",+ "crux": {+ "code": " return JSON.stringify(entry ?? '').includes('graft-hooks.cjs');",+ "span": "L19-L19"+ }},{"id": "src/claude/settings-merge.ts#Json",@@ -2648,8 +3547,8 @@"exported": false,"origin": "ast","body_hash": "0c2b997e71a6ecf28fd3f46a0f9d4799bef1615b247ca3e471aad6b57e73189c",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines a flexible JSON type for various settings configurations.","crux": null},{@@ -2662,9 +3561,12 @@"exported": true,"origin": "ast","body_hash": "ea1e86633976a209debc5f9a83ac8ef1e7fd74f5327e196617b64ae8849ff8c5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Merges existing settings with Graft-specific configurations, ensuring idempotency and compliance with Graft rules.",+ "crux": {+ "code": " if (!merged.statusLine) merged.statusLine = { type: 'command', command: SL_CMD };\n else if (merged.statusLine.command !== SL_CMD)\n warnings.push('Existing statusLine left untouched (a session allows only one). To use Graft, point it at .claude/helpers/graft-statusline.cjs.');\n\n if (!merged.subagentStatusLine) merged.subagentStatusLine = { type: 'command', command: SL_CMD };\n else if (merged.subagentStatusLine.command !== SL_CMD)\n warnings.push('Existing subagentStatusLine left untouched.');",+ "span": "L26-L32"+ }},{"id": "src/claude/shim-template.ts",@@ -2677,9 +3579,12 @@"origin": "ast","body_hash": "53c468c5de89b06fb76439c756932592409eba5fc19ba07ff6a37403912033a9","chars": 3141,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates shims to dynamically locate and execute the correct version of the @nanonets/graft package's entry points, ensuring compatibility across different installation methods.",+ "crux": {+ "code": "}",+ "span": "L56-L56"+ }},{"id": "src/claude/shim-template.ts#hooksShim",@@ -2691,8 +3596,8 @@"exported": true,"origin": "ast","body_hash": "8ea2753059a8ae115b10aaa971482641a2462ad97d8c79dbd7a78cbe94c9213a",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Creates a shim for the hooks entry of the graft package, enabling its execution with command-line arguments.","crux": null},{@@ -2705,9 +3610,12 @@"exported": false,"origin": "ast","body_hash": "bc007e4fd1420dea4e01d8ae1c8994ea3e04c75b62ddc76b8a5fd671bab71dd3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a script that dynamically locates and executes a specified entry file from the installed graft package, ensuring compatibility across various installation methods.",+ "crux": {+ "code": "// The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched.\nfunction fromPkg(base) {\n try {\n const pkg = require.resolve('@nanonets/graft/package.json', { paths: [base] });\n return path.join(path.dirname(pkg), 'dist', 'claude');\n } catch { return null; }\n}\n\n// The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand.\nfunction globalRoot() {\n try {\n const root = execFileSync('npm', ['root', '-g'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], shell: process.platform === 'win32' }).trim();",+ "span": "L25-L36"+ }},{"id": "src/claude/shim-template.ts#statuslineShim",@@ -2719,8 +3627,8 @@"exported": true,"origin": "ast","body_hash": "1923650d5135a05cad7f41616e3c1e7c5d8af844798ad9fa9cbcb77299de5a3c",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Creates a shim for the statusline entry of the graft package, facilitating its execution in a consistent manner.","crux": null},{@@ -2734,9 +3642,12 @@"origin": "ast","body_hash": "4e951868562ef41f827b4828dc1931cf1e645d2e57999308b1919f62de5af7fb","chars": 4071,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Provides a structured template for the graft Claude Code skill, enabling efficient onboarding and understanding of the codebase.",+ "crux": {+ "code": "export function skillTemplate(): string {\n return `---\nname: graft\ndescription: This repo is indexed by graft/. For ANY task here — understanding\n how something works, finding where code lives, or scoping a change — get your\n context from graft before grepping or reading source files.\n---\n\n# graft\n\nThis repo's code is summarised in \\`graft/\\` — small markdown nodes, each\nexplaining one part in plain prose and naming the exact files and line-spans it",+ "span": "L6-L17"+ }},{"id": "src/claude/skill-template.ts#skillTemplate",@@ -2748,9 +3659,12 @@"exported": true,"origin": "ast","body_hash": "a556c949cf0d4da9758a04f07d3a0d2ba7b7630e947aca38bdaad8430ee73a2f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a markdown string that serves as a comprehensive guide for using the graft tool effectively within a code repository.",+ "crux": {+ "code": "export function skillTemplate(): string {\n return `---\nname: graft\ndescription: This repo is indexed by graft/. For ANY task here — understanding\n how something works, finding where code lives, or scoping a change — get your\n context from graft before grepping or reading source files.\n---\n\n# graft\n\nThis repo's code is summarised in \\`graft/\\` — small markdown nodes, each\nexplaining one part in plain prose and naming the exact files and line-spans it",+ "span": "L6-L17"+ }},{"id": "src/claude/state.ts",@@ -2763,9 +3677,12 @@"origin": "ast","body_hash": "f8b8d93b534be15a3d71565e63a63caa302f036348d20dcd645fb49f25db3f61","chars": 3650,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Manages application state and session data, including statistics and file locking mechanisms.",+ "crux": {+ "code": "export function patchStats(d: string, patch: Partial<Stats>): Stats {\n const next: Stats = { ...(readStats(d) ?? emptyStats()), ...patch };\n writeStats(d, next);\n return next;",+ "span": "L51-L54"+ }},{"id": "src/claude/state.ts#acquireLock",@@ -2777,9 +3694,12 @@"exported": true,"origin": "ast","body_hash": "d10ac8134d1cc35d9bd14414ba7608b48646c70492b96b624f1e140f86dbd4b6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Attempts to acquire a lock for the specified directory to prevent concurrent access issues.",+ "crux": {+ "code": "export function acquireLock(d: string): boolean {\n const p = lockPath(d);\n mkdirSync(cacheDir(d), { recursive: true });\n const payload = JSON.stringify({ pid: process.pid, at: new Date().toISOString() });\n try {\n writeFileSync(p, payload, { flag: 'wx' }); // atomic exclusive create\n return true;\n } catch (e: any) {\n if (e?.code !== 'EEXIST') throw e;\n let stale: boolean;\n try { stale = Date.now() - statSync(p).mtimeMs >= LOCK_STALE_MS; } catch { stale = true; }\n if (!stale) return false;",+ "span": "L63-L74"+ }},{"id": "src/claude/state.ts#cacheDir",@@ -2791,9 +3711,12 @@"exported": true,"origin": "ast","body_hash": "c5b57c650fe2af36c19b2cad9b398f6c77e16046d173394d0710edde24c516f2",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs the path to the cache directory for a given project.",+ "crux": {+ "code": "export function cacheDir(projectDir: string): string { return join(projectDir, 'graft', '.cache'); }",+ "span": "L32-L32"+ }},{"id": "src/claude/state.ts#emptySession",@@ -2805,9 +3728,12 @@"exported": false,"origin": "ast","body_hash": "b08d2c899575a022887655dd89d27362e526c5f66dc5c41b0766da5f918c7b31",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates and returns an initial empty SessionState object to reset session tracking.",+ "crux": {+ "code": "function emptySession(): SessionState {\n return { lastQuery: null, perAgentQuery: {}, graftReads: 0, sourceReads: 0, savedTokens: 0, injectedPointers: [] };\n}",+ "span": "L28-L30"+ }},{"id": "src/claude/state.ts#emptyStats",@@ -2819,9 +3745,12 @@"exported": true,"origin": "ast","body_hash": "f507d8c6bb5222d97af97220bed44ebab58221672fe4c0f1e43c410c7ad6f03f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates and returns an initial empty Stats object to reset statistics tracking.",+ "crux": {+ "code": "export function emptyStats(): Stats {\n return { nodeCount: 0, edgeCount: 0, languages: [], totalCount: 0, readyCount: 0,\n staleCount: 0, dirty: false, syncing: false, syncedAt: null, lastFile: null };\n}",+ "span": "L24-L27"+ }},{"id": "src/claude/state.ts#lockPath",@@ -2833,9 +3762,12 @@"exported": false,"origin": "ast","body_hash": "d9e771038564b59c8e77023262cf3b4cb19cb67a11bdffd03596b55ba16abd19",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates the file path for the synchronization lock used in the caching mechanism.",+ "crux": {+ "code": "function lockPath(d: string): string { return join(cacheDir(d), '.sync.lock'); }",+ "span": "L35-L35"+ }},{"id": "src/claude/state.ts#patchStats",@@ -2847,9 +3779,12 @@"exported": true,"origin": "ast","body_hash": "44a7279d2463dc0c60b5992a1bbf3ca152a81fbf281ba3181f66306ea47bac0b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Updates the existing statistics with a patch and writes the updated stats back to storage.",+ "crux": {+ "code": "export function patchStats(d: string, patch: Partial<Stats>): Stats {\n const next: Stats = { ...(readStats(d) ?? emptyStats()), ...patch };\n writeStats(d, next);\n return next;\n}",+ "span": "L51-L55"+ }},{"id": "src/claude/state.ts#readJson",@@ -2861,9 +3796,12 @@"exported": false,"origin": "ast","body_hash": "70bcbc68383bedc607095d101f70d8bf5a7c0bfa84d2fec3b9583674646386e0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reads and parses a JSON file, returning the content or null if an error occurs.",+ "crux": {+ "code": "function readJson<T>(p: string): T | null {\n try { return JSON.parse(readFileSync(p, 'utf8')) as T; } catch { return null; }\n}",+ "span": "L37-L39"+ }},{"id": "src/claude/state.ts#readSession",@@ -2875,9 +3813,12 @@"exported": true,"origin": "ast","body_hash": "9c9ff7506f27585bde3a8218144cc25959b1b5a460f65eedbec712dce641f391",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reads the session data from the specified path, returning an empty session if not found.",+ "crux": {+ "code": "export function readSession(d: string, id: string): SessionState {\n return readJson<SessionState>(sessionPath(d, id)) ?? emptySession();\n}",+ "span": "L56-L58"+ }},{"id": "src/claude/state.ts#readStats",@@ -2889,9 +3830,12 @@"exported": true,"origin": "ast","body_hash": "0fc71d400d255e986f4914c0a59304ed5b6d39684e7ddbae7e72fa4edd56a633",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reads the statistics from the specified path, returning null if not found.",+ "crux": {+ "code": "export function readStats(d: string): Stats | null { return readJson<Stats>(statsPath(d)); }",+ "span": "L47-L47"+ }},{"id": "src/claude/state.ts#releaseLock",@@ -2902,10 +3846,13 @@"signature": "function releaseLock(d: string): void","exported": true,"origin": "ast",- "body_hash": "0e65162ca2e768f56fcd08d222fb831dc50e2c8f69bf8e3a4b568178d3efb7bb",- "summary_state": "pending",- "summary": null,- "crux": null+ "body_hash": "0e65162ca2e768f56fcd08d222fb831dc50e2c8f69bf8e3a4b568178d3efb7bb",+ "summary_state": "ready",+ "summary": "Releases the lock for the specified directory, allowing other processes to access it.",+ "crux": {+ "code": "export function releaseLock(d: string): void { try { rmSync(lockPath(d)); } catch { /* already gone */ } }",+ "span": "L80-L80"+ }},{"id": "src/claude/state.ts#sessionPath",@@ -2917,9 +3864,12 @@"exported": false,"origin": "ast","body_hash": "2cb9cb73fc21b0857099f40d2df6a5b62657b5464ba8830cda3edd015ef1ccc3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates the file path for storing session data in JSON format.",+ "crux": {+ "code": "function sessionPath(d: string, id: string): string { return join(cacheDir(d), 'session', `${id}.json`); }",+ "span": "L34-L34"+ }},{"id": "src/claude/state.ts#SessionState",@@ -2931,9 +3881,12 @@"exported": true,"origin": "ast","body_hash": "71b7141bbad2edaaeb5de514b603e2f56d62428dfe0da720818a505a19b96c52",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for maintaining the state of a session, including queries and token savings.",+ "crux": {+ "code": "export interface SessionState {\n lastQuery: string | null;\n perAgentQuery: Record<string, string>;\n graftReads: number; sourceReads: number;\n /** Cumulative tokens saved this session via `ask --source` retrieval (est.). */\n savedTokens: number;\n /** Pointers the prompt hook already injected this session (novelty gate:\n * a hit whose pointer was shown once is never re-injected). Optional so\n * session files written before this field still parse. */\n injectedPointers?: string[];\n}",+ "span": "L10-L20"+ }},{"id": "src/claude/state.ts#Stats",@@ -2945,9 +3898,12 @@"exported": true,"origin": "ast","body_hash": "c6f7b600be3741c9535991dad2a97f36768b6376460c696df32a279008044ab0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for tracking various statistics related to nodes and edges in the system.",+ "crux": {+ "code": "export interface Stats {\n nodeCount: number; edgeCount: number; languages: string[];\n totalCount: number; readyCount: number;\n staleCount: number; dirty: boolean; syncing: boolean;\n syncedAt: string | null; lastFile: string | null;\n}",+ "span": "L4-L9"+ }},{"id": "src/claude/state.ts#statsPath",@@ -2959,9 +3915,12 @@"exported": false,"origin": "ast","body_hash": "82bf554697f883d634f98df066c106f57a2dd1f90f5d2ff5575f04ae5237a829",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates the file path for storing statistics in JSON format.",+ "crux": {+ "code": "function statsPath(d: string): string { return join(cacheDir(d), 'stats.json'); }",+ "span": "L33-L33"+ }},{"id": "src/claude/state.ts#writeJsonAtomic",@@ -2973,9 +3932,12 @@"exported": false,"origin": "ast","body_hash": "52709eed6470bfb5239dc6472ae93c63768fa95d1bc308cadc7f2c99f4961ba6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Writes a JSON object to a file atomically, ensuring no data corruption during the write process.",+ "crux": {+ "code": "function writeJsonAtomic(p: string, value: unknown): void {\n mkdirSync(dirname(p), { recursive: true });\n const tmp = `${p}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(value, null, 2));\n renameSync(tmp, p);\n}",+ "span": "L40-L45"+ }},{"id": "src/claude/state.ts#writeSession",@@ -2987,9 +3949,12 @@"exported": true,"origin": "ast","body_hash": "a8eead65e532c3c1791cffad444c6fd7622cdb054e1eaae5cf7e441a83d58b81",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Writes the session data to the specified path in JSON format.",+ "crux": {+ "code": "export function writeSession(d: string, id: string, s: SessionState): void {\n writeJsonAtomic(sessionPath(d, id), s);\n}",+ "span": "L59-L61"+ }},{"id": "src/claude/state.ts#writeStats",@@ -3001,9 +3966,12 @@"exported": true,"origin": "ast","body_hash": "9be95135d233dd6454caab02396b7a742dd79d3f7fc3bf7eb4ddc3d5991b56d6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Writes the provided statistics to the specified path in JSON format.",+ "crux": {+ "code": "export function writeStats(d: string, s: Stats): void { writeJsonAtomic(statsPath(d), s); }",+ "span": "L48-L48"+ }},{"id": "src/claude/stats.ts",@@ -3016,9 +3984,12 @@"origin": "ast","body_hash": "fc205923682e656d3e68bf301ba25702b827262f12057910615b4b648de3338b","chars": 853,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This module provides functions to read wiring data from a JSON file and compute statistics about graph nodes and edges, facilitating analysis of project structure.",+ "crux": {+ "code": "export function computeStats(\n w: GraphV1,\n): Pick<Stats, 'nodeCount' | 'edgeCount' | 'languages' | 'totalCount' | 'readyCount'> {\n const nodes = w.nodes ?? [];\n const edges = w.edges ?? [];\n const readyCount = nodes.filter((n) => n.summary_state === 'ready').length;\n return {\n nodeCount: w.meta?.nodeCount ?? nodes.length,\n edgeCount: w.meta?.edgeCount ?? edges.length,\n languages: w.meta?.languages ?? [],\n totalCount: nodes.length,\n readyCount,",+ "span": "L12-L23"+ }},{"id": "src/claude/stats.ts#computeStats",@@ -3030,9 +4001,12 @@"exported": true,"origin": "ast","body_hash": "87947ad507814b67ebf5ac5ad9517c223db582a48a1731c266e3a2d9eb1ce289",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates and returns statistics about the nodes and edges in a graph, including counts and languages used.",+ "crux": {+ "code": " const readyCount = nodes.filter((n) => n.summary_state === 'ready').length;\n return {\n nodeCount: w.meta?.nodeCount ?? nodes.length,\n edgeCount: w.meta?.edgeCount ?? edges.length,\n languages: w.meta?.languages ?? [],\n totalCount: nodes.length,\n readyCount,",+ "span": "L17-L23"+ }},{"id": "src/claude/stats.ts#readWiring",@@ -3044,9 +4018,12 @@"exported": true,"origin": "ast","body_hash": "af195cd730aedc42089766e76e9e82876adbc6ee689b7b06626ad3aa90ed9ac4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Loads and parses the wiring configuration from a JSON file, returning the graph structure or null if an error occurs.",+ "crux": {+ "code": " return JSON.parse(readFileSync(join(projectDir, 'graft', '.graph', 'wiring.json'), 'utf8')) as GraphV1;\n } catch { return null; }",+ "span": "L8-L9"+ }},{"id": "src/claude/statusline.ts",@@ -3073,9 +4050,12 @@"exported": true,"origin": "ast","body_hash": "bddbcc037fe00e01bb76e40b1ceed83b0a308423cc286bc4b3cc95bf9c98c825",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles input and orchestrates the rendering of the status line or subagent output based on the provided context.",+ "crux": {+ "code": " if (agent) { process.stdout.write(renderSubagent(agent, session)); return; }\n const stats = resolveStats(dir);\n const raw = input?.context_window?.used_percentage;\n const ctxPct = typeof raw === 'number' ? Math.round(raw) : null;\n process.stdout.write(renderStatusline(stats, session, { ctxPct }).join('\\n'));",+ "span": "L28-L32"+ }},{"id": "src/claude/statusline.ts#resolveStats",@@ -3087,9 +4067,12 @@"exported": true,"origin": "ast","body_hash": "080c7327bf26883f0575973010484e67024f57e455022563706d85582ca08891",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the current statistics of the project, either from a cache or by reading the wiring graph directly.",+ "crux": {+ "code": " if (cached && cached.nodeCount > 0) return cached;\n const wiring = readWiring(dir);\n if (wiring) return { ...emptyStats(), ...computeStats(wiring) };",+ "span": "L16-L18"+ }},{"id": "src/claude/sync-run.ts",@@ -3102,9 +4085,12 @@"origin": "ast","body_hash": "7ee672e67d3167a38e9577a673656f7958c69b48e62ec715850a9b14599a1d2a","chars": 1291,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Coordinates the synchronous build process and updates the system state based on the build results.",+ "crux": {+ "code": "export function runSync(dir: string, build: (d: string) => void = realBuild): void {\n try {\n build(dir);\n const w = readWiring(dir);\n if (!w) { patchStats(dir, { syncing: false }); return; } // build ran but output unreadable — stay dirty, retry\n patchStats(dir, {\n dirty: false, staleCount: 0, syncing: false, syncedAt: new Date().toISOString(),\n ...computeStats(w),\n });\n } catch {\n patchStats(dir, { syncing: false }); // leave dirty=true; retry next turn\n } finally {",+ "span": "L13-L24"+ }},{"id": "src/claude/sync-run.ts#main",@@ -3116,9 +4102,12 @@"exported": true,"origin": "ast","body_hash": "f4921fe8ea499e226c1d9a10d551ed55efcab2c954dfe44299c23bfe7c833b5d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Initiates the synchronization process when the script is executed directly with a specified directory.",+ "crux": {+ "code": " const dir = process.argv[2];\n if (dir) runSync(dir);",+ "span": "L30-L31"+ }},{"id": "src/claude/sync-run.ts#realBuild",@@ -3130,9 +4119,12 @@"exported": false,"origin": "ast","body_hash": "9138acc16457c5ba012c6a206acc5e406dd226657f7915e57d6a215aa138a4e6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes a build process for a specified directory, ensuring it adheres to specific constraints.",+ "crux": {+ "code": " execFileSync(process.execPath, [graftCliPath(), 'build', '.'],\n { cwd: dir, stdio: 'ignore', timeout: 120000 });",+ "span": "L9-L10"+ }},{"id": "src/claude/sync-run.ts#runSync",@@ -3144,9 +4136,12 @@"exported": true,"origin": "ast","body_hash": "31c8d6625fe3855ae2c854d45a6364ad66759b9098596ddacb95b9b8f883fccc",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Coordinates the build process and updates the system state based on the build outcome.",+ "crux": {+ "code": " const w = readWiring(dir);\n if (!w) { patchStats(dir, { syncing: false }); return; } // build ran but output unreadable — stay dirty, retry\n patchStats(dir, {\n dirty: false, staleCount: 0, syncing: false, syncedAt: new Date().toISOString(),\n ...computeStats(w),\n });",+ "span": "L16-L21"+ }},{"id": "src/cli-epilogue.ts",@@ -3159,9 +4154,12 @@"origin": "ast","body_hash": "a4534c83c0a600020421be92882a83db7fda3e1626a38702fc372bb3c523a232","chars": 3220,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a closing message for the `graft init` command, including next steps and a visual wordmark.",+ "crux": {+ "code": " const wordmark = WORDMARK_LINES.map((l) => (tty ? indigo(l) : l));\n if (graphBuilt && nodes !== undefined && edges !== undefined) {\n const stats = ` ${nodes.toLocaleString(\"en-US\")} nodes · ${edges.toLocaleString(\"en-US\")} edges`;\n wordmark[STATS_LINE_INDEX] += tty ? muted(stats) : stats;\n }\n\n const steps: Step[] = [\n ...(graphBuilt ? [] : [{ label: \"build the graph\", command: \"graft build\" }]),\n { label: \"restart your agent\", command: \"a new session picks up graft automatically\" },\n {\n label: \"code as usual\",\n command: \"ask your agent to fix a bug or explain a flow —\",",+ "span": "L48-L59"+ }},{"id": "src/cli-epilogue.ts#formatInitEpilogue",@@ -3173,9 +4171,12 @@"exported": true,"origin": "ast","body_hash": "9d5c62edd17deaccdf340662903164b7d3d4d3d641a2de63e4d724d5c5414eae",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats and returns the next-steps epilogue for the `graft init` command based on provided options.",+ "crux": {+ "code": " const wordmark = WORDMARK_LINES.map((l) => (tty ? indigo(l) : l));\n if (graphBuilt && nodes !== undefined && edges !== undefined) {\n const stats = ` ${nodes.toLocaleString(\"en-US\")} nodes · ${edges.toLocaleString(\"en-US\")} edges`;\n wordmark[STATS_LINE_INDEX] += tty ? muted(stats) : stats;\n }\n\n const steps: Step[] = [\n ...(graphBuilt ? [] : [{ label: \"build the graph\", command: \"graft build\" }]),\n { label: \"restart your agent\", command: \"a new session picks up graft automatically\" },\n {\n label: \"code as usual\",\n command: \"ask your agent to fix a bug or explain a flow —\",",+ "span": "L48-L59"+ }},{"id": "src/cli-epilogue.ts#indigo",@@ -3187,8 +4188,8 @@"exported": false,"origin": "ast","body_hash": "c8106154914b8f7b5e0f082446550f686fb2e88b53c90f669c27ee0fee6a09d8",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Applies a specific color formatting to a string for terminal output.","crux": null},{@@ -3201,8 +4202,8 @@"exported": true,"origin": "ast","body_hash": "5cf812b2bbf455f2e65e722c3d550f588c328a471edf9578bdc6d9b897b770d8",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Specifies options for rendering the init epilogue, including graph status and node/edge counts.","crux": null},{@@ -3215,8 +4216,8 @@"exported": false,"origin": "ast","body_hash": "8e2dfbf259448165613a7d727cf2a32d4f097985d48e67393b809379fb3bb0d7",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Applies a muted color formatting to a string for terminal output.","crux": null},{@@ -3229,8 +4230,8 @@"exported": false,"origin": "ast","body_hash": "a968435c9dfdf66413f2465053633289b8ec0b3be46d92eae9616521b0ec3873",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure for a step in the epilogue, including a label and command.","crux": null},{@@ -3244,9 +4245,12 @@"origin": "ast","body_hash": "95ee44a152ed1936f0461b2452d9902fbf422555da9f01e8f5ff57fbb84a2f00","chars": 5427,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file provides support for version management and upgrade functionality for the graft package, including version resolution and reporting.",+ "crux": {+ "code": "const PKG_NAME = \"@nanonets/graft\";",+ "span": "L12-L12"+ }},{"id": "src/cli-meta.ts#formatUpgradeReport",@@ -3258,9 +4262,12 @@"exported": true,"origin": "ast","body_hash": "55b6aaadead32c8dda3ff65edf58270fa52b937ae45c1c8c8067c416a3923c86",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a user-friendly report after an upgrade attempt, indicating success or failure.",+ "crux": {+ "code": " return `✗ npm install -g ${PKG_NAME}@latest failed${result.errorMessage ? `: ${result.errorMessage}` : \"\"}`;\n }\n return `graft ${result.oldVersion ?? \"?\"} → ${result.newVersion ?? result.oldVersion ?? \"?\"}`;",+ "span": "L124-L126"+ }},{"id": "src/cli-meta.ts#formatVersionReport",@@ -3272,9 +4279,12 @@"exported": true,"origin": "ast","body_hash": "2bd4c8400f266d189b191ed9ec76a804b8bedf30e0cb2d3cb9d087a3da3001a9",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a report on the current and latest package versions for user-friendly output.",+ "crux": {+ "code": " if (!latest.ok || !latest.version) {\n lines.push(\"latest: unreachable (offline?)\");\n } else if (latest.version === current) {\n lines.push(`latest on npm: ${current} ✓ up to date`);\n } else {\n lines.push(`latest on npm: ${latest.version} — run graft upgrade`);\n }\n return lines.join(\"\\n\");",+ "span": "L65-L72"+ }},{"id": "src/cli-meta.ts#getNpmViewVersion",@@ -3286,9 +4296,12 @@"exported": true,"origin": "ast","body_hash": "7f899924ef65d988bcc484d526263978178eeb1df18c3f4e189a7b5553cdf346",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Fetches the version of a specified package from npm, handling errors gracefully to ensure reliability.",+ "crux": {+ "code": " if (res.error || res.signal || res.status !== 0) return { ok: false };\n const version = res.stdout?.trim();\n if (!version) return { ok: false };\n return { ok: true, version };",+ "span": "L53-L56"+ }},{"id": "src/cli-meta.ts#globalRoot",@@ -3300,9 +4313,12 @@"exported": false,"origin": "ast","body_hash": "5296e6bdbdafb80632f1587a2815e89717ae7eeaa7b5d384cbf164d6e73ffb45",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the global npm node_modules directory, accommodating various installation layouts.",+ "crux": {+ "code": "function globalRoot(): string | null {\n try {\n const root = execFileSync(\"npm\", [\"root\", \"-g\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n shell: process.platform === \"win32\",\n }).trim();\n return root || null;\n } catch {\n return null;\n }",+ "span": "L76-L86"+ }},{"id": "src/cli-meta.ts#isRunningViaNpx",@@ -3314,9 +4330,12 @@"exported": true,"origin": "ast","body_hash": "da893b35a5ddbd2d55bf3d9e0eb76737586227d1c80ca3ab3dba8b88a2357781",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Checks if the current module is executed from an npx cache directory, affecting how upgrades are handled.",+ "crux": {+ "code": " return fileURLToPath(moduleUrl).includes(\"/_npx/\");",+ "span": "L36-L36"+ }},{"id": "src/cli-meta.ts#NpmViewResult",@@ -3328,9 +4347,12 @@"exported": true,"origin": "ast","body_hash": "90ac467dca193bc177b9a38002fc19687935fe93dee82c7f0667b7355905126e",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for the result of an npm view command, indicating success and the version of a package.",+ "crux": {+ "code": "export interface NpmViewResult {\n ok: boolean;\n version?: string;\n}",+ "span": "L39-L42"+ }},{"id": "src/cli-meta.ts#readCurrentVersion",@@ -3342,9 +4364,12 @@"exported": true,"origin": "ast","body_hash": "2853fef726b29eba13de30dd028e6e1f2eff130828dc1b0ba8278d408e112b68",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Retrieves the current version of the graft package from its package.json file, ensuring the application uses the correct version.",+ "crux": {+ "code": " const raw = readFileSync(resolvePackageJsonPath(moduleUrl), \"utf8\");\n const pkg = JSON.parse(raw) as { version?: string };\n return pkg.version ?? \"0.0.0\";",+ "span": "L28-L30"+ }},{"id": "src/cli-meta.ts#readGlobalInstalledVersion",@@ -3356,9 +4381,12 @@"exported": true,"origin": "ast","body_hash": "8d5197a36519f93e72ca3694601f4b7f8e4986badda334b6a58fd62faf02e456",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reads the installed version of a package directly from the global node_modules directory, providing accurate local versioning.",+ "crux": {+ "code": " const pkg = JSON.parse(readFileSync(pkgJson, \"utf8\")) as { version?: string };\n return pkg.version ?? null;",+ "span": "L98-L99"+ }},{"id": "src/cli-meta.ts#resolvePackageJsonPath",@@ -3370,9 +4398,12 @@"exported": true,"origin": "ast","body_hash": "1f7a429abe093ad617757a954aac19d08c678691a5ecb54332b81fe0bb375752",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the path to the package.json file for a given module URL, enabling access to package metadata.",+ "crux": {+ "code": " if (existsSync(c)) return c;\n }\n return candidates[0];",+ "span": "L21-L23"+ }},{"id": "src/cli-meta.ts#runUpgrade",@@ -3384,9 +4415,12 @@"exported": true,"origin": "ast","body_hash": "e97acdffcbf87e0d54489080b688476ec3b4ae5ecf0b76dd0e418c754e053e5c",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes the upgrade process for the graft package, ensuring the latest version is installed unless running via npx.",+ "crux": {+ "code": " const oldVersion = readCurrentVersion(moduleUrl);\n if (isRunningViaNpx(moduleUrl)) {\n return { ran: false, ok: true, oldVersion };\n }\n const res = spawnSync(\"npm\", [\"install\", \"-g\", `${PKG_NAME}@latest`], { stdio: \"inherit\" });\n if (res.error || (res.status ?? 1) !== 0) {\n return { ran: true, ok: false, oldVersion, errorMessage: res.error?.message };\n }\n const newVersion = readGlobalInstalledVersion(PKG_NAME) ?? getNpmViewVersion(PKG_NAME).version ?? oldVersion;\n return { ran: true, ok: true, oldVersion, newVersion };",+ "span": "L133-L142"+ }},{"id": "src/cli-meta.ts#UpgradeResult",@@ -3398,26 +4432,46 @@"exported": true,"origin": "ast","body_hash": "c9bb4b9900b362a7a657417bd3b0ffb018623634cff10a318332c4d1bb83654e",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for the result of an upgrade operation, indicating whether it was executed and its success status.",+ "crux": {+ "code": "export interface UpgradeResult {\n /** True when `npm install -g` actually ran (false for the npx no-op path). */\n ran: boolean;\n ok: boolean;\n /** Present when ran=true and the install failed. */\n errorMessage?: string;\n oldVersion?: string;\n newVersion?: string;\n}",+ "span": "L105-L113"+ }},{"id": "src/cli.ts","name": "cli.ts","kind": "file","path": "src/cli.ts",- "span": "L1-L430",+ "span": "L1-L460","signature": null,"exported": true,"origin": "ast",- "body_hash": "16405afe8b55c6c376785cbd9ddb2854631f6985ab287b5ac230189bf360d00e",- "chars": 18761,- "summary_state": "stale",- "summary": "This file implements the `graft` CLI tool for building and maintaining a context graph from code, ensuring it stays in sync with the repository.",+ "body_hash": "2c7acb076bd022635defd0b67c5358edd3b662328050be6c2d976e6baa17fc9c",+ "chars": 19746,+ "summary_state": "ready",+ "summary": "Defines the command-line interface for the graft tool, enabling various operations on the codebase's context graph.","crux": {"code": "program\n .name(\"graft\")\n .description(\"Build a repo's context graph as linked markdown, and keep it in sync with the code.\")",- "span": "L22-L24"+ "span": "L38-L40"+ }+ },+ {+ "id": "src/cli.ts#cliConfig",+ "name": "cliConfig",+ "kind": "function",+ "path": "src/cli.ts",+ "span": "L57-L66",+ "signature": "function cliConfig(): EngineConfig",+ "exported": false,+ "origin": "ast",+ "body_hash": "590dc12f9a414fbcb6b1fbf9ebfd22558f09f9026befe27f6e9ba777f69fe71f",+ "summary_state": "ready",+ "summary": "Constructs the configuration object for the engine based on CLI options, ensuring the correct parameters are used for graph generation.",+ "crux": {+ "code": " const o = program.opts<GlobalOpts>();\n return {\n contextDir: o.dir,\n provider: o.provider as ProviderKind | undefined,\n model: o.model,\n apiKey: o.apiKey,\n baseUrl: o.baseUrl,\n };\n}",+ "span": "L58-L66"}},{@@ -3425,16 +4479,16 @@"name": "engineFrom","kind": "function","path": "src/cli.ts",- "span": "L43-L46",+ "span": "L68-L70","signature": "function engineFrom(): Graft","exported": false,"origin": "ast",- "body_hash": "ddbb4f4e57bee5d05b95dc81f034e26183495162d84c6a290e12c6fda6c92ee8",+ "body_hash": "a8702efa2bdf4b53435b4de19b54bb861c1158e976334c561913e1e149df740e","summary_state": "ready",- "summary": "Creates an instance of the Graft engine configured with the specified context directory.",+ "summary": "Creates an instance of the Graft engine using the current CLI configuration, enabling graph operations.","crux": {- "code": " return new Graft({ contextDir: opts.dir });",- "span": "L28-L28"+ "code": "function engineFrom(): Graft {\n return new Graft(cliConfig());\n}",+ "span": "L68-L70"}},{@@ -3442,7 +4496,7 @@"name": "fmt","kind": "function","path": "src/cli.ts",- "span": "L82-L86",+ "span": "L106-L110","signature": "fmt = (o: Record<string, number>)","exported": false,"origin": "ast",@@ -3454,19 +4508,36 @@"span": "L42-L46"}},+ {+ "id": "src/cli.ts#GlobalOpts",+ "name": "GlobalOpts",+ "kind": "interface",+ "path": "src/cli.ts",+ "span": "L48-L54",+ "signature": "interface GlobalOpts",+ "exported": false,+ "origin": "ast",+ "body_hash": "9cf4b199ef21dbd1a2ea64ac02508675e2a8b3958dbbdb2a741dd2322145bc2e",+ "summary_state": "ready",+ "summary": "Holds the global options for the CLI, allowing configuration of the context graph generation and LLM provider settings.",+ "crux": null+ },{"id": "src/cli.ts#traverseAction","name": "traverseAction","kind": "function","path": "src/cli.ts",- "span": "L257-L263",+ "span": "L287-L293","signature": "function traverseAction(kind: import(\"./graph/traverse-cli.js\").TraverseKind)","exported": false,"origin": "ast","body_hash": "22a87797c4d09df4b6dcf4876910653663d7e7968bc0c19e90dc77a9a3d675b4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles traversal commands for graph analysis, allowing users to query relationships between symbols in the codebase.",+ "crux": {+ "code": " return async (symbol: string, dir: string, opts: { in?: string; json?: boolean; depth?: string }) => {\n const { runTraverseCommand } = await import(\"./graph/traverse-cli.js\");\n const globalOpts = program.opts<{ dir?: string }>();\n runTraverseCommand(kind, symbol, dir, { in: opts.in, json: opts.json, depth: opts.depth, globalDir: globalOpts.dir });\n };",+ "span": "L288-L292"+ }},{"id": "src/context/build.ts",@@ -4184,17 +5255,17 @@"name": "engine.ts","kind": "file","path": "src/engine.ts",- "span": "L1-L129",+ "span": "L1-L141","signature": null,"exported": true,"origin": "ast",- "body_hash": "68b18392490544224b551743dcf524ad370a34ec5f84ba443b1bf8a1d1476f9f",- "chars": 5145,- "summary_state": "stale",- "summary": "The Context Graph Engine builds and checks a code context graph from a repository without a database.",+ "body_hash": "55e2191dd67d1e4369c2a872f1b908937bd6034ce6f8f4b03e6c86a059e271c7",+ "chars": 5445,+ "summary_state": "ready",+ "summary": "The Graft class manages the construction and validation of a context graph from a code repository, ensuring it remains in sync with the codebase.","crux": {- "code": " * - {@link Graft.init} build `.context/` from a code repo.\n * - {@link Graft.check} report whether `.context/` is still in\n * sync with the code (for CI).\n *\n * The graph is a folder of linked markdown files committed to the repo; git is\n * the sync. This class wires the OpenRouter LLM providers into the build/check\n * pipelines; an API key is required for any LLM-backed operation.",- "span": "L5-L11"+ "code": " /** Build the `.context/` graph from the repo at `dir`. */\n async init(dir: string, opts: InitOptions = {}): Promise<BuildResult> {\n return buildContext(dir, {\n contextDir: this.cfg.contextDir,\n extensions: opts.extensions,\n model: this.modelLabel(),\n summarizer: this.summarizer(),\n synthesizer: this.synthesizer(),\n onProgress: opts.onProgress,\n });\n }\n",+ "span": "L54-L65"}},{@@ -4202,7 +5273,7 @@"name": "CheckRunOptions","kind": "interface","path": "src/engine.ts",- "span": "L33-L35",+ "span": "L35-L37","signature": "interface CheckRunOptions","exported": true,"origin": "ast",@@ -4216,30 +5287,50 @@"name": "Graft","kind": "class","path": "src/engine.ts",- "span": "L45-L128",+ "span": "L47-L140","signature": "class Graft","exported": true,"origin": "ast",- "body_hash": "77ee468ac84c61f0fbb143c6010c5fb04bb9948421092680d53a33e7c8388530",- "summary_state": "stale",- "summary": "Encapsulates methods for building and checking a context graph from a code repository.",- "crux": null+ "body_hash": "adb6ec4334ba397064dea215aa67225cda0e2ae630d092cb55289a43ec5ab406",+ "summary_state": "ready",+ "summary": "Manages the context graph operations, including building and checking synchronization with the codebase.",+ "crux": {+ "code": " /** Build the `.context/` graph from the repo at `dir`. */\n async init(dir: string, opts: InitOptions = {}): Promise<BuildResult> {\n return buildContext(dir, {\n contextDir: this.cfg.contextDir,\n extensions: opts.extensions,\n model: this.modelLabel(),\n summarizer: this.summarizer(),\n synthesizer: this.synthesizer(),\n onProgress: opts.onProgress,\n });\n }",+ "span": "L54-L64"+ }},{"id": "src/engine.ts#Graft.ask","name": "ask","kind": "method","path": "src/engine.ts",- "span": "L93-L95",+ "span": "L95-L97","signature": "ask(dir: string, query: string, opts: { limit?: number; source?: boolean; full?: boolean } = {}): AskResult","exported": true,"origin": "ast","body_hash": "f06a9cfee7165c009dc1154af3d19c72286f5e59f5df7fd0fd096836bbc1cf90",- "summary_state": "stale",- "summary": "Processes a query against the committed graph to return relevant information based on structural and lexical ranking.",+ "summary_state": "ready",+ "summary": "Processes a query against the context graph, returning results based on structural and lexical analysis.",+ "crux": {+ "code": " ask(dir: string, query: string, opts: { limit?: number; source?: boolean; full?: boolean } = {}): AskResult {\n return ask(dir, query, { contextDir: this.cfg.contextDir, limit: opts.limit, source: opts.source, full: opts.full });",+ "span": "L95-L96"+ }+ },+ {+ "id": "src/engine.ts#Graft.chatModel",+ "name": "chatModel",+ "kind": "method",+ "path": "src/engine.ts",+ "span": "L102-L119",+ "signature": "private chatModel(): ChatModel",+ "exported": true,+ "origin": "ast",+ "body_hash": "8027a62d0dbb02b564aaf97010177ba193d415b944639211a6aa8604049001d0",+ "summary_state": "ready",+ "summary": "Retrieves the configured chat model or throws an error if the API key is missing, ensuring proper setup for LLM operations.","crux": {- "code": " ask(dir: string, query: string, opts: { limit?: number; source?: boolean } = {}): AskResult {",- "span": "L93-L93"+ "code": " if (!this.cfg.apiKey) {\n throw new Error(\n \"No API key. Set GRAFT_API_KEY (and GRAFT_PROVIDER / GRAFT_BASE_URL / GRAFT_MODEL \" +\n \"for your provider) to build or summarize the graph.\",\n );\n }",+ "span": "L105-L110"}},{@@ -4247,7 +5338,7 @@"name": "check","kind": "method","path": "src/engine.ts",- "span": "L65-L67",+ "span": "L67-L69","signature": "check(dir: string, opts: CheckRunOptions = {}): CheckResult","exported": true,"origin": "ast",@@ -4264,7 +5355,7 @@"name": "checkGraph","kind": "method","path": "src/engine.ts",- "span": "L70-L72",+ "span": "L72-L74","signature": "checkGraph(dir: string): GraphCheckResult","exported": true,"origin": "ast",@@ -4281,7 +5372,7 @@"name": "constructor","kind": "method","path": "src/engine.ts",- "span": "L48-L50",+ "span": "L50-L52","signature": "constructor(config: EngineConfig = {})","exported": true,"origin": "ast",@@ -4298,16 +5389,16 @@"name": "cruxSummarizer","kind": "method","path": "src/engine.ts",- "span": "L114-L116",+ "span": "L126-L128","signature": "private cruxSummarizer(): CruxSummarizer","exported": true,"origin": "ast",- "body_hash": "3b07279c83115a1232de5b510ce2f501f8699e7b8c70a052c4c455e136f01ca6",+ "body_hash": "59d1f34a9105fe6c97198009342ac29f8c7047efa2ba68f10001439bf14a14cd","summary_state": "ready",- "summary": "Creates a crux summarizer for the code graph's Tier-2 pass, ensuring it is properly configured.",+ "summary": "Returns a crux summarizer for the Tier-2 pass of the code graph, ensuring detailed summarization of nodes.","crux": {- "code": " private cruxSummarizer(): CruxSummarizer {\n return new OpenRouterCruxSummarizer(this.requireKey(), this.cfg.openrouterModel, this.cfg.openrouterBaseUrl);\n }",- "span": "L111-L113"+ "code": " private cruxSummarizer(): CruxSummarizer {\n return this.cfg.cruxSummarizer ?? new ChatCruxSummarizer(this.chatModel());\n }",+ "span": "L126-L128"}},{@@ -4315,7 +5406,7 @@"name": "graph","kind": "method","path": "src/engine.ts",- "span": "L79-L86",+ "span": "L81-L88","signature": "graph(dir: string, opts: GraphRunOptions = {}): Promise<GraphBuildResult>","exported": true,"origin": "ast",@@ -4332,7 +5423,7 @@"name": "init","kind": "method","path": "src/engine.ts",- "span": "L53-L62",+ "span": "L55-L64","signature": "async init(dir: string, opts: InitOptions = {}): Promise<BuildResult>","exported": true,"origin": "ast",@@ -4349,33 +5440,16 @@"name": "modelLabel","kind": "method","path": "src/engine.ts",- "span": "L124-L127",+ "span": "L135-L139","signature": "private modelLabel(): string","exported": true,"origin": "ast",- "body_hash": "7034c4cd5e06b1b37f2ef068736f35fddaca136a3cae2ae5e595fda7efa2bd89",- "summary_state": "ready",- "summary": "Determines the human-readable label for the active model used in the context graph.",- "crux": {- "code": " private modelLabel(): string {\n if (this.cfg.synthesizer || this.cfg.summarizer) return \"custom\";\n return `openrouter:${this.cfg.openrouterModel}`;\n }",- "span": "L121-L124"- }- },- {- "id": "src/engine.ts#Graft.requireKey",- "name": "requireKey",- "kind": "method",- "path": "src/engine.ts",- "span": "L98-L106",- "signature": "private requireKey(): string",- "exported": true,- "origin": "ast",- "body_hash": "9aed1d64896a6e8f8d3cd6c00e53f8e8baf2b424e0522d28408861b2f7c22912",+ "body_hash": "54b282db93470ea6937b432de6889d721755de5b7bd67bada35be5237b11021c","summary_state": "ready",- "summary": "Ensures that a valid OpenRouter API key is available, throwing an error if it is not set.",+ "summary": "Determines the human-readable label for the active model, which is recorded in the manifest for reference.","crux": {- "code": " if (!this.cfg.openrouterApiKey) {\n throw new Error(\n \"No OpenRouter API key. Set OPENROUTER_API_KEY (get one at https://openrouter.ai/keys) \" +\n \"to build or summarize the graph.\",\n );\n }\n return this.cfg.openrouterApiKey;",- "span": "L96-L102"+ "code": " private modelLabel(): string {\n if (this.cfg.chatModel) return this.cfg.chatModel.label;\n if (this.cfg.synthesizer || this.cfg.summarizer || this.cfg.cruxSummarizer) return \"custom\";\n return `${this.cfg.provider}:${this.cfg.model}`;\n }",+ "span": "L135-L139"}},{@@ -4383,16 +5457,16 @@"name": "summarizer","kind": "method","path": "src/engine.ts",- "span": "L118-L121",+ "span": "L130-L132","signature": "private summarizer(): Summarizer","exported": true,"origin": "ast",- "body_hash": "160e884c1dd10b916c36a737886880d98430fb84c5dd7828e69536b8198e3b2f",+ "body_hash": "b1360c129530fa4de856caf6d8e6aa6479d7cad492fea9f5e93ee82becd9ac22","summary_state": "ready",- "summary": "Obtains the summarizer instance, initializing it if no custom summarizer is provided.",+ "summary": "Fetches the summarizer for generating summaries, defaulting to a chat summarizer if not explicitly set.","crux": {- "code": " private summarizer(): Summarizer {\n if (this.cfg.summarizer) return this.cfg.summarizer;\n return new OpenRouterSummarizer(this.requireKey(), this.cfg.openrouterModel, this.cfg.openrouterBaseUrl);\n }",- "span": "L115-L118"+ "code": " private summarizer(): Summarizer {\n return this.cfg.summarizer ?? new ChatSummarizer(this.chatModel());\n }",+ "span": "L130-L132"}},{@@ -4400,16 +5474,16 @@"name": "synthesizer","kind": "method","path": "src/engine.ts",- "span": "L108-L111",+ "span": "L121-L123","signature": "private synthesizer(): Synthesizer","exported": true,"origin": "ast",- "body_hash": "2a65f2a449bd40274d81542edfb36e20ceb8cf0160b030e8bd42b9698a386d20",+ "body_hash": "5e3e4becf7575fbae3d5093185d5fcba1fcdc49ae45227c94a9c537a9ac61c5d","summary_state": "ready",- "summary": "Retrieves the synthesizer instance, creating one if it is not already configured.",+ "summary": "Provides the synthesizer for generating responses, defaulting to a chat synthesizer if none is configured.","crux": {- "code": " private synthesizer(): Synthesizer {\n if (this.cfg.synthesizer) return this.cfg.synthesizer;\n return new OpenRouterSynthesizer(this.requireKey(), this.cfg.openrouterModel, this.cfg.openrouterBaseUrl);\n }",- "span": "L105-L108"+ "code": " private synthesizer(): Synthesizer {\n return this.cfg.synthesizer ?? new ChatSynthesizer(this.chatModel());\n }",+ "span": "L121-L123"}},{@@ -4417,7 +5491,7 @@"name": "GraphRunOptions","kind": "interface","path": "src/engine.ts",- "span": "L37-L43",+ "span": "L39-L45","signature": "interface GraphRunOptions","exported": true,"origin": "ast",@@ -4431,7 +5505,7 @@"name": "InitOptions","kind": "interface","path": "src/engine.ts",- "span": "L26-L31",+ "span": "L28-L33","signature": "interface InitOptions","exported": true,"origin": "ast",@@ -4451,9 +5525,12 @@"origin": "ast","body_hash": "5cfcbb66a1aa754f3b56d68c09d5bcf52f5002a67abd70cc8f1a8d0c1dddce6a","chars": 14041,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file implements a binding pass that resolves variable types in a parsed file, enabling accurate type lookups for local variables, parameters, and class fields during code analysis.",+ "crux": {+ "code": " set(scopePath: string, name: string, type: string): void {\n this.map.set(`${scopePath}|${name}`, type);\n }\n\n /** Innermost-first: for scope [\"a\",\"b\"] name \"x\", tries `a.b|x`, `a|x`, `|x`. */\n lookup(scope: string[], name: string): string | null {\n for (let i = scope.length; i >= 0; i--) {\n const hit = this.map.get(`${scope.slice(0, i).join(\".\")}|${name}`);\n if (hit) return hit;\n }\n return null;",+ "span": "L21-L31"+ }},{"id": "src/graph/bindings.ts#callTypeName",@@ -4465,9 +5542,12 @@"exported": false,"origin": "ast","body_hash": "1142e3a6b9cbf15363de7f4a6b63e29fcbda79257c58b9908e163cae86e1a0c2",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the type name from a call expression, which is important for understanding the types of function calls in the code.",+ "crux": {+ "code": "function callTypeName(node: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null {\n if (node?.type !== \"call\") return null;\n const fn = node.childForFieldName(\"function\");\n if (fn?.type !== \"identifier\") return null;\n return aliases.get(fn.text) ?? fn.text;\n}",+ "span": "L202-L207"+ }},{"id": "src/graph/bindings.ts#collectAliases",@@ -4479,9 +5559,12 @@"exported": false,"origin": "ast","body_hash": "4222a97dc61f81be4c7c795013ee09c14b2575fa0fd21dbb005a8e9e6b44513a",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Scans the syntax tree to collect import aliases, ensuring that type resolution accounts for aliased names in the code.",+ "crux": {+ "code": "function collectAliases(node: Parser.SyntaxNode, lang: Language, aliases: Map<string, string>): void {\n if (lang === \"python\" && node.type === \"aliased_import\") {\n const nameNode = node.childForFieldName(\"name\");\n const aliasNode = node.childForFieldName(\"alias\");\n if (nameNode && aliasNode) {\n const orig = nameNode.type === \"dotted_name\" ? (nameNode.namedChildren.at(-1)?.text ?? nameNode.text) : nameNode.text;\n aliases.set(aliasNode.text, orig);\n }\n } else if ((lang === \"typescript\" || lang === \"tsx\") && node.type === \"import_specifier\") {\n const nameNode = node.childForFieldName(\"name\");\n const aliasNode = node.childForFieldName(\"alias\");\n if (nameNode && aliasNode) aliases.set(aliasNode.text, nameNode.text);",+ "span": "L142-L153"+ }},{"id": "src/graph/bindings.ts#collectBindings",@@ -4493,9 +5576,12 @@"exported": true,"origin": "ast","body_hash": "132de062858baae6517153462acf369bc86e13651952480acdbb253f07698f21",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Traverses a parsed syntax tree to gather variable-to-type bindings, which are essential for type resolution in the codebase.",+ "crux": {+ "code": "export function collectBindings(root: Parser.SyntaxNode, lang: Language): FileBindings {\n const bindings = new FileBindings();\n const aliases = new Map<string, string>();\n collectAliases(root, lang, aliases);\n visit(root, lang, [], null, bindings, aliases);\n return bindings;\n}",+ "span": "L132-L138"+ }},{"id": "src/graph/bindings.ts#defName",@@ -4507,9 +5593,12 @@"exported": true,"origin": "ast","body_hash": "dfc038207eec571860ec5f6c8900f00f453254c23b22fd3874921c3f71fd8317",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the name of a definition node (like a function or class) based on its syntax, aiding in the identification of types during analysis.",+ "crux": {+ "code": "export function defName(node: Parser.SyntaxNode, lang: Language): string | null {\n if (lang === \"go\") {\n if (node.type === \"method_declaration\") {\n const name = node.childForFieldName(\"name\")?.text;\n if (!name) return null;\n const recv = goReceiverTypeOf(node);\n return recv ? `${recv}.${name}` : name;\n }\n if (node.type === \"function_declaration\" || node.type === \"type_spec\") {\n return node.childForFieldName(\"name\")?.text ?? null;\n }\n return null;",+ "span": "L45-L56"+ }},{"id": "src/graph/bindings.ts#FileBindings",@@ -4521,9 +5610,12 @@"exported": true,"origin": "ast","body_hash": "19908ed6e06f561286fc85a8cac0c560d1babb4d856658f9783dc67c9c8c1679",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Manages the mapping of variable/field names to their types within different scopes, enabling type resolution during code analysis.",+ "crux": {+ "code": " set(scopePath: string, name: string, type: string): void {\n this.map.set(`${scopePath}|${name}`, type);\n }",+ "span": "L21-L23"+ }},{"id": "src/graph/bindings.ts#FileBindings.lookup",@@ -4535,9 +5627,12 @@"exported": true,"origin": "ast","body_hash": "675fb0f092ed5acc91063e941c243037560f93003456d5a5a127112c5e7e12cd",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Retrieves the type associated with a variable or field name from the closest matching scope, facilitating type resolution in nested contexts.",+ "crux": {+ "code": " lookup(scope: string[], name: string): string | null {\n for (let i = scope.length; i >= 0; i--) {\n const hit = this.map.get(`${scope.slice(0, i).join(\".\")}|${name}`);\n if (hit) return hit;\n }\n return null;\n }",+ "span": "L26-L32"+ }},{"id": "src/graph/bindings.ts#FileBindings.set",@@ -4549,9 +5644,12 @@"exported": true,"origin": "ast","body_hash": "9027da9c550dcb7059bfabc81dfe561504b7b512caeb20631d0563463b5a7016",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Records the type of a variable or field in the specified scope, allowing for later retrieval during type resolution.",+ "crux": {+ "code": " set(scopePath: string, name: string, type: string): void {\n this.map.set(`${scopePath}|${name}`, type);\n }",+ "span": "L21-L23"+ }},{"id": "src/graph/bindings.ts#goReceiverTypeOf",@@ -4563,9 +5661,12 @@"exported": false,"origin": "ast","body_hash": "78374b16a5d2b5c21465a6a299cff5c422327d2c6402a03e88993526b69afe1a",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the base type of a receiver in a Go method, which is crucial for type resolution in method calls.",+ "crux": {+ "code": "function goReceiverTypeOf(node: Parser.SyntaxNode): string | null {\n const recv = node.childForFieldName(\"receiver\");\n const param = recv?.namedChildren.find((c) => c.type === \"parameter_declaration\");\n let type = param?.childForFieldName(\"type\");\n if (type?.type === \"pointer_type\") type = type.namedChildren.at(-1) ?? null;\n return type?.type === \"type_identifier\" ? type.text : null;\n}",+ "span": "L91-L97"+ }},{"id": "src/graph/bindings.ts#goReceiverVarOf",@@ -4577,9 +5678,12 @@"exported": true,"origin": "ast","body_hash": "a824bc4cfb8364a115c60e40390e9abf6c580976177ee4b0fe5028f272175414",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts the variable name of the receiver parameter from a Go method node, which is essential for understanding method context.",+ "crux": {+ "code": "export function goReceiverVarOf(node: Parser.SyntaxNode): string | null {\n const recv = node.childForFieldName(\"receiver\");\n const param = recv?.namedChildren.find((c) => c.type === \"parameter_declaration\");\n return param?.childForFieldName(\"name\")?.text ?? null;\n}",+ "span": "L81-L85"+ }},{"id": "src/graph/bindings.ts#handleGo",@@ -4591,9 +5695,12 @@"exported": false,"origin": "ast","body_hash": "f5f75a60c9e0b8689d2ad6bbe6dc12e6bf5ef88e7a1157b115d34a7cbd1846ac",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles the processing of Go nodes to extract type information, ensuring that type resolution is accurate for Go code.",+ "crux": {+ "code": "function handleGo(node: Parser.SyntaxNode, scope: string[], bindings: FileBindings): void {\n const scopePath = scope.join(\".\");\n if (node.type === \"var_spec\") {\n const name = node.childForFieldName(\"name\");\n let type = node.childForFieldName(\"type\");\n if (type?.type === \"pointer_type\") type = type.namedChildren.at(-1) ?? null;\n if (name?.type === \"identifier\" && type?.type === \"type_identifier\") {\n bindings.set(scopePath, name.text, type.text);\n }\n return;\n }\n if (node.type !== \"short_var_declaration\") return;",+ "span": "L287-L298"+ }},{"id": "src/graph/bindings.ts#handlePy",@@ -4605,9 +5712,12 @@"exported": false,"origin": "ast","body_hash": "1c564356d137b8086c52e38f67ff0ca1646212aeb89e93bbacb3282172cec8e1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles the processing of Python nodes to extract type information, contributing to the overall type resolution process.",+ "crux": {+ "code": "function handlePy(\n node: Parser.SyntaxNode,\n scope: string[],\n classScope: string | null,\n bindings: FileBindings,\n aliases: Map<string, string>,\n): void {\n const scopePath = scope.join(\".\");\n if (node.type === \"typed_parameter\") {\n const nameNode = node.namedChildren.find((c) => c.type === \"identifier\");\n const typeName = pyTypeName(node.childForFieldName(\"type\"), aliases);\n if (nameNode && typeName) bindings.set(scopePath, nameNode.text, typeName);",+ "span": "L209-L220"+ }},{"id": "src/graph/bindings.ts#handleTs",@@ -4619,9 +5729,12 @@"exported": false,"origin": "ast","body_hash": "61f3e570f631fdbc6bb8bc3323b05e0062eeef973368cce674bc3a93644b8dba",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Processes TypeScript nodes to gather type information, which is essential for accurate type resolution in TypeScript code.",+ "crux": {+ "code": "function handleTs(\n node: Parser.SyntaxNode,\n scope: string[],\n classScope: string | null,\n bindings: FileBindings,\n aliases: Map<string, string>,\n): void {\n const scopePath = scope.join(\".\");\n if (node.type === \"variable_declarator\") {\n const value = node.childForFieldName(\"value\");\n if (value && FN_VALUE_TYPES.has(value.type)) return; // a function def, not a type binding\n const name = node.childForFieldName(\"name\");",+ "span": "L257-L268"+ }},{"id": "src/graph/bindings.ts#isClassNode",@@ -4633,9 +5746,12 @@"exported": false,"origin": "ast","body_hash": "c74d234cc18f7097a4f71d4ff572a8660c7003c82f7d0938f972564845864a32",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Checks if a given node represents a class definition, which is important for understanding the structure of the code being analyzed.",+ "crux": {+ "code": "function isClassNode(node: Parser.SyntaxNode, lang: Language): boolean {\n if (lang === \"python\") return node.type === \"class_definition\";\n if (lang === \"typescript\" || lang === \"tsx\") {\n return node.type === \"class_declaration\" || node.type === \"abstract_class_declaration\";\n }\n return false;\n}",+ "span": "L123-L129"+ }},{"id": "src/graph/bindings.ts#pyTypeName",@@ -4647,9 +5763,12 @@"exported": false,"origin": "ast","body_hash": "e3f0ef8b9205ddeb7f2bccc89c1100745b73301e6d65f4a5090ed43fef3ffd49",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts and resolves the type name from a Python node, which is necessary for accurate type binding in Python code.",+ "crux": {+ "code": "function pyTypeName(node: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null {\n if (!node) return null;\n if (node.type === \"identifier\") return resolveAlias(node.text, aliases);\n if (node.type === \"type\") {\n const inner = node.namedChildren[0];\n return inner?.type === \"identifier\" ? resolveAlias(inner.text, aliases) : null;\n }\n return null;\n}",+ "span": "L192-L200"+ }},{"id": "src/graph/bindings.ts#resolveAlias",@@ -4661,9 +5780,12 @@"exported": false,"origin": "ast","body_hash": "57147e33c3f450e825a480f2adb620f8c470472ee69afe5075f163e81752cf18",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Resolves a name through the collected aliases, ensuring that type lookups are accurate even when using aliased names.",+ "crux": {+ "code": "function resolveAlias(name: string, aliases: Map<string, string>): string {\n return aliases.get(name) ?? name;\n}",+ "span": "L188-L190"+ }},{"id": "src/graph/bindings.ts#resolveRecvType",@@ -4675,9 +5797,12 @@"exported": true,"origin": "ast","body_hash": "fdc0ccb4d1186b98b4d805519bb3c23ecde386bdd78a6c0e3d5e421b63fe6594",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Resolves the type of a receiver in a method call based on the current context, ensuring accurate type information is used during analysis.",+ "crux": {+ "code": "export function resolveRecvType(\n receiver: string | undefined,\n ctx: Pick<WalkCtx, \"scope\" | \"enclosingClass\" | \"goReceiverVar\" | \"lang\" | \"bindings\">,\n): string | undefined {\n if (!receiver) return undefined;\n if (receiver === \"self\" || receiver === \"cls\" || receiver === \"this\") return ctx.enclosingClass ?? undefined;\n if (receiver.startsWith(\"self.\") || receiver.startsWith(\"this.\")) {\n return (\n ctx.bindings.lookup(ctx.scope, receiver) ??\n ctx.bindings.lookup(ctx.scope, receiver.replace(/^this\\./, \"self.\")) ??\n undefined\n );",+ "span": "L103-L114"+ }},{"id": "src/graph/bindings.ts#tsAnnotationTypeName",@@ -4689,9 +5814,12 @@"exported": false,"origin": "ast","body_hash": "6ab85b25d2211b7cce5a9901c7b450a1902ff95e5234b1119836a467d57c68ed",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts the type name from TypeScript annotation nodes, which is crucial for type resolution in TypeScript code.",+ "crux": {+ "code": "function tsAnnotationTypeName(\n typeAnn: Parser.SyntaxNode | null | undefined,\n aliases: Map<string, string>,\n): string | null {\n if (!typeAnn || typeAnn.type !== \"type_annotation\") return null;\n const t = typeAnn.namedChildren[0];\n return t?.type === \"type_identifier\" ? resolveAlias(t.text, aliases) : null;\n}",+ "span": "L241-L248"+ }},{"id": "src/graph/bindings.ts#tsNewTypeName",@@ -4703,9 +5831,12 @@"exported": false,"origin": "ast","body_hash": "974b137011eeae18fd510c7ff38fd2bab7dee9d20ca1434ca492c38e369e203b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the type name from a TypeScript new expression, aiding in the resolution of types during analysis.",+ "crux": {+ "code": "function tsNewTypeName(value: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null {\n if (value?.type !== \"new_expression\") return null;\n const ctor = value.childForFieldName(\"constructor\");\n if (ctor?.type !== \"identifier\") return null;\n return aliases.get(ctor.text) ?? ctor.text;\n}",+ "span": "L250-L255"+ }},{"id": "src/graph/bindings.ts#visit",@@ -4717,9 +5848,12 @@"exported": false,"origin": "ast","body_hash": "fdf216c190f3963b2a3f1d7e97be3a98709efedc167777ceb79abf31c0d078ce",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Recursively processes nodes in the syntax tree to build up type bindings and scopes, facilitating comprehensive type analysis.",+ "crux": {+ "code": "function visit(\n node: Parser.SyntaxNode,\n lang: Language,\n scope: string[],\n classScope: string | null,\n bindings: FileBindings,\n aliases: Map<string, string>,\n): void {\n if (lang === \"python\") handlePy(node, scope, classScope, bindings, aliases);\n else if (lang === \"go\") handleGo(node, scope, bindings);\n else handleTs(node, scope, classScope, bindings, aliases);\n",+ "span": "L162-L173"+ }},{"id": "src/graph/build.ts",@@ -4732,12 +5866,9 @@"origin": "ast","body_hash": "10ae2a085b299a56cb90d41289a956065dd8eef358ae2abbc39db59b82a12dc9","chars": 6887,- "summary_state": "stale",- "summary": "This file defines the logic to build a graph representation from source code files in a repository.",- "crux": {- "code": "export async function buildGraph(\n dir: string,\n opts: GraphBuildOptions = {},\n): Promise<GraphBuildResult> {\n const root = resolve(dir);\n const outDir = contextDirFor(root, opts.contextDir);\n const files = listSourceFiles(root, outDir);\n\n const nodes: NodeV1[] = [];\n const rawEdges: RawEdge[] = [];\n const sources = new Map<string, string>();\n const langs = new Set<Language>();",- "span": "L57-L68"- }+ "summary_state": "ready",+ "summary": "This file defines the logic for building a graph representation of a code repository, including parsing source files and resolving dependencies.",+ "crux": null},{"id": "src/graph/build.ts#buildGraph",@@ -4749,11 +5880,11 @@"exported": true,"origin": "ast","body_hash": "d1af486578fcbf56fba090f509e508dd3643f0b735167a7277b055e3cf16e450",- "summary_state": "stale",- "summary": "This function orchestrates the process of reading source files, extracting nodes and edges, and writing the resulting graph to a file.",+ "summary_state": "ready",+ "summary": "This function orchestrates the entire graph building process, from parsing source files to writing the final graph output.","crux": {- "code": " const edges = resolveEdges(nodes, rawEdges);\n\n // graph.json is its own Tier-2 cache: fold in the prior meaning layer so an\n // unchanged body is never re-summarized (and a Tier-1-only run never wipes it).\n const prior = readGraph(wiringPath(outDir));\n const priorById = new Map((prior?.nodes ?? []).map((n) => [n.id, n]));\n const meaning = await enrichGraph(nodes, priorById, sources, {\n summarizer: opts.summarizer,\n concurrency: opts.concurrency,\n onProgress: ({ index, total, node }) =>\n opts.onProgress?.({ phase: \"enrich\", index, total, file: node }),\n });",- "span": "L93-L104"+ "code": "export async function buildGraph(\n dir: string,\n opts: GraphBuildOptions = {},\n): Promise<GraphBuildResult> {\n const root = resolve(dir);\n const outDir = contextDirFor(root, opts.contextDir);\n const files = listSourceFiles(root, outDir);\n\n const nodes: NodeV1[] = [];\n const rawEdges: RawEdge[] = [];\n const sources = new Map<string, string>();\n const langs = new Set<Language>();",+ "span": "L78-L89"}},{@@ -4811,9 +5942,12 @@"exported": false,"origin": "ast","body_hash": "02cadfa0e94721ec1c8de1ff70b9b2b3e1ce1c54086c49d5163d3a7f3b266982",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This function identifies and reads Go modules from the repository to facilitate edge resolution for Go import paths.",+ "crux": {+ "code": "function readGoModules(root: string): GoModule[] {\n const mods: GoModule[] = [];\n for (const f of walkDir(root)) {\n if (basename(f) !== \"go.mod\") continue;\n try {\n const m = readFileSync(f, \"utf8\").match(/^\\s*module\\s+(\\S+)/m);\n if (!m) continue;\n const rel = relative(root, dirname(f)).split(sep).join(\"/\");\n mods.push({ module: m[1], dir: rel === \"\" ? \".\" : rel });\n } catch {\n /* unreadable go.mod — skip this module */\n }",+ "span": "L62-L73"+ }},{"id": "src/graph/cards.ts",@@ -5292,11 +6426,11 @@"origin": "ast","body_hash": "8449958d4b5fd74c8eafeb488ae16cb60dcaf3e5fcaf1e3069cebf4cf9ef48d9","chars": 19990,- "summary_state": "stale",- "summary": "This module extracts structured data from source files into a normalized format for further processing.",+ "summary_state": "ready",+ "summary": "This file provides functionality to extract and represent code structure from source files into a standardized format for further processing.","crux": {- "code": " return { nodes, rawEdges };",- "span": "L126-L126"+ "code": "/**\n * Tier-1 extraction: source file → {@link NodeV1}[] + raw edges, via tree-sitter.\n *\n * Deterministic and dependency-only (no LLM, no network). Emits one node per\n * definition (file, class, function, method, interface, type, enum, and TS\n * arrow-function consts) plus unresolved edge intents. Edge *targets* are\n * resolved against the whole-repo node index later, in build.ts.\n */",+ "span": "L1-L8"}},{@@ -5309,11 +6443,11 @@"exported": false,"origin": "ast","body_hash": "9c911a104a07cec5e22e4448197a54939d77a9eda45a1a14c67a62a722f61de3",- "summary_state": "stale",- "summary": "Extracts the name of a function or method being called in the syntax tree.",+ "summary_state": "ready",+ "summary": "Extracts the name and context of a function call from the syntax tree, including receiver information.","crux": {- "code": " if (fn.type === \"identifier\") return { name: fn.text, viaMember: false };\n if (lang === \"python\" && fn.type === \"attribute\") {\n const a = fn.childForFieldName(\"attribute\") ?? fn.namedChildren.at(-1);\n return a ? { name: a.text, viaMember: true } : null;\n }\n if (lang !== \"python\" && fn.type === \"member_expression\") {\n const p = fn.childForFieldName(\"property\") ?? fn.namedChildren.at(-1);\n return p ? { name: p.text, viaMember: true } : null;",- "span": "L250-L257"+ "code": "function calleeName(\n node: Parser.SyntaxNode,\n lang: Language,\n): { name: string; viaMember: boolean; receiver?: string } | null {\n const fn = node.childForFieldName(\"function\");\n if (!fn) return null;\n if (fn.type === \"identifier\") return { name: fn.text, viaMember: false };\n if (lang === \"python\" && fn.type === \"attribute\") {\n const a = fn.childForFieldName(\"attribute\") ?? fn.namedChildren.at(-1);\n return a ? { name: a.text, viaMember: true, receiver: pyReceiver(fn) } : null;\n }\n if (lang === \"go\" && fn.type === \"selector_expression\") {",+ "span": "L405-L416"}},{@@ -5343,9 +6477,12 @@"exported": false,"origin": "ast","body_hash": "ed38eee7d2f573a31deea6ef15de2d05409f8ecf4f39ab4234c0bbcc14c66198",- "summary_state": "stale",- "summary": "Describes a definition in the syntax tree, including its name and type.",- "crux": null+ "summary_state": "ready",+ "summary": "Describes a code definition with its relevant metadata for extraction purposes.",+ "crux": {+ "code": "interface DefDescriptor {\n name: string; // the bare symbol name (used for the node's `name` and call resolution)\n idName?: string; // id-scope segment when it differs from `name` (Go: `Receiver.method`)\n kind: Kind;\n headerEnd: number; // char index where the signature ends (body starts)\n hashNode: Parser.SyntaxNode; // node whose text forms body_hash / span\n}",+ "span": "L150-L156"+ }},{"id": "src/graph/extract.ts#describe",@@ -5357,11 +6494,11 @@"exported": false,"origin": "ast","body_hash": "724ba386be23031ee221f1721155296b86dce3c9908c26bdd68848e0e6a37a1b",- "summary_state": "stale",- "summary": "Identifies and describes definitions in the syntax tree based on their node types.",+ "summary_state": "ready",+ "summary": "Identifies and describes the shape of code definitions based on their syntax tree representation.","crux": {- "code": " if (mapped) {\n const name = node.childForFieldName(\"name\")?.text;\n if (!name) return null;\n let kind = mapped;\n if (ctx.lang === \"python\" && mapped === \"function\" && ctx.enclosingKind === \"class\") {\n kind = \"method\";\n }\n const body = node.childForFieldName(\"body\");\n return { name, kind, headerEnd: body ? body.startIndex : node.endIndex, hashNode: node };\n }",- "span": "L186-L195"+ "code": "function describe(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | null {\n if (ctx.lang === \"go\") return describeGo(node, ctx);\n\n const mapped = ctx.kinds[node.type];\n if (mapped) {\n const name = node.childForFieldName(\"name\")?.text;\n if (!name) return null;\n let kind = mapped;\n if (ctx.lang === \"python\" && mapped === \"function\" && ctx.enclosingKind === \"class\") {\n kind = \"method\";\n }\n const body = node.childForFieldName(\"body\");",+ "span": "L282-L293"}},{@@ -5374,9 +6511,12 @@"exported": false,"origin": "ast","body_hash": "4e7f1a5f6681729c6592b514762ab354ecf0bf9b2a8cd86bfea5415d75b6c56d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Describes Go-specific code definitions, including functions and methods, from the syntax tree.",+ "crux": {+ "code": "function describeGo(node: Parser.SyntaxNode, _ctx: WalkCtx): DefDescriptor | null {\n if (node.type === \"function_declaration\") {\n const name = node.childForFieldName(\"name\")?.text;\n if (!name) return null;\n const body = node.childForFieldName(\"body\");\n return { name, kind: \"function\", headerEnd: body ? body.startIndex : node.endIndex, hashNode: node };\n }\n\n if (node.type === \"method_declaration\") {\n const name = node.childForFieldName(\"name\")?.text;\n if (!name) return null;\n const recv = goReceiverType(node);",+ "span": "L318-L329"+ }},{"id": "src/graph/extract.ts#extractFile",@@ -5388,11 +6528,11 @@"exported": true,"origin": "ast","body_hash": "5522857555c6dfaa28878349fb9388619fa166f997b7bb5b442ae6be1153a595",- "summary_state": "stale",- "summary": "Extracts nodes and edges from a source file based on its syntax tree.",+ "summary_state": "ready",+ "summary": "Extracts nodes and edges from a source file, representing its structure in a standardized format.","crux": {- "code": " return { nodes, rawEdges };",- "span": "L126-L126"+ "code": "export function extractFile(rel: string, source: string, lang: Language): ExtractResult {\n parser.setLanguage(GRAMMARS[lang] as never);\n const root = parseSource(source);\n const bindings = collectBindings(root, lang);\n\n const nodes: NodeV1[] = [\n {\n id: rel,\n name: basename(rel),\n kind: \"file\",\n path: rel,\n span: `L1-L${root.endPosition.row + 1}`,",+ "span": "L168-L179"}},{@@ -5419,9 +6559,12 @@"exported": false,"origin": "ast","body_hash": "fc01f952b2cff13ab8af6748f1ad94168e5cef0015a100f090331cd428d09f4b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts the module-level residual content from a source file that is not covered by any symbol definitions.",+ "crux": {+ "code": "function fileResidual(source: string, symbols: NodeV1[]): string {\n const lines = source.split(\"\\n\");\n const covered = new Uint8Array(lines.length + 2);\n for (const s of symbols) {\n const m = s.span.match(/^L(\\d+)-L(\\d+)$/);\n if (!m) continue;\n for (let r = Number(m[1]); r <= Number(m[2]) && r < covered.length; r++) covered[r] = 1;\n }\n const kept: string[] = [];\n for (let i = 0; i < lines.length; i++) if (!covered[i + 1]) kept.push(lines[i]);\n return searchBody(kept.join(\" \"), MAX_FILE_BODY_CHARS);\n}",+ "span": "L78-L89"+ }},{"id": "src/graph/extract.ts#goExported",@@ -5433,9 +6576,12 @@"exported": false,"origin": "ast","body_hash": "d63372a3436b530577ba2055e6ea2ba440d16206d299c19a81e6f9d11fbb857e",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines if a Go symbol is exported based on its naming convention.",+ "crux": {+ "code": "function goExported(name: string): boolean {\n const own = name.includes(\".\") ? name.slice(name.lastIndexOf(\".\") + 1) : name;\n const first = own[0] ?? \"\";\n return first !== first.toLowerCase() && first === first.toUpperCase();\n}",+ "span": "L370-L374"+ }},{"id": "src/graph/extract.ts#goReceiverType",@@ -5447,9 +6593,12 @@"exported": false,"origin": "ast","body_hash": "1487f5274066918e95fd92b382636fe3ead06f927349744bde2289a732c5c7ae",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts the base type name of a receiver for Go methods, if applicable.",+ "crux": {+ "code": "function goReceiverType(node: Parser.SyntaxNode): string | null {\n const recv = node.childForFieldName(\"receiver\"); // parameter_list\n const param = recv?.namedChildren.find((c) => c.type === \"parameter_declaration\");\n let type = param?.childForFieldName(\"type\");\n if (type?.type === \"pointer_type\") type = type.namedChildren.at(-1) ?? null;\n return type?.type === \"type_identifier\" ? type.text : null;\n}",+ "span": "L360-L366"+ }},{"id": "src/graph/extract.ts#heritageEdges",@@ -5478,12 +6627,9 @@"exported": false,"origin": "ast","body_hash": "0a0b7079eca209656048651dc132aa4dd7ed735b2ee04bc63e3a887e5aa0a1e8",- "summary_state": "stale",- "summary": "Extracts the module name from an import statement in the syntax tree.",- "crux": {- "code": "function importSpecifier(node: Parser.SyntaxNode, lang: Language): string | null {\n if (lang === \"python\") {\n const m =\n node.childForFieldName(\"module_name\") ??\n node.namedChildren.find((c) => c.type === \"dotted_name\" || c.type === \"relative_import\");\n return m?.text ?? null;\n }\n const str = node.namedChildren.find((c) => c.type === \"string\");\n if (!str) return null;\n const frag = str.namedChildren.find((c) => c.type === \"string_fragment\");\n return frag?.text ?? str.text.replace(/^['\"]|['\"]$/g, \"\");",- "span": "L266-L276"- }+ "summary_state": "ready",+ "summary": "Extracts the module path from an import statement in the syntax tree.",+ "crux": null},{"id": "src/graph/extract.ts#isImport",@@ -5495,8 +6641,8 @@"exported": false,"origin": "ast","body_hash": "dd3cad276b6f4a2258722865073f7cde28f74612df009ea697b0ce6d599257b1",- "summary_state": "stale",- "summary": "Determines if a node represents an import statement in the syntax tree.",+ "summary_state": "ready",+ "summary": "Determines if a syntax node represents an import statement in the code.","crux": null},{@@ -5509,8 +6655,8 @@"exported": true,"origin": "ast","body_hash": "4a8375e329e48af90b91a0dd802628af5549f46d771302e53de74dbde006ebc2",- "summary_state": "stale",- "summary": "Defines the supported programming languages for extraction.",+ "summary_state": "ready",+ "summary": "Defines a type representing the supported programming languages for extraction.","crux": null},{@@ -5523,11 +6669,11 @@"exported": true,"origin": "ast","body_hash": "bee30bc0236b0322b93537a0f778f70b33a0fa9df86ad4413c6ef71ee088a733",- "summary_state": "stale",- "summary": "Determines the programming language of a given file path.",+ "summary_state": "ready",+ "summary": "Determines the programming language of a given file path based on its extension.","crux": {- "code": " if (p.endsWith(\".tsx\") || p.endsWith(\".jsx\")) return \"tsx\";\n if (/\\.(ts|mts|cts|js|mjs|cjs)$/.test(p)) return \"typescript\";\n if (p.endsWith(\".py\") || p.endsWith(\".pyi\")) return \"python\";",- "span": "L21-L23"+ "code": " if (p.endsWith(\".tsx\") || p.endsWith(\".jsx\")) return \"tsx\";\n if (/\\.(ts|mts|cts|js|mjs|cjs)$/.test(p)) return \"typescript\";\n if (p.endsWith(\".py\") || p.endsWith(\".pyi\")) return \"python\";\n if (p.endsWith(\".go\")) return \"go\";\n return null;",+ "span": "L23-L27"}},{@@ -5540,9 +6686,12 @@"exported": false,"origin": "ast","body_hash": "213c9aa0ad691d3ceb1ad5f59d083930b3db690225b344bb24cf024d96181cdb",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Parses the source code into a syntax tree while handling large files in manageable chunks.",+ "crux": {+ "code": "function parseSource(source: string): Parser.SyntaxNode {\n return parser.parse((index: number) => source.slice(index, index + PARSE_CHUNK)).rootNode;\n}",+ "span": "L164-L166"+ }},{"id": "src/graph/extract.ts#pyReceiver",@@ -5554,9 +6703,12 @@"exported": false,"origin": "ast","body_hash": "2b1521e31249912b974bf8cf1d5cc98a72b3a4ea8a1e2eec09552a96cb4c81eb",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Identifies the receiver of a Python method call from its syntax tree representation.",+ "crux": {+ "code": "function pyReceiver(fn: Parser.SyntaxNode): string | undefined {\n const obj = fn.childForFieldName(\"object\");\n if (obj?.type === \"identifier\") return obj.text;\n if (obj?.type === \"attribute\") {\n const innerObj = obj.childForFieldName(\"object\");\n const innerAttr = obj.childForFieldName(\"attribute\");\n if (innerObj?.type === \"identifier\" && innerObj.text === \"self\" && innerAttr) return `self.${innerAttr.text}`;\n }\n return undefined;\n}",+ "span": "L432-L441"+ }},{"id": "src/graph/extract.ts#RawEdge",@@ -5568,9 +6720,12 @@"exported": true,"origin": "ast","body_hash": "125f3fc1acb36f3855a6d3a1e320c3b1cfb1a7c9601004cd7fb6861458281026",- "summary_state": "stale",- "summary": "Represents an unresolved edge in the extraction process, linking nodes in the graph.",- "crux": null+ "summary_state": "ready",+ "summary": "Represents an unresolved edge in the code structure that will be resolved later during processing.",+ "crux": {+ "code": "export interface RawEdge {\n source: string; // resolved node id\n relation: Relation;\n file: string; // the file this edge originates in (scopes name resolution)\n targetId?: string; // already-resolved target (contains)\n specifier?: string; // module path to resolve (imports)\n name?: string; // symbol name to resolve (extends/implements/calls)\n viaMember?: boolean; // calls: was it `obj.foo()` (→ prefer method targets)?\n /** calls with viaMember: the receiver's resolved type name (from bindings /\n * self / this / Go receiver), when a confident local clue exists. */\n recvType?: string;\n}",+ "span": "L34-L45"+ }},{"id": "src/graph/extract.ts#searchBody",@@ -5582,9 +6737,12 @@"exported": false,"origin": "ast","body_hash": "8ec6ac10c60767f9a430043e8d62d03fa463664677d35afd08916c65aadd2ae7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Normalizes and truncates the body of a code definition for efficient searching.",+ "crux": {+ "code": "function searchBody(text: string, max = MAX_BODY_CHARS): string {\n const norm = text.replace(/\\s+/g, \" \").trim();\n return norm.length > max ? norm.slice(0, max) : norm;\n}",+ "span": "L67-L70"+ }},{"id": "src/graph/extract.ts#tsExported",@@ -5613,9 +6771,12 @@"exported": false,"origin": "ast","body_hash": "633ed0d3c059772fe3d875bcf394cac70e7cab8d7f76fc033ac16358fea1e073",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Identifies the receiver of a TypeScript method call from its syntax tree representation.",+ "crux": {+ "code": "function tsReceiver(fn: Parser.SyntaxNode): string | undefined {\n const obj = fn.childForFieldName(\"object\");\n if (obj?.type === \"this\") return \"this\";\n if (obj?.type === \"identifier\") return obj.text;\n if (obj?.type === \"member_expression\") {\n const innerObj = obj.childForFieldName(\"object\");\n const innerProp = obj.childForFieldName(\"property\");\n if (innerObj?.type === \"this\" && innerProp) return `this.${innerProp.text}`;\n }\n return undefined;\n}",+ "span": "L444-L454"+ }},{"id": "src/graph/extract.ts#walk",@@ -5627,11 +6788,11 @@"exported": false,"origin": "ast","body_hash": "aa75459c73b63a4c6489c7a1ea205af0552500aafa250eb055edebafbb84b671",- "summary_state": "stale",+ "summary_state": "ready","summary": "Recursively traverses the syntax tree to collect definitions and their relationships.","crux": {- "code": " const desc = describe(node, ctx);\n if (desc) {\n const id = `${ctx.rel}#${[...ctx.scope, desc.name].join(\".\")}`;\n out.push({\n id,\n name: desc.name,\n kind: desc.kind,\n path: ctx.rel,\n span: `L${desc.hashNode.startPosition.row + 1}-L${desc.hashNode.endPosition.row + 1}`,\n signature: clean(ctx.source.slice(desc.hashNode.startIndex, desc.headerEnd)),\n exported: ctx.lang === \"python\" ? !desc.name.startsWith(\"_\") : tsExported(node),\n origin: \"ast\",",- "span": "L130-L141"+ "code": "function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEdge[]): void {\n const desc = describe(node, ctx);\n if (desc) {\n // `idName` scopes the id (e.g. a Go method under its receiver: `#DB.Count`) while\n // `name` stays the bare symbol name so member-call resolution matches it.\n const idPart = desc.idName ?? desc.name;\n const id = `${ctx.rel}#${[...ctx.scope, idPart].join(\".\")}`;\n out.push({\n id,\n name: desc.name,\n kind: desc.kind,\n path: ctx.rel,",+ "span": "L211-L222"}},{@@ -5644,8 +6805,8 @@"exported": true,"origin": "ast","body_hash": "fea4ebb4bc9443534fb5fb32b3928c9ebb1a108f885567ae40ab831845f1a594",- "summary_state": "stale",- "summary": "Context for walking through the syntax tree during extraction, maintaining state and scope.",+ "summary_state": "ready",+ "summary": "Contextual information used during the traversal of the syntax tree for code extraction.","crux": null},{@@ -5659,9 +6820,12 @@"origin": "ast","body_hash": "115b75e947618be7755ac59310f898943cb4c1d8266bdf5a4a30fdca4956914a","chars": 4000,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This module implements a caching mechanism to optimize the loading of graph and ask index data by avoiding unnecessary re-parsing of files when their metadata has not changed.",+ "crux": {+ "code": " * Keyed by `(path, mtimeMs, size)` from `statSync`, so a rebuild (`graft\n * build`) is picked up on the very next call with no polling and no TTL: the\n * stat is cheap relative to the parse it guards, and a changed mtime or size\n * invalidates the entry. A missing file returns null and is never cached — the\n * next call re-stats, so a file created after a prior miss is picked up\n * immediately (no negative caching).\n *\n * **Cache invalidation assumption:** This strategy assumes filesystem mtime\n * resolution is finer than build cadence. This is safe because `graft build`\n * rewrites the entire output file atomically, so same-size rewrites within a\n * single mtime tick (which would serve stale data) are infeasible in practice.\n * On APFS (macOS) mtime is nanosecond-granular and a build takes milliseconds,",+ "span": "L8-L19"+ }},{"id": "src/graph/load.ts#__resetParseCounts",@@ -5673,9 +6837,12 @@"exported": true,"origin": "ast","body_hash": "28ab92cf6abb38e1d4de7cc6ddc03e68cb6acb34aabc4d0553264118a856676f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Resets the counters that track the number of cache misses for graph and ask index parsing, ensuring a clean state for tests.",+ "crux": {+ "code": " __parseCount.graph = 0;\n __parseCount.askIndex = 0;\n}",+ "span": "L46-L48"+ }},{"id": "src/graph/load.ts#CacheEntry",@@ -5687,9 +6854,12 @@"exported": false,"origin": "ast","body_hash": "7b772fc4a0a866aa5269e023f8eae6c328a7c3f2e6108c498c231326d7e344f7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for cache entries, encapsulating the metadata and value of cached items to facilitate efficient cache management.",+ "crux": {+ "code": "interface CacheEntry<T> {\n mtimeMs: number;\n size: number;\n value: T | null;\n}",+ "span": "L31-L35"+ }},{"id": "src/graph/load.ts#loadAskIndexCached",@@ -5701,9 +6871,12 @@"exported": true,"origin": "ast","body_hash": "63af14b09b6d8f7534ccbb2eb58a5e80acfc526b67371bf46acad0de46aa6f07",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Caches the result of reading an ask index from a file, ensuring that it is only re-read when the file's metadata indicates a change.",+ "crux": {+ "code": " return loadCached(askIndexCache, path, () => readAskIndex(outDir), () => {\n __parseCount.askIndex++;\n });",+ "span": "L97-L99"+ }},{"id": "src/graph/load.ts#loadCached",@@ -5715,9 +6888,12 @@"exported": false,"origin": "ast","body_hash": "68385d5b28bc28f8be320bc279f74823f8bba12c26c0938152ff332102572035",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Loads a cached value from a specified cache, re-parsing the value if the file's metadata has changed, thus ensuring up-to-date data retrieval.",+ "crux": {+ "code": " if (!st) {\n // Missing file: don't negatively cache, and drop any stale entry so a\n // subsequently-created file at the same path is re-parsed, not served\n // from a cache keyed to the old (mtime, size).\n cache.delete(path);\n return null;\n }\n const cached = cache.get(path);\n if (cached && cached.mtimeMs === st.mtimeMs && cached.size === st.size) {\n return cached.value;\n }\n onParse();",+ "span": "L66-L77"+ }},{"id": "src/graph/load.ts#loadGraphCached",@@ -5729,9 +6905,12 @@"exported": true,"origin": "ast","body_hash": "d7c103b7e1115f04dcd8713d605dc9955ed0098e746f30bcd7f6f288e78ac257",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Caches the result of reading a graph from a file, ensuring that it is only re-read when the file's metadata indicates a change.",+ "crux": {+ "code": " return loadCached(graphCache, path, () => readGraph(path), () => {\n __parseCount.graph++;\n });",+ "span": "L88-L90"+ }},{"id": "src/graph/load.ts#statOf",@@ -5741,11 +6920,14 @@"span": "L50-L57","signature": "function statOf(path: string): { mtimeMs: number; size: number } | null","exported": false,- "origin": "ast",- "body_hash": "acb9f673ef79f4c554be70b06fc65d7f2c7501eb029a590c4a0df65470d3677d",- "summary_state": "pending",- "summary": null,- "crux": null+ "origin": "ast",+ "body_hash": "acb9f673ef79f4c554be70b06fc65d7f2c7501eb029a590c4a0df65470d3677d",+ "summary_state": "ready",+ "summary": "Retrieves the metadata (mtime and size) of a file, returning null if the file does not exist, which is essential for cache validation.",+ "crux": {+ "code": " const s = statSync(path);\n return { mtimeMs: s.mtimeMs, size: s.size };",+ "span": "L52-L53"+ }},{"id": "src/graph/map.ts",@@ -5758,9 +6940,12 @@"origin": "ast","body_hash": "aa982e0a06ce4e8d3af76cec5847846d495f36ace8835fe6bf70805429346ffd","chars": 8087,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Builds a structured representation of a repository's file and symbol organization based on their relationships, facilitating easier navigation and understanding of the codebase.",+ "crux": {+ "code": "export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RepoMap {\n const maxDirs = opts.maxDirs ?? DEFAULT_MAX_DIRS;\n const hubsPerDir = opts.hubsPerDir ?? DEFAULT_HUBS_PER_DIR;\n const hotspotsN = opts.hotspots ?? DEFAULT_HOTSPOTS;\n\n const fileNodes = graph.nodes.filter((n) => n.kind === \"file\");\n const totalFiles = fileNodes.length;\n\n // Pass 1: depth-1 file counts, to find (at most one) group over the\n // split threshold — two groups can't both exceed 60% of the same total.\n const depth1FileCounts = new Map<string, number>();\n for (const n of fileNodes) {",+ "span": "L112-L123"+ }},{"id": "src/graph/map.ts#basenameOf",@@ -5772,9 +6957,12 @@"exported": false,"origin": "ast","body_hash": "eec53beedb7464e5d97f487106cabdb9015de90a2378b2751fd4bb4087406ae6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts the base name from a file path, simplifying the representation of file names in the output.",+ "crux": {+ "code": "function basenameOf(path: string): string {\n const i = path.lastIndexOf(\"/\");\n return i >= 0 ? path.slice(i + 1) : path;\n}",+ "span": "L184-L187"+ }},{"id": "src/graph/map.ts#buildRepoMap",@@ -5786,9 +6974,12 @@"exported": true,"origin": "ast","body_hash": "c66c141b16315640a81aa5795d073aea7f842de00309186def0f0008e8bfd6af",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs the repository map from a given graph, organizing files and symbols into a structured format for easy access.",+ "crux": {+ "code": "export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RepoMap {\n const maxDirs = opts.maxDirs ?? DEFAULT_MAX_DIRS;\n const hubsPerDir = opts.hubsPerDir ?? DEFAULT_HUBS_PER_DIR;\n const hotspotsN = opts.hotspots ?? DEFAULT_HOTSPOTS;\n\n const fileNodes = graph.nodes.filter((n) => n.kind === \"file\");\n const totalFiles = fileNodes.length;\n\n // Pass 1: depth-1 file counts, to find (at most one) group over the\n // split threshold — two groups can't both exceed 60% of the same total.\n const depth1FileCounts = new Map<string, number>();\n for (const n of fileNodes) {",+ "span": "L112-L123"+ }},{"id": "src/graph/map.ts#buildRepoMap.depthFor",@@ -5800,9 +6991,12 @@"exported": true,"origin": "ast","body_hash": "61bba230120b002d39f95d53c1a4a157c255dd033dba747ac2bcee979f62f947",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the depth for a given path, influencing how files are grouped in the repository map based on the split segment.",+ "crux": {+ "code": " const depthFor = (path: string): number => (splitSegment !== null && dirKey(path, 1) === splitSegment ? 2 : 1);",+ "span": "L137-L137"+ }},{"id": "src/graph/map.ts#BuildRepoMapOptions",@@ -5814,9 +7008,12 @@"exported": true,"origin": "ast","body_hash": "270b8285c1189b3c2fcafcf501677802ec6efcc18d350c5dfa5a80e7df791512",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Specifies options for building the repository map, allowing customization of directory and hub limits.",+ "crux": {+ "code": "export interface BuildRepoMapOptions {\n /** Max directory entries kept (the rest are counted into `dropped`). Default 16. */\n maxDirs?: number;\n /** Max hubs listed per directory. Default 3. */\n hubsPerDir?: number;\n /** Max global hotspots. Default 12. */\n hotspots?: number;\n}",+ "span": "L51-L58"+ }},{"id": "src/graph/map.ts#computeInDegree",@@ -5828,9 +7025,12 @@"exported": false,"origin": "ast","body_hash": "614d2e67e179ee5a934d6c1b03134ca1e1c394d3036a1754bd41dd7ee8dcc1b7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the in-degree of nodes in the graph, determining the number of incoming edges for each target, which is crucial for identifying hubs.",+ "crux": {+ "code": "function computeInDegree(graph: GraphV1): Map<string, number> {\n const deg = new Map<string, number>();\n for (const e of graph.edges) {\n if (!WALK_RELATIONS.has(e.relation)) continue;\n deg.set(e.target, (deg.get(e.target) ?? 0) + 1);\n }\n return deg;\n}",+ "span": "L78-L85"+ }},{"id": "src/graph/map.ts#DirEntry",@@ -5842,9 +7042,12 @@"exported": true,"origin": "ast","body_hash": "1aed0e0df317b263286233153a93927552e23d59efef6822065986f6b9efb90b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Represents a directory entry in the repository map, summarizing its contents and associated hubs for better navigation.",+ "crux": {+ "code": "export interface DirEntry {\n path: string;\n files: number;\n symbols: number;\n languages: string[];\n hubs: Hub[];\n}",+ "span": "L33-L39"+ }},{"id": "src/graph/map.ts#dirKey",@@ -5856,9 +7059,12 @@"exported": false,"origin": "ast","body_hash": "8888f547f8daa2607546a3010a0af99b212d4c13618efa6140c60e3677d1ac85",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a directory key based on the specified depth, facilitating the grouping of files in the repository map.",+ "crux": {+ "code": "function dirKey(path: string, depth: number): string {\n const segments = path.split(\"/\");\n return segments.slice(0, Math.min(depth, segments.length)).join(\"/\");\n}",+ "span": "L70-L73"+ }},{"id": "src/graph/map.ts#formatDirHub",@@ -5870,9 +7076,12 @@"exported": false,"origin": "ast","body_hash": "7e92c9bff3f9e0cf1649150c2d86d768ec091f8cbf6f62000cc30e0aa22fd9eb",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a hub's information for display, providing a user-friendly representation of its attributes.",+ "crux": {+ "code": "function formatDirHub(h: Hub): string {\n return `${h.name} (${basenameOf(h.path)}, ${h.inDegree}←)`;\n}",+ "span": "L189-L191"+ }},{"id": "src/graph/map.ts#formatDirLine",@@ -5884,9 +7093,12 @@"exported": false,"origin": "ast","body_hash": "9a3db58b03fcc2ffa99b84aab037542b6ca49d55fac6441b9ca23edfede291b6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a directory entry for display, summarizing its contents and associated hubs in a readable format.",+ "crux": {+ "code": "function formatDirLine(d: DirEntry): string {\n const label = `${d.path}/`.padEnd(DIR_COL_WIDTH);\n const counts = `${d.files} files · ${d.symbols} symbols`;\n const hubs = d.hubs.length ? ` hubs: ${d.hubs.map(formatDirHub).join(\", \")}` : \"\";\n return `${label}${counts}${hubs}`;\n}",+ "span": "L193-L198"+ }},{"id": "src/graph/map.ts#formatHotspot",@@ -5898,9 +7110,12 @@"exported": false,"origin": "ast","body_hash": "2b94aab983d26d13940a46012331d1b3c7254f92b56a9c3a19e7964efee38cd4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a hotspot's information for display, detailing its attributes in a clear manner.",+ "crux": {+ "code": "function formatHotspot(h: Hub): string {\n return `${h.name} · ${h.kind} · ${h.path}:${h.span} · ${h.inDegree}←`;\n}",+ "span": "L200-L202"+ }},{"id": "src/graph/map.ts#formatRepoMap",@@ -5912,9 +7127,12 @@"exported": true,"origin": "ast","body_hash": "ff6f40dcbf4f3a67393e3322642d103b5f68f05b209276a8b74247e219560f1f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Renders the repository map as a human-readable string, summarizing its contents and structure for easy understanding.",+ "crux": {+ "code": "export function formatRepoMap(map: RepoMap): string {\n const { totals } = map;\n const header = `repo map — ${totals.files} files · ${totals.symbols} symbols · ${totals.edges} edges · ${totals.languages.join(\", \")}`;\n\n const lines: string[] = [header, \"\"];\n for (const d of map.dirs) lines.push(formatDirLine(d));\n if (map.dropped > 0) {\n lines.push(`… +${map.dropped} more director${map.dropped === 1 ? \"y\" : \"ies\"} not shown (raise max-dirs to see more)`);\n }\n lines.push(\"\");\n lines.push(`hotspots: ${map.hotspots.map(formatHotspot).join(\" \")}`);\n",+ "span": "L210-L221"+ }},{"id": "src/graph/map.ts#Hub",@@ -5926,9 +7144,12 @@"exported": true,"origin": "ast","body_hash": "1419fd8f2dea589de852c5fc3df6a8ee92ee056d4b321c2bd7eb5e726d30620d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure of a hub in the repository map, capturing its essential attributes for identification and ranking.",+ "crux": {+ "code": "export interface Hub {\n name: string;\n kind: string;\n path: string;\n span: string;\n inDegree: number;\n}",+ "span": "L25-L31"+ }},{"id": "src/graph/map.ts#RepoMap",@@ -5940,9 +7161,12 @@"exported": true,"origin": "ast","body_hash": "3086d36e77c71336febddbd8948e49aff8230f0f3ddd37c9e0d02c5063b73f5b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Encapsulates the entire repository map structure, providing a comprehensive overview of files, symbols, and their relationships.",+ "crux": {+ "code": "export interface RepoMap {\n totals: { files: number; symbols: number; edges: number; languages: string[] };\n /** Sorted by symbol count desc (ties by path asc), capped at `maxDirs`. */\n dirs: DirEntry[];\n /** Global top hubs by inDegree, ties by name asc then path asc. */\n hotspots: Hub[];\n /** Directory groups beyond the `maxDirs` cap — never silently dropped. */\n dropped: number;\n}",+ "span": "L41-L49"+ }},{"id": "src/graph/map.ts#sortedLanguages",@@ -5954,9 +7178,12 @@"exported": false,"origin": "ast","body_hash": "30c69f26bce208536a33c802d04d52eff2107fba4ce07daf17849f4858cb83f3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sorts and deduplicates the programming languages used in the repository, enhancing the metadata of the repository map.",+ "crux": {+ "code": "function sortedLanguages(paths: string[]): string[] {\n const set = new Set<string>();\n for (const p of paths) {\n const lang = languageOf(p);\n if (lang) set.add(lang);\n }\n return [...set].sort();\n}",+ "span": "L98-L105"+ }},{"id": "src/graph/map.ts#topHubs",@@ -5968,9 +7195,12 @@"exported": false,"origin": "ast","body_hash": "eef17e5cf1d97a53a78541847f1ded2d9a8fdaaeff5a240a2798f32debb14fba",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Identifies the top hubs based on in-degree, ensuring that only significant nodes are included in the repository map.",+ "crux": {+ "code": "function topHubs(nodes: NodeV1[], inDegree: Map<string, number>, cap: number): Hub[] {\n return nodes\n .map((n) => ({ name: n.name, kind: n.kind, path: n.path, span: n.span, inDegree: inDegree.get(n.id) ?? 0 }))\n .filter((h) => h.inDegree > 0)\n .sort((a, b) => b.inDegree - a.inDegree || a.name.localeCompare(b.name) || a.path.localeCompare(b.path))\n .slice(0, cap);\n}",+ "span": "L90-L96"+ }},{"id": "src/graph/relations.ts",@@ -5983,9 +7213,12 @@"origin": "ast","body_hash": "e62bc9934057bf232f86edcf942e71b0a2f4c44b57ffd78ddb935b85ab75aca8","chars": 796,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines a set of dependency relations for graph traversal, ensuring accurate representation of connections between symbols.",+ "crux": {+ "code": "export const WALK_RELATIONS: ReadonlySet<Relation> = new Set<Relation>([\n \"calls\",\n \"references\",\n \"imports\",\n \"implements\",\n \"extends\",\n]);",+ "span": "L14-L20"+ }},{"id": "src/graph/resolve.ts",@@ -5998,11 +7231,11 @@"origin": "ast","body_hash": "23e2e29f6e907f079f0d214ac6ce24b6105c403a51da30c2f4d39494f4b6b110","chars": 11721,- "summary_state": "stale",- "summary": "This file resolves raw edge intents into concrete edges by matching names against a node index, ensuring accurate relationships between nodes.",+ "summary_state": "ready",+ "summary": "This module resolves various types of edges between nodes in a codebase, ensuring accurate connections based on defined relationships and confidence levels.","crux": {- "code": "export function resolveEdges(nodes: NodeV1[], rawEdges: RawEdge[]): EdgeV1[] {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const globalName = new Map<string, NodeV1[]>();\n const perFileName = new Map<string, Map<string, NodeV1[]>>();\n for (const n of nodes) {\n if (n.kind === \"file\") continue;\n push(globalName, n.name, n);\n let fileMap = perFileName.get(n.path);\n if (!fileMap) perFileName.set(n.path, (fileMap = new Map()));\n push(fileMap, n.name, n);\n }\n",- "span": "L20-L31"+ "code": "export function resolveEdges(\n nodes: NodeV1[],\n rawEdges: RawEdge[],\n opts: ResolveOptions = {},\n): EdgeV1[] {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const globalName = new Map<string, NodeV1[]>();\n const perFileName = new Map<string, Map<string, NodeV1[]>>();\n // Owner-qualified method index: \"Owner.method\" → candidate method nodes, for\n // typed member-call resolution (recvType + name → a specific class's method).\n const ownerMethod = new Map<string, NodeV1[]>();\n // Go package resolution: dir (posix) → its `.go` file node ids, for import mapping.",+ "span": "L51-L62"}},{@@ -6015,9 +7248,12 @@"exported": true,"origin": "ast","body_hash": "52dff1265ffff874843c00b1425c7af639b28683dd0866e48a25e8b406543ec5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for a Go module, enabling the mapping of Go import paths to their corresponding directories in the repository.",+ "crux": {+ "code": "export interface GoModule {\n module: string;\n dir: string;\n}",+ "span": "L39-L42"+ }},{"id": "src/graph/resolve.ts#push",@@ -6043,11 +7279,11 @@"exported": true,"origin": "ast","body_hash": "0faf60f3424e744ecbd1e58dfe31e4afc1760c28211d27754f87cc308984b472",- "summary_state": "stale",- "summary": "This function processes raw edges and establishes relationships between nodes based on their types and specified relations.",+ "summary_state": "ready",+ "summary": "Processes nodes and raw edges to create a list of resolved edges, ensuring accurate relationships based on various resolution strategies.","crux": {- "code": " for (const e of rawEdges) {\n if (e.relation === \"contains\" && e.targetId) {\n add(e.source, e.targetId, \"contains\", \"extracted\");\n } else if (e.relation === \"imports\" && e.specifier) {\n add(e.source, resolveImport(e.specifier, e.file, byId), \"imports\", \"extracted\");\n } else if (e.relation === \"extends\" || e.relation === \"implements\") {\n const kinds: Kind[] = e.relation === \"implements\" ? [\"interface\"] : [\"class\", \"interface\"];\n const hit = resolveName(e.name!, e.file, kinds, perFileName, globalName);\n // an unresolved base is usually an external/imported type — keep the name.\n add(e.source, hit?.id ?? e.name!, e.relation, hit?.confidence ?? \"inferred\");\n } else if (e.relation === \"calls\") {\n const kinds: Kind[] = e.viaMember ? [\"method\"] : [\"function\"];",- "span": "L41-L52"+ "code": "export function resolveEdges(\n nodes: NodeV1[],\n rawEdges: RawEdge[],\n opts: ResolveOptions = {},\n): EdgeV1[] {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const globalName = new Map<string, NodeV1[]>();\n const perFileName = new Map<string, Map<string, NodeV1[]>>();\n // Owner-qualified method index: \"Owner.method\" → candidate method nodes, for\n // typed member-call resolution (recvType + name → a specific class's method).\n const ownerMethod = new Map<string, NodeV1[]>();\n // Go package resolution: dir (posix) → its `.go` file node ids, for import mapping.",+ "span": "L51-L62"}},{@@ -6060,11 +7296,11 @@"exported": true,"origin": "ast","body_hash": "d56a5f75ce46c0a907240751e35c16d07beec97e4a61a83cf77cccfc9fea0d03",- "summary_state": "stale",- "summary": "This function adds a new edge to the output if it hasn't been seen before, preventing duplicate edges in the result.",+ "summary_state": "ready",+ "summary": "Adds a new edge to the output if it hasn't been seen before, preventing duplicates in the resolved edges list.","crux": {- "code": " const add = (source: string, target: string, relation: Relation, confidence: EdgeV1[\"confidence\"]) => {\n const key = `${source}\u0000${relation}\u0000${target}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({ source, target, relation, confidence });\n };",- "span": "L34-L39"+ "code": " const add = (source: string, target: string, relation: Relation, confidence: EdgeV1[\"confidence\"]) => {\n const key = `${source}\\0${relation}\\0${target}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({ source, target, relation, confidence });\n };",+ "span": "L97-L102"}},{@@ -6077,9 +7313,12 @@"exported": false,"origin": "ast","body_hash": "c23e15aab9607316b1fe167acca80ba6c6fe19fc0b1fcd01f37000b7e8d20635",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Maps a Go import package path to an in-repo file node, handling module paths and ensuring correct resolution within the repository structure.",+ "crux": {+ "code": "function resolveGoImport(spec: string, modules: GoModule[], filesByDir: Map<string, string[]>): string {\n let best: { mod: GoModule; subpath: string } | null = null;\n for (const mod of modules) {\n let subpath: string | null = null;\n if (spec === mod.module) subpath = \"\";\n else if (spec.startsWith(mod.module + \"/\")) subpath = spec.slice(mod.module.length + 1);\n if (subpath === null) continue;\n if (!best || mod.module.length > best.mod.module.length) best = { mod, subpath };\n }\n if (!best) return spec; // stdlib / third-party — keep the package path\n\n const dir = posix.normalize(posix.join(best.mod.dir, best.subpath));",+ "span": "L243-L254"+ }},{"id": "src/graph/resolve.ts#resolveImport",@@ -6125,9 +7364,12 @@"exported": true,"origin": "ast","body_hash": "e17c6299def742bdf54acc75fc234fd89ca3ae31fd45bf599cbe5a928a9af359",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Specifies options for resolving edges, including the Go modules present in the repository for accurate import path mapping.",+ "crux": {+ "code": "export interface ResolveOptions {\n /** The Go modules found in the repo. Enables mapping Go import package paths\n * (`example.com/app/pkg/util`) to the in-repo directory they name, relative to the\n * owning module's `go.mod` location. Empty/absent → Go imports stay external strings. */\n goModules?: GoModule[];\n}",+ "span": "L44-L49"+ }},{"id": "src/graph/resolve.ts#resolveTypedMember",@@ -6139,9 +7381,12 @@"exported": false,"origin": "ast","body_hash": "8000e044cb5b139df44e3da0b2597da034e3325265e40670bb77b1ded16ead26",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Resolves a typed member call against a method index, traversing the inheritance chain to find the appropriate method or returning ambiguity if necessary.",+ "crux": {+ "code": "function resolveTypedMember(\n recvType: string,\n name: string,\n file: string,\n ownerMethod: Map<string, NodeV1[]>,\n classParents: Map<string, string[]>,\n): { id: string; confidence: EdgeV1[\"confidence\"] } | \"ambiguous\" | null {\n const MAX_DEPTH = 3;\n const visited = new Set<string>([recvType]);\n let frontier = [recvType];\n for (let depth = 0; depth <= MAX_DEPTH && frontier.length; depth++) {\n for (const type of frontier) {",+ "span": "L180-L191"+ }},{"id": "src/graph/traverse-cli.ts",@@ -6154,9 +7399,12 @@"origin": "ast","body_hash": "080714fc91e5caefe4548e87c071b2010fdc593a670366db941d9fd2907b08e2","chars": 5487,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file implements CLI commands for traversing a graph to find callers, callees, and impact of symbols, ensuring a consistent user experience across different commands.",+ "crux": {+ "code": "function edgesFor(kind: TraverseKind, graph: GraphV1, node: NodeV1, depth: number): EdgeHit[] {\n if (kind === \"callers\") return callersOf(graph, node);\n if (kind === \"callees\") return calleesOf(graph, node);\n return impactOf(graph, node, depth);\n}",+ "span": "L31-L35"+ }},{"id": "src/graph/traverse-cli.ts#edgesFor",@@ -6168,9 +7416,12 @@"exported": false,"origin": "ast","body_hash": "0cba9677135c955d5db241232c49e8a076f471de306cbbe19cc540c3c02255a5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the edges to traverse in the graph based on the specified kind, facilitating the retrieval of relevant connections for a node.",+ "crux": {+ "code": "function edgesFor(kind: TraverseKind, graph: GraphV1, node: NodeV1, depth: number): EdgeHit[] {\n if (kind === \"callers\") return callersOf(graph, node);\n if (kind === \"callees\") return calleesOf(graph, node);\n return impactOf(graph, node, depth);",+ "span": "L31-L34"+ }},{"id": "src/graph/traverse-cli.ts#headerOf",@@ -6182,9 +7433,12 @@"exported": true,"origin": "ast","body_hash": "cf66c3da70d4f8f16119a88148580dc66acba7d47a6c37e24480581733e44f48",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a formatted header string for a node, providing essential information for display in CLI output.",+ "crux": {+ "code": "export function headerOf(n: NodeV1): string {\n return `${n.name} · ${n.kind} · ${n.path}:${n.span}`;\n}",+ "span": "L41-L43"+ }},{"id": "src/graph/traverse-cli.ts#hitJson",@@ -6196,9 +7450,12 @@"exported": false,"origin": "ast","body_hash": "aeb2e815cc9892b59d1d815123cf824d7a3d11ccd4a031b92a779047885c70c7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Transforms an EdgeHit into a JSON format, ensuring structured output for hits in the traversal results.",+ "crux": {+ "code": "function hitJson(hit: EdgeHit): HitJson {\n const out: HitJson = { id: hit.id, relation: hit.relation, depth: hit.depth };\n if (hit.node) {\n out.name = hit.node.name;\n out.kind = hit.node.kind;\n out.path = hit.node.path;\n out.span = hit.node.span;\n }\n return out;\n}",+ "span": "L88-L97"+ }},{"id": "src/graph/traverse-cli.ts#HitJson",@@ -6210,8 +7467,8 @@"exported": false,"origin": "ast","body_hash": "e30ba67c87b04404964f6fc197fbe1a5f31f00a74662498406e311388b72e416",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure for hit details in JSON format, providing information about the relationship and depth of hits.","crux": null},{@@ -6224,9 +7481,12 @@"exported": true,"origin": "ast","body_hash": "76918dc9bd348cc7c19fdf778ccb604a9d1e9123167d71979c83c477df61d026",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a single hit line for display, showing the relationship and details of a node in the context of the traversal.",+ "crux": {+ "code": "export function hitLine(kind: TraverseKind, hit: EdgeHit): string {\n const arrow = ARROW[kind];\n const depthTag = kind === \"impact\" ? ` [depth ${hit.depth}]` : \"\";\n const label = hit.node ? `${hit.node.name} (${hit.node.path}:${hit.node.span})` : `${hit.id} (unresolved import)`;\n return ` ${hit.relation} ${arrow} ${label}${depthTag}`;\n}",+ "span": "L45-L50"+ }},{"id": "src/graph/traverse-cli.ts#looseNoteFor",@@ -6238,9 +7498,12 @@"exported": true,"origin": "ast","body_hash": "7b7f3eefe60c81c8c2e4026e5c3237c9a33ff5ce6076535787d52b45dd3adcd5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a user-friendly message when no edges are found for a symbol, guiding users on next steps.",+ "crux": {+ "code": "export function looseNoteFor(kind: TraverseKind, name: string): string {\n const label = kind === \"callees\" ? \"callees\" : \"callers\";\n const direction = kind === \"callees\" ? \"outgoing\" : \"incoming\";\n return ` no indexed ${label} — the graph has no ${direction} call/reference edges for this symbol; try grep -rn \"${name}\"`;\n}",+ "span": "L54-L58"+ }},{"id": "src/graph/traverse-cli.ts#MatchJson",@@ -6252,8 +7515,8 @@"exported": false,"origin": "ast","body_hash": "6d323182fe81c0462020fa7bbb67d2feb5a214b25ec176e5d2f109106079d09a",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure for matching results in JSON format, encapsulating symbol information and associated hits.","crux": null},{@@ -6266,9 +7529,12 @@"exported": true,"origin": "ast","body_hash": "166ca03408bcfd5c0f8deac25be0afbf85b3ea1f99d143ab3e0c012f48599bb1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes the traversal command based on user input, handling graph resolution and output formatting, while managing errors effectively.",+ "crux": {+ "code": "export function runTraverseCommand(kind: TraverseKind, query: string, dir: string, opts: TraverseCliOptions): void {\n const root = resolve(dir);\n const contextDir = contextDirFor(root, opts.globalDir);\n const graph = loadGraphCached(contextDir);\n if (!graph) {\n console.error(`✗ no graph found at ${contextDir} — run \\`graft build\\` first`);\n process.exit(1);\n }\n\n const matches = resolveSymbol(graph, query, opts.in ? { in: opts.in } : {});\n if (matches.length === 0) {\n console.error(`✗ no symbol \"${query}\" in the graph — check spelling or run graft build`);",+ "span": "L105-L116"+ }},{"id": "src/graph/traverse-cli.ts#symbolJson",@@ -6280,9 +7546,12 @@"exported": false,"origin": "ast","body_hash": "8ae58a388e66eb07e52378d530705f1f2c7f5bfcec085c17480cbde4170ef689",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Converts a node into a standardized JSON format, facilitating consistent output for symbol information.",+ "crux": {+ "code": "function symbolJson(n: NodeV1): SymbolJson {\n return { id: n.id, name: n.name, kind: n.kind, path: n.path, span: n.span };\n}",+ "span": "L84-L86"+ }},{"id": "src/graph/traverse-cli.ts#SymbolJson",@@ -6294,8 +7563,8 @@"exported": false,"origin": "ast","body_hash": "576f5963f808dc7657213b6d61ed08efff33b0e48aef2b768986e1e9dff85c00",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure for symbol metadata in JSON format, ensuring consistent representation of symbols in output.","crux": null},{@@ -6308,8 +7577,8 @@"exported": true,"origin": "ast","body_hash": "81222f4fc4c9c9d285bd325a0e77f451c77b0f8465314cab9438111230c4d997",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Specifies options for the CLI traversal commands, allowing customization of input, output format, and traversal depth.","crux": null},{@@ -6322,8 +7591,8 @@"exported": true,"origin": "ast","body_hash": "324cf2d7939c64ad6d957bf858d25acb5b665dbe40de99d3a22e5c4741d309c4",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the types of traversal operations available for graph navigation, ensuring type safety in CLI commands.","crux": null},{@@ -6337,9 +7606,12 @@"origin": "ast","body_hash": "dd38bef08a175c1db6751823f7f6f1eaae3952227737b063373987f69c52d7fa","chars": 8004,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Centralizes the logic for resolving symbol queries in a graph, enabling consistent identification of nodes based on various naming conventions and paths.",+ "crux": {+ "code": " */\nexport function resolveSymbol(graph: GraphV1, query: string, opts: ResolveSymbolOptions = {}): NodeV1[] {\n const lowerQuery = query.toLowerCase();\n const looksLikeFilename = query.includes(\".\") && !query.includes(\"#\");\n\n let matches = symbolMatches(graph.nodes, lowerQuery);\n\n if (matches.length === 0 && query.includes(\".\")) {\n const lastSegment = query.slice(query.lastIndexOf(\".\") + 1).toLowerCase();\n if (lastSegment) {\n matches = graph.nodes.filter((n) => n.kind !== \"file\" && n.name.toLowerCase() === lastSegment);\n }",+ "span": "L46-L57"+ }},{"id": "src/graph/traverse.ts#calleesOf",@@ -6351,9 +7623,12 @@"exported": true,"origin": "ast","body_hash": "001e16cf23b57798f48070d4e11375c2810748138337667eb68dea5926d076c2",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Identifies all edges originating from a specified symbol, showing which nodes it directly calls.",+ "crux": {+ "code": "export function calleesOf(graph: GraphV1, symbol: NodeV1): EdgeHit[] {\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const hits: EdgeHit[] = [];\n for (const e of graph.edges as EdgeV1[]) {\n if (!WALK_RELATIONS.has(e.relation) || e.source !== symbol.id) continue;\n hits.push({ node: byId.get(e.target) ?? null, id: e.target, relation: e.relation, depth: 1 });\n }",+ "span": "L107-L113"+ }},{"id": "src/graph/traverse.ts#callersOf",@@ -6365,9 +7640,12 @@"exported": true,"origin": "ast","body_hash": "777f6d8e8beaf3605809ad8a9622b1b232531ac27b729fb1f210ea28f24729f9",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Finds all edges leading to a specified symbol, indicating which nodes directly call it.",+ "crux": {+ "code": "export function callersOf(graph: GraphV1, symbol: NodeV1): EdgeHit[] {\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const hits: EdgeHit[] = [];\n for (const e of graph.edges as EdgeV1[]) {\n if (!WALK_RELATIONS.has(e.relation) || e.target !== symbol.id) continue;\n hits.push({ node: byId.get(e.source) ?? null, id: e.source, relation: e.relation, depth: 1 });\n }\n return hits;",+ "span": "L96-L103"+ }},{"id": "src/graph/traverse.ts#EdgeHit",@@ -6379,9 +7657,12 @@"exported": true,"origin": "ast","body_hash": "73c31bb7b1eb001536307926e08135697bac347ffb2d3444d5e8d6b0aac7d538",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Represents a traversed edge in the graph, capturing the relationship and depth of the connection to a node.",+ "crux": {+ "code": "export interface EdgeHit {\n node: NodeV1 | null;\n id: string;\n relation: Relation;\n depth: number;\n}",+ "span": "L88-L93"+ }},{"id": "src/graph/traverse.ts#impactOf",@@ -6393,9 +7674,12 @@"exported": true,"origin": "ast","body_hash": "45561c34c5e0037acb3147d064ca3097df2bfd0da1bf34603b30ae61f00ac590",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Performs a breadth-first search to determine the impact of changes to a symbol, identifying affected nodes up to a specified depth.",+ "crux": {+ "code": "export function impactOf(graph: GraphV1, symbol: NodeV1, maxDepth = 2): EdgeHit[] {\n return impactOfMany(graph, [symbol], maxDepth);\n}",+ "span": "L123-L125"+ }},{"id": "src/graph/traverse.ts#impactOfFile",@@ -6407,9 +7691,12 @@"exported": true,"origin": "ast","body_hash": "37bb8999dd4c8486366d90c974d9d7161a40dc6a42508927b5befbc19a1b923d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Aggregates the impact analysis for a file node and its defined symbols, ensuring all dependents are considered.",+ "crux": {+ "code": "export function impactOfFile(graph: GraphV1, fileNode: NodeV1, maxDepth = 2): EdgeHit[] {\n return impactOfMany(graph, [fileNode, ...symbolsInFile(graph, fileNode)], maxDepth);\n}",+ "span": "L189-L191"+ }},{"id": "src/graph/traverse.ts#impactOfMany",@@ -6421,9 +7708,12 @@"exported": true,"origin": "ast","body_hash": "bd8d064833fa0679633b8c4d662761e243c0d78a5dd31c60d3f49c613000353a",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generalizes the impact analysis to multiple seed nodes, aggregating the results of their incoming edges.",+ "crux": {+ "code": "export function impactOfMany(graph: GraphV1, seeds: NodeV1[], maxDepth = 2): EdgeHit[] {\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n\n // target id → incoming {source, relation} pairs, restricted to walk relations.\n const incoming = new Map<string, { source: string; relation: Relation }[]>();\n for (const e of graph.edges as EdgeV1[]) {\n if (!WALK_RELATIONS.has(e.relation)) continue;\n const arr = incoming.get(e.target);\n const entry = { source: e.source, relation: e.relation };\n if (arr) arr.push(entry);\n else incoming.set(e.target, [entry]);\n }",+ "span": "L141-L152"+ }},{"id": "src/graph/traverse.ts#resolveSymbol",@@ -6435,9 +7725,12 @@"exported": true,"origin": "ast","body_hash": "16417bb8ff31274a793c3224197aa5fde4299a18bc9b7bb26f950cb326a86978",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Resolves a query string to all matching nodes in the graph, handling various naming conventions and fallbacks.",+ "crux": {+ "code": "export function resolveSymbol(graph: GraphV1, query: string, opts: ResolveSymbolOptions = {}): NodeV1[] {\n const lowerQuery = query.toLowerCase();\n const looksLikeFilename = query.includes(\".\") && !query.includes(\"#\");\n\n let matches = symbolMatches(graph.nodes, lowerQuery);\n\n if (matches.length === 0 && query.includes(\".\")) {\n const lastSegment = query.slice(query.lastIndexOf(\".\") + 1).toLowerCase();\n if (lastSegment) {\n matches = graph.nodes.filter((n) => n.kind !== \"file\" && n.name.toLowerCase() === lastSegment);\n }\n }",+ "span": "L47-L58"+ }},{"id": "src/graph/traverse.ts#ResolveSymbolOptions",@@ -6449,9 +7742,12 @@"exported": true,"origin": "ast","body_hash": "96b7318d8119016aed9f8227251f25db2278e7a943d3b1eb2fe9a0c934f09004",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines options for narrowing down symbol resolution candidates based on path substring filtering.",+ "crux": {+ "code": "export interface ResolveSymbolOptions {\n /** Narrow candidates to nodes whose `path` contains this substring. */\n in?: string;\n}",+ "span": "L23-L26"+ }},{"id": "src/graph/traverse.ts#SymbolMatch",@@ -6463,9 +7759,12 @@"exported": true,"origin": "ast","body_hash": "e5aecaaa624e92197121baf03e995fd17c765a9d5aa9ebf5d0b5720ad07cc57f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Represents a resolved match for a symbol search in the graph, allowing for future disambiguation of metadata.",+ "crux": {+ "code": "export interface SymbolMatch {\n node: NodeV1;\n}",+ "span": "L19-L21"+ }},{"id": "src/graph/traverse.ts#symbolMatches",@@ -6477,9 +7776,12 @@"exported": false,"origin": "ast","body_hash": "d579fefa0302961e7b0bc5935016c6ab9f9f39da13d4f05667820ec0e33955d0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Filters nodes in the graph to find matches based on a case-insensitive query, considering both name and id suffixes.",+ "crux": {+ "code": "function symbolMatches(nodes: NodeV1[], lowerQuery: string): NodeV1[] {\n const suffixHash = \"#\" + lowerQuery;\n const suffixDot = \".\" + lowerQuery;\n return nodes.filter((n) => {\n if (n.kind === \"file\") return false;\n if (n.name.toLowerCase() === lowerQuery) return true;\n const lowerId = n.id.toLowerCase();\n return lowerId.endsWith(suffixHash) || lowerId.endsWith(suffixDot);\n });",+ "span": "L74-L82"+ }},{"id": "src/graph/traverse.ts#symbolsInFile",@@ -6491,9 +7793,12 @@"exported": false,"origin": "ast","body_hash": "ff4bea79b1a8c5565a8d6de8abcaa08f594400577551fe1fa3c7ed2b73142249",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Retrieves all symbols defined in a specific file, filtering out file nodes.",+ "crux": {+ "code": "function symbolsInFile(graph: GraphV1, fileNode: NodeV1): NodeV1[] {\n return graph.nodes.filter((n) => n.kind !== \"file\" && n.path === fileNode.path);\n}",+ "span": "L176-L178"+ }},{"id": "src/graph/types.ts",@@ -6506,8 +7811,8 @@"origin": "ast","body_hash": "27a9bdbef7783e5da94c860bc83525ef788e38a2176bc1184c8adbee539b1b51","chars": 3148,- "summary_state": "stale",- "summary": "Defines the schema for a code graph, outlining nodes and edges for code structure representation.",+ "summary_state": "ready",+ "summary": "Defines the structure and relationships of a code graph schema, facilitating the representation of code elements and their interactions.","crux": {"code": "/**\n * `graph.json` — the code graph schema (v1).\n *\n * One node per definition (file, class, function, method, interface, type, enum),\n * wired by edges (contains, imports, calls, ...). Field names follow the LSP /\n * SCIP vocabulary (`name`, `kind`, ...) rather than any one tool's conventions.\n *\n * Two tiers of data live on a node:\n * - Tier-1 (deterministic, $0): everything from the AST. Rebuilt on every run.\n * - Tier-2 (one LLM call, cached on `body_hash`): `summary` + `crux`.\n * M1 populates Tier-1 only; Tier-2 fields ship as `pending`/null.\n */","span": "L1-L12"@@ -6591,11 +7896,11 @@"exported": true,"origin": "ast","body_hash": "cbc16d65aefa07ebb6e28cd90ff587681249a4762ab8d10fcb56788adc902a97",- "summary_state": "stale",- "summary": "Enumerates the types of symbols that can exist in the code graph, facilitating type identification.",+ "summary_state": "ready",+ "summary": "Enumerates the various types of nodes in the code graph, ensuring consistent categorization of code elements across different languages.","crux": {- "code": "export type Kind =\n | \"file\"\n | \"class\"\n | \"function\"\n | \"method\"\n | \"interface\" // TS only\n | \"type\" // TS only (type alias)\n | \"enum\"; // TS only",- "span": "L15-L22"+ "code": "export type Kind =\n | \"file\"\n | \"class\"\n | \"function\"\n | \"method\"\n | \"interface\" // TS + Go\n | \"type\" // TS + Go (type alias / named type)\n | \"enum\" // TS only\n | \"struct\"; // Go only",+ "span": "L15-L23"}},{@@ -6608,11 +7913,11 @@"exported": true,"origin": "ast","body_hash": "6b0321068a3be9495509962011da101ea4730e74376e2568a237d4d6d736f1fc",- "summary_state": "stale",- "summary": "Represents a node in the graph with its identity, location, and meaning, essential for graph construction.",+ "summary_state": "ready",+ "summary": "Describes the properties of a node in the code graph, encapsulating its identity, location, and meaning for effective graph representation.","crux": {"code": "export interface NodeV1 {\n // identity\n id: string; // path-scoped: \"src/cache.ts#Cache.get\"\n name: string; // the symbol's own name: \"get\"\n kind: Kind;\n\n // location (Tier-1, deterministic)\n path: string; // repo-relative: \"src/cache.ts\"\n span: string; // whole definition: \"L165-L222\"\n signature: string | null; // \"get(k: string): number\" — null for kind:\"file\"\n exported: boolean;\n origin: \"ast\";",- "span": "L37-L48"+ "span": "L38-L49"}},{@@ -6660,9 +7965,12 @@"origin": "ast","body_hash": "a8f0d1b3efed9ca1ac3c22175c46c7a737b91bf632930ebb4437ebf52326ed69","chars": 2665,- "summary_state": "stale",- "summary": "This file contains functions for managing the serialization and deserialization of a wiring graph used in a context directory.",- "crux": null+ "summary_state": "ready",+ "summary": "This file manages the serialization and deserialization of a wiring graph, ensuring efficient storage and retrieval of graph data for further processing.",+ "crux": {+ "code": "export function writeGraph(graph: GraphV1, outDir: string): string {\n const sorted: GraphV1 = {\n ...graph,\n nodes: [...graph.nodes].sort((a, b) => a.id.localeCompare(b.id)).map(stripBodyText),\n edges: [...graph.edges].sort(edgeOrder),\n };\n const path = wiringPath(outDir);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(sorted, null, 2) + \"\\n\");\n return path;\n}",+ "span": "L36-L46"+ }},{"id": "src/graph/write.ts#edgeOrder",@@ -6708,9 +8016,12 @@"exported": false,"origin": "ast","body_hash": "066abd2d7e9f13c6df67c4ba9100acdba5518e271bbc326536475e8610ae24cf",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Removes the body_text property from a node to reduce the size of the serialized graph, avoiding duplication of data already stored elsewhere.",+ "crux": {+ "code": "function stripBodyText(node: NodeV1): NodeV1 {\n if (node.body_text === undefined) return node;\n const { body_text: _body_text, ...rest } = node;\n return rest as NodeV1;\n}",+ "span": "L57-L61"+ }},{"id": "src/graph/write.ts#wiringPath",@@ -6739,11 +8050,11 @@"exported": true,"origin": "ast","body_hash": "13647ca6eab5d041c45b3ef6efb6b851a3991c63742c94c88f4d05ecfc944354",- "summary_state": "stale",- "summary": "Writes a sorted representation of the wiring graph to a specified output directory, ensuring the directory structure exists.",+ "summary_state": "ready",+ "summary": "Writes a serialized and sorted representation of the graph to a JSON file, optimizing for size by stripping unnecessary data.","crux": {- "code": " nodes: [...graph.nodes].sort((a, b) => a.id.localeCompare(b.id)),\n edges: [...graph.edges].sort(edgeOrder),\n };\n const path = wiringPath(outDir);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(sorted, null, 2) + \"\\n\");",- "span": "L39-L44"+ "code": "export function writeGraph(graph: GraphV1, outDir: string): string {\n const sorted: GraphV1 = {\n ...graph,\n nodes: [...graph.nodes].sort((a, b) => a.id.localeCompare(b.id)).map(stripBodyText),\n edges: [...graph.edges].sort(edgeOrder),\n };\n const path = wiringPath(outDir);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(sorted, null, 2) + \"\\n\");\n return path;\n}",+ "span": "L36-L46"}},{@@ -6757,9 +8068,12 @@"origin": "ast","body_hash": "0b9ba9ba677876d1adf4ce8d05aa534cddfbdeb7060ed11a92111a41a76d1512","chars": 3168,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Facilitates the installation and management of user-level hooks for CLI agents, ensuring that hooks are correctly written and updated in the hooks.json configuration file after file edits.",+ "crux": {+ "code": "export function installCodexHooks(home: string): HookWrite[] {\n const base = join(home, '.codex');\n if (!dirExists(base)) return [];\n\n const shimPath = join(base, 'hooks', 'graft', 'graft-hooks.cjs');\n const shimWrite = writeOwned('codex-hook-shim', shimPath, hooksShim(claudeDistDir()), 0o755);\n\n const cfgPath = join(base, 'hooks.json');\n let root: Record<string, any> = {};\n const existed = existsSync(cfgPath);\n if (existed) {\n try { root = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch {",+ "span": "L37-L48"+ }},{"id": "src/hosts/codex-hooks.ts#dirExists",@@ -6771,9 +8085,12 @@"exported": false,"origin": "ast","body_hash": "3cb56ff33de328b88ab53b8b869149394e3f46919184cc3d9c7bebed9fb4dcc7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Checks if a given directory path exists, returning a boolean value to indicate its existence.",+ "crux": {+ "code": " try { return statSync(p).isDirectory(); } catch { return false; }\n}",+ "span": "L18-L19"+ }},{"id": "src/hosts/codex-hooks.ts#HookWrite",@@ -6785,8 +8102,8 @@"exported": true,"origin": "ast","body_hash": "87f37fccd34dabd662b284ad06e364c60173827b1eef5170714b232943a22693",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure for hook write operations, encapsulating the ID, path, and action taken during the write process.","crux": null},{@@ -6799,9 +8116,12 @@"exported": true,"origin": "ast","body_hash": "ed7ea45d024b73cc41550f0b5f3edcebc2555fbc1db0aba5437ded0b2c869d52",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Installs codex hooks by writing a shim and updating the hooks configuration based on the provided home directory.",+ "crux": {+ "code": " const shimPath = join(base, 'hooks', 'graft', 'graft-hooks.cjs');\n const shimWrite = writeOwned('codex-hook-shim', shimPath, hooksShim(claudeDistDir()), 0o755);\n\n const cfgPath = join(base, 'hooks.json');\n let root: Record<string, any> = {};\n const existed = existsSync(cfgPath);\n if (existed) {\n try { root = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch {\n return [shimWrite, { id: 'codex-hooks', path: cfgPath, action: 'skipped-unparseable' }];\n }\n }\n if (typeof root !== 'object' || root === null || Array.isArray(root)) {",+ "span": "L41-L52"+ }},{"id": "src/hosts/codex-hooks.ts#isGraftEntry",@@ -6813,9 +8133,12 @@"exported": false,"origin": "ast","body_hash": "628b0f417080f2b63d9928d37116e818fc0d2c50c5d1319fdf1cb4ec7ef6e9f3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines if a given entry is a graft entry by checking for a specific string in its JSON representation.",+ "crux": {+ "code": " return JSON.stringify(entry).includes('graft-hooks.cjs');\n}",+ "span": "L34-L35"+ }},{"id": "src/hosts/codex-hooks.ts#writeOwned",@@ -6827,9 +8150,12 @@"exported": false,"origin": "ast","body_hash": "0e2c5fcb677016e7114466756f114b05de75fd91cca3829607c528461e02edb1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles the creation or updating of a file with specific content and permissions, returning the action taken.",+ "crux": {+ "code": " const existed = existsSync(path);\n if (existed && readFileSync(path, 'utf8') === content) {\n if (mode !== undefined && (statSync(path).mode & 0o777) !== mode) chmodSync(path, mode);\n return { id, path, action: 'unchanged' };\n }\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content);\n if (mode !== undefined) chmodSync(path, mode);\n return { id, path, action: existed ? 'updated' : 'created' };",+ "span": "L22-L30"+ }},{"id": "src/hosts/init.ts",@@ -6842,9 +8168,12 @@"origin": "ast","body_hash": "cd3ef307f207a48b82fa81ea55e34fdc97b8663612ad639a3256336d5531afa0","chars": 2627,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Initializes host configurations by writing instruction files based on selected hosts, ensuring that the correct files are created or updated as needed.",+ "crux": {+ "code": "export function runHostsInit(\n repo: string,\n opts: { agents?: string[]; all?: boolean; home?: string; mcp?: boolean; hooks?: boolean } = {},\n): HostsInitResult {\n const home = opts.home ?? homedir();\n const probe = probeFor(home, repo);\n\n let selected: HostTarget[];\n let unknown: string[] = [];\n if (opts.agents !== undefined) {\n const byId = new Map(HOSTS.map((h) => [h.id, h]));\n selected = opts.agents.flatMap((id) => byId.get(id) ?? []);",+ "span": "L37-L48"+ }},{"id": "src/hosts/init.ts#HostsInitResult",@@ -6856,8 +8185,8 @@"exported": true,"origin": "ast","body_hash": "c643482048fe39520f2fc0aaee0c8761e9f13ed7f7bf5fcfc8ef404cd2f0e98f",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure of the result returned by the host initialization process, capturing written, skipped, and unknown hosts along with MCP and hooks data.","crux": null},{@@ -6870,9 +8199,12 @@"exported": false,"origin": "ast","body_hash": "7653739002fda057d1517f18bfe77dfb0dcf78ab6cb9716ceb7624601eec1f7f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a probe object to check for the existence of directories in a specified repository, facilitating host detection.",+ "crux": {+ "code": " home, repo,\n dirExists: (p) => { try { return statSync(p).isDirectory(); } catch { return false; } },\n };",+ "span": "L24-L26"+ }},{"id": "src/hosts/init.ts#runHostsInit",@@ -6884,9 +8216,12 @@"exported": true,"origin": "ast","body_hash": "8b9a15d05dcd9a43c414b8c27e34f565538950d578ed452568d9c61f08bb9dbd",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Initializes hosts by selecting them based on provided options and writing their instruction files, while also handling MCP configurations and hooks.",+ "crux": {+ "code": " const path = join(repo, host.relPath);\n const action =\n host.kind === 'owned'\n ? writeOwned(path, host.content())\n : upsertSection(path, host.content()).action;\n written.push({ id: host.id, path, action });\n }\n const skipped = HOSTS.filter((h) => !selected.includes(h)).map((h) => h.id);\n const mcp = opts.mcp === false ? [] : registerMcpConfigs(repo, selected.map((h) => h.id), { home });\n const hooks =\n opts.hooks === false || !selected.some((h) => h.id === 'agents')\n ? []",+ "span": "L58-L69"+ }},{"id": "src/hosts/init.ts#writeOwned",@@ -6898,9 +8233,12 @@"exported": false,"origin": "ast","body_hash": "f25633ece4c0cfb7a956003dd26ad8e1b095e7955d13d796c24ac389d75a4f09",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Writes content to a specified path, creating or replacing the file as necessary, and returns the action taken.",+ "crux": {+ "code": " if (existsSync(path) && readFileSync(path, 'utf8') === content) return 'unchanged';\n mkdirSync(dirname(path), { recursive: true });\n const existed = existsSync(path);\n writeFileSync(path, content);\n return existed ? 'replaced' : 'created';",+ "span": "L30-L34"+ }},{"id": "src/hosts/instructions.ts",@@ -6913,8 +8251,8 @@"origin": "ast","body_hash": "1dddea660f4d5e65952faf2beee42f04153ccab893658e75bda1dce6c0245b18","chars": 2627,- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "This file provides Graft instructions for navigating and utilizing the context graph effectively.","crux": null},{@@ -6927,9 +8265,12 @@"exported": true,"origin": "ast","body_hash": "697397dc5e04836b10f9f9b6c4dfb5df6d95c5f89317ce9a77bb838a7e71e929",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines a rule to always apply the Graft context graph before exploring source code.",+ "crux": {+ "code": "export function cursorRule(): string {\n return `---\ndescription: Use the Graft context graph in graft/ before exploring source\nalwaysApply: true\n---\n${instructionBody()}",+ "span": "L44-L49"+ }},{"id": "src/hosts/instructions.ts#instructionBody",@@ -6941,9 +8282,12 @@"exported": true,"origin": "ast","body_hash": "9003c83453867680b4936696a28bb8086e14e432bb3c3debc4d7e5ab5ab7a0be",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates the main instructional content for using the Graft context graph.",+ "crux": {+ "code": "export function instructionBody(): string {\n return `## Graft — repo context graph\n\nThis repo is indexed in \\`graft/\\`: small linked markdown nodes that explain each\nsystem and carry exact file:line spans, kept in sync with the code through git.\n\nFor ANY task here — understanding how something works, finding where code lives,\nor scoping a change — get context from the graph before grepping or opening\nsource files. Re-ask freely (it's cheap) and reuse literal identifiers you\nalready have (symbol, error string, file name) as the query. New to this repo?\nRun \\`graft map\\` first — a token-budgeted orientation (dir clusters, hubs,\nhotspots), no LLM, no key.",+ "span": "L6-L17"+ }},{"id": "src/hosts/instructions.ts#kiroSteering",@@ -6955,9 +8299,12 @@"exported": true,"origin": "ast","body_hash": "a3fea9a2ad9ee6488338f60825284e55bc5cd09cee354e9554efb2d90e2be20f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Specifies a rule for always including the Graft context graph in the workflow.",+ "crux": {+ "code": "export function kiroSteering(): string {\n return `---\ninclusion: always\n---\n${instructionBody()}",+ "span": "L53-L57"+ }},{"id": "src/hosts/instructions.ts#windsurfRule",@@ -6969,9 +8316,12 @@"exported": true,"origin": "ast","body_hash": "a30d7b9ed58bdcfc402576d4a79e3643691145a92c521402e594243533cb4aed",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Provides a rule that incorporates the Graft context graph into its logic.",+ "crux": {+ "code": "export function windsurfRule(): string {\n return `${instructionBody()}",+ "span": "L61-L62"+ }},{"id": "src/hosts/mcp-config.ts",@@ -6984,9 +8334,12 @@"origin": "ast","body_hash": "c3a3dea18371806ed352e7cab582265db2341b7d4ea5797578e495b512a9b0b3","chars": 3338,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Facilitates the registration and configuration of multiple MCP servers in specified host configurations, ensuring proper JSON and TOML formatting.",+ "crux": {+ "code": "export function registerMcpConfigs(\n repo: string,\n ids: string[],\n opts: { home?: string } = {},\n): McpWrite[] {\n const home = opts.home ?? homedir();\n const out: McpWrite[] = [];\n for (const id of ids) {\n switch (id) {\n case 'cursor':\n out.push(mergeJsonKey(id, join(repo, '.cursor', 'mcp.json'), 'mcpServers', SERVER_ENTRY));\n break;",+ "span": "L56-L67"+ }},{"id": "src/hosts/mcp-config.ts#dirExists",@@ -6998,9 +8351,12 @@"exported": false,"origin": "ast","body_hash": "3cb56ff33de328b88ab53b8b869149394e3f46919184cc3d9c7bebed9fb4dcc7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Checks if a given directory path exists, returning a boolean value.",+ "crux": {+ "code": "function dirExists(p: string): boolean {\n try { return statSync(p).isDirectory(); } catch { return false; }\n}",+ "span": "L19-L21"+ }},{"id": "src/hosts/mcp-config.ts#McpWrite",@@ -7012,9 +8368,12 @@"exported": true,"origin": "ast","body_hash": "9c185f100ff537beef3b464e5c8969c84b257c9897a30596b210f5534c8173c7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for writing MCP configuration results, indicating the operation performed on the configuration file.",+ "crux": {+ "code": "export interface McpWrite {\n id: string;\n path: string;\n action: 'created' | 'updated' | 'unchanged' | 'skipped-unparseable';\n}",+ "span": "L10-L14"+ }},{"id": "src/hosts/mcp-config.ts#mergeJsonKey",@@ -7026,9 +8385,12 @@"exported": false,"origin": "ast","body_hash": "e399dc21ae5ece8ec15889555e73360fb028691ac71f96255de36ae942b6707d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Merges a JSON entry into a specified key of a JSON file, creating or updating the file as necessary.",+ "crux": {+ "code": "function mergeJsonKey(id: string, path: string, topKey: string, entry: object): McpWrite {\n let root: Record<string, any> = {};\n const existed = existsSync(path);\n if (existed) {\n try {\n root = JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n return { id, path, action: 'skipped-unparseable' };\n }\n }\n const bucket = (root[topKey] ??= {});\n if (typeof bucket !== 'object' || bucket === null || Array.isArray(bucket)) {",+ "span": "L23-L34"+ }},{"id": "src/hosts/mcp-config.ts#registerMcpConfigs",@@ -7040,9 +8402,12 @@"exported": true,"origin": "ast","body_hash": "13f7e325e26de9e426d475d1ff63fe06af411ca36b4d3c0fca7b2c2eb11fb45f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Registers MCP configurations for multiple IDs, handling different file types and structures based on the ID.",+ "crux": {+ "code": "export function registerMcpConfigs(\n repo: string,\n ids: string[],\n opts: { home?: string } = {},\n): McpWrite[] {\n const home = opts.home ?? homedir();\n const out: McpWrite[] = [];\n for (const id of ids) {\n switch (id) {\n case 'cursor':\n out.push(mergeJsonKey(id, join(repo, '.cursor', 'mcp.json'), 'mcpServers', SERVER_ENTRY));\n break;",+ "span": "L56-L67"+ }},{"id": "src/hosts/mcp-config.ts#upsertCodexToml",@@ -7054,9 +8419,12 @@"exported": false,"origin": "ast","body_hash": "2dd6f4be2733f7bbd211b3ba2c6a8ceda215a135a9606a33fb7b1654ab320f9a",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Inserts or updates a section in a TOML configuration file for the codex, ensuring the section exists.",+ "crux": {+ "code": "function upsertCodexToml(id: string, path: string): McpWrite {\n const existed = existsSync(path);\n const text = existed ? readFileSync(path, 'utf8') : '';\n if (/^\\[mcp_servers\\.graft\\]$/m.test(text)) return { id, path, action: 'unchanged' };\n const section = `[mcp_servers.graft]\\ncommand = \"npx\"\\nargs = [\"-y\", \"@nanonets/graft\", \"mcp\"]\\n`;\n const sep = text.length === 0 ? '' : text.endsWith('\\n') ? '\\n' : '\\n\\n';\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${text}${sep}${section}`);\n return { id, path, action: existed ? 'updated' : 'created' };\n}",+ "span": "L45-L54"+ }},{"id": "src/hosts/registry.ts",@@ -7083,9 +8451,12 @@"exported": true,"origin": "ast","body_hash": "3e698dbf2457932d7a8713477813adac3b143152cafeb164aef5daf4fce398e5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Filters and returns host targets that are detected based on the provided probing information.",+ "crux": {+ "code": "export function detectHosts(probe: DetectProbe): HostTarget[] {\n return HOSTS.filter((h) => h.detect(probe));\n}",+ "span": "L86-L88"+ }},{"id": "src/hosts/registry.ts#DetectProbe",@@ -7097,8 +8468,8 @@"exported": true,"origin": "ast","body_hash": "b9f830f4861e96bdce7f7bf638175022642738bd7155f68167eb50a879f7a525",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the structure for probing the existence of directories related to AI coding hosts.","crux": null},{@@ -7111,9 +8482,12 @@"exported": true,"origin": "ast","body_hash": "4f4ec61bb5cdc94d5a40965c4bd6757b2e888811bb63fba7368f5f606d055ada",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Retrieves a list of identifiers for all defined host targets.",+ "crux": {+ "code": "export function hostIds(): string[] {\n return HOSTS.map((h) => h.id);\n}",+ "span": "L82-L84"+ }},{"id": "src/hosts/registry.ts#HostTarget",@@ -7125,8 +8499,8 @@"exported": true,"origin": "ast","body_hash": "061c7862838ab4494e485220f52fea2202e0db5be2d2ff0e34d8e5fba4bb4b14",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Represents a target host with its identification, type, and detection logic for AI coding environments.","crux": null},{@@ -7140,9 +8514,12 @@"origin": "ast","body_hash": "f172618889d5a02683032df8c69dd85b71c00c72a8b76958305ade22d6cda714","chars": 2879,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file provides functionality to manage sections of text within files, specifically for inserting and updating content between defined markers.",+ "crux": {+ "code": "export function upsertSection(filePath: string, body: string): { action: UpsertAction } {\n if (!existsSync(filePath)) {\n const block = fencedBlock(body);\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, `${block}\\n`);\n return { action: 'created' };\n }\n const text = readFileSync(filePath, 'utf8');\n const eol = detectEol(text);\n // Split on either eol so lines never carry an embedded '\\r' — that keeps\n // the marker/content comparison clean and lets us rejoin deliberately with\n // the detected eol instead of relying on '\\r' characters riding along",+ "span": "L36-L47"+ }},{"id": "src/hosts/sections.ts#detectEol",@@ -7154,9 +8531,12 @@"exported": false,"origin": "ast","body_hash": "902fbd2b08830cb32450b0a84ba8f76f1fd34d4fe8345b28fadba29a682c4b43",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the dominant line ending used in a given text, facilitating consistent handling of line breaks.",+ "crux": {+ "code": "function detectEol(text: string): LineEnding {\n return text.includes('\\r\\n') ? '\\r\\n' : '\\n';\n}",+ "span": "L24-L26"+ }},{"id": "src/hosts/sections.ts#fencedBlock",@@ -7168,9 +8548,12 @@"exported": true,"origin": "ast","body_hash": "cfc11a2e95b5d0866b455dfff3cd2e1f98f13e3dc5dad5fe47b8f624cb93b6bd",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a formatted block of text enclosed by specific markers, ensuring proper line endings and normalization of input.",+ "crux": {+ "code": " const normalizedBody = body.replace(/\\r/g, '');\n const block = `${START}\\n${normalizedBody.replace(/\\s+$/, '')}\\n${END}`;\n return eol === '\\n' ? block : block.replace(/\\n/g, '\\r\\n');",+ "span": "L18-L20"+ }},{"id": "src/hosts/sections.ts#LineEnding",@@ -7182,8 +8565,8 @@"exported": false,"origin": "ast","body_hash": "e49b9a5218efdfb100f47552da255afff2e24a84ab10c02564adb1e72892a229",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Specifies the types of line endings that can be used in the text, ensuring compatibility with different operating systems.","crux": null},{@@ -7196,9 +8579,12 @@"exported": false,"origin": "ast","body_hash": "b090a3b83b05f46da8f10b2c37a8f0a5c1522280f786fe4263f161294e0ffbd3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Finds the index of a specified marker in an array of lines, helping to locate the start and end of sections within the text.",+ "crux": {+ "code": " for (let i = from; i < lines.length; i++) {\n if (lines[i].trim() === marker) return i;\n }\n return -1;",+ "span": "L30-L33"+ }},{"id": "src/hosts/sections.ts#UpsertAction",@@ -7210,8 +8596,8 @@"exported": true,"origin": "ast","body_hash": "53d24b330d60564589d8a07882c099e9fc964a43b0523536ea03cc430551452f",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines the possible outcomes of an upsert operation on a section, indicating whether it was created, appended, replaced, or unchanged.","crux": null},{@@ -7224,23 +8610,26 @@"exported": true,"origin": "ast","body_hash": "552b5cf28b36f1e019f183739f266aa59b8af6bbf691056507639ce5633c2dd0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Handles the logic for inserting or updating a section of text in a file, managing file creation, content comparison, and writing operations.",+ "crux": {+ "code": "export function upsertSection(filePath: string, body: string): { action: UpsertAction } {\n if (!existsSync(filePath)) {\n const block = fencedBlock(body);\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, `${block}\\n`);\n return { action: 'created' };\n }\n const text = readFileSync(filePath, 'utf8');\n const eol = detectEol(text);\n // Split on either eol so lines never carry an embedded '\\r' — that keeps\n // the marker/content comparison clean and lets us rejoin deliberately with\n // the detected eol instead of relying on '\\r' characters riding along",+ "span": "L36-L47"+ }},{"id": "src/index.ts","name": "index.ts","kind": "file","path": "src/index.ts",- "span": "L1-L37",+ "span": "L1-L45","signature": null,"exported": true,"origin": "ast",- "body_hash": "e56e74612514fd45665b27e3c47b4a685b503a533b38e1674d256344511107fc",- "chars": 1542,+ "body_hash": "f66577d7952e061dd28f782e39f572fe9421a52758e9151f2620739894dd006d",+ "chars": 2061,"summary_state": "ready",- "summary": "This file serves as the public API for the Graft library, facilitating the management and synchronization of linked markdown files in a repository.",+ "summary": "This module serves as the public API for the Graft library, facilitating the building and checking of a graph of linked markdown files.","crux": {"code": " * await engine.init(\".\"); // writes .context/*.md + manifest.json\n *\n * const result = engine.check(\".\"); // { ok: boolean, ...drift }\n * if (!result.ok) process.exitCode = 1;","span": "L12-L15"@@ -7289,9 +8678,12 @@"origin": "ast","body_hash": "0bdeba850ab62132a01b683cd2db7ee36a7509a67ebd58e73887a22a611ce100","chars": 2258,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines a minimal JSON-RPC 2.0 server for handling protocol messages and tool calls.",+ "crux": {+ "code": "export function startMcpServer(root: string, dirOverride?: string): void {\n const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });\n rl.on('line', (line) => {\n const text = line.trim();\n if (!text) return;\n let msg: { id?: unknown; method?: string; params?: Record<string, any> };\n try {\n msg = JSON.parse(text);\n } catch {\n replyError(null, -32700, 'parse error');\n return;\n }",+ "span": "L20-L31"+ }},{"id": "src/mcp/server.ts#reply",@@ -7303,9 +8695,12 @@"exported": false,"origin": "ast","body_hash": "ebf863d2db4e0898846deff35e6a0d581dae06f6e402592309f8c6742a3abe59",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs and sends a successful JSON-RPC response message.",+ "crux": {+ "code": "function reply(id: unknown, result: object): void {\n send({ jsonrpc: '2.0', id, result });\n}",+ "span": "L12-L14"+ }},{"id": "src/mcp/server.ts#replyError",@@ -7317,9 +8712,12 @@"exported": false,"origin": "ast","body_hash": "540611464bba68e3e678870e748cde38aa6790c52ca10dfda8f891dcf0d59717",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs and sends a JSON-RPC error response message.",+ "crux": {+ "code": "function replyError(id: unknown, code: number, message: string): void {\n send({ jsonrpc: '2.0', id, error: { code, message } });\n}",+ "span": "L16-L18"+ }},{"id": "src/mcp/server.ts#send",@@ -7331,9 +8729,12 @@"exported": false,"origin": "ast","body_hash": "7446435a2fc268ad8d76124c2e66f957d5de51730babfc38d8cb4dff5fc80c58",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sends a JSON-RPC message to the standard output stream.",+ "crux": {+ "code": "function send(msg: object): void {\n process.stdout.write(`${JSON.stringify(msg)}\\n`);\n}",+ "span": "L8-L10"+ }},{"id": "src/mcp/server.ts#startMcpServer",@@ -7345,9 +8746,12 @@"exported": true,"origin": "ast","body_hash": "bbf674f912399a59d133f52a0d975069c215acfb0cc62b5f6ffc3d15ef92acbd",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Initializes the server to listen for incoming JSON-RPC messages and handle them appropriately.",+ "crux": {+ "code": "export function startMcpServer(root: string, dirOverride?: string): void {\n const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });\n rl.on('line', (line) => {\n const text = line.trim();\n if (!text) return;\n let msg: { id?: unknown; method?: string; params?: Record<string, any> };\n try {\n msg = JSON.parse(text);\n } catch {\n replyError(null, -32700, 'parse error');\n return;\n }",+ "span": "L20-L31"+ }},{"id": "src/mcp/tools.ts",@@ -7373,10 +8777,13 @@"signature": "function callTool( root: string, name: string, args: Record<string, unknown>, dirOverride?: string, ): { text: string; isError: boolean }","exported": true,"origin": "ast",- "body_hash": "ff7c769fef542a2ef86fd774fd9ad72aee3dc1745d295a675c530f76c530dab2",- "summary_state": "pending",- "summary": null,- "crux": null+ "body_hash": "ff7c769fef542a2ef86fd774fd9ad72aee3dc1745d295a675c530f76c530dab2",+ "summary_state": "ready",+ "summary": "Handles the invocation of various tools based on user input, managing errors and returning formatted results for different graph operations.",+ "crux": {+ "code": "export function callTool(\n root: string,\n name: string,\n args: Record<string, unknown>,\n dirOverride?: string,\n): { text: string; isError: boolean } {\n try {\n switch (name) {\n case 'graft_ask': {\n const query = String(args.query ?? '');\n if (!query) return { text: 'graft_ask requires a query', isError: true };\n const limit = typeof args.limit === 'number' ? args.limit : 5;",+ "span": "L149-L160"+ }},{"id": "src/mcp/tools.ts#renderMatches",@@ -7388,9 +8795,12 @@"exported": false,"origin": "ast","body_hash": "b1fb04cdcb7c8aef1225f590bb7147d80d211ffa478c2f0eec54b33028045d66",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats and renders the results of graph traversal matches, providing a structured output for users to understand symbol relationships.",+ "crux": {+ "code": "function renderMatches(kind: TraverseKind, matches: NodeV1[], hitsFor: (n: NodeV1) => EdgeHit[]): string {\n return matches\n .map((m) => {\n const hits = hitsFor(m);\n const lines = [headerOf(m)];\n if (hits.length === 0) lines.push(looseNoteFor(kind, m.name));\n else for (const h of hits) lines.push(hitLine(kind, h));\n return lines.join('\\n');\n })\n .join('\\n\\n');\n}",+ "span": "L137-L147"+ }},{"id": "src/mcp/tools.ts#ToolDef",@@ -7402,9 +8812,12 @@"exported": true,"origin": "ast","body_hash": "66213a2ab8c0b58ddbf6e632f4ac26e643f00ff02eef696f9b321c2236b45365",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines the structure for tool definitions used in the MCP tools, ensuring consistent input schema and metadata for each tool.",+ "crux": {+ "code": "export interface ToolDef {\n name: string;\n description: string;\n inputSchema: object;\n}",+ "span": "L18-L22"+ }},{"id": "src/mcp/tools.ts#unknownSymbolText",@@ -7416,9 +8829,12 @@"exported": false,"origin": "ast","body_hash": "ea43b6a930c9fe3d67aa2e40b6d1d7dc2ebdb0e55a23c1f42047c0089bc2917e",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates an error message for an unknown symbol query, guiding users to check their input or build the graph.",+ "crux": {+ "code": "function unknownSymbolText(query: string): string {\n return `no symbol \"${query}\" in the graph — check spelling or run \\`graft build\\``;\n}",+ "span": "L29-L31"+ }},{"id": "src/search/grep-cli.ts",@@ -7431,9 +8847,12 @@"origin": "ast","body_hash": "70bcb32d3ae5e4e9e39eb8b07151da7145a08756015e91f215edcadce5bddef8","chars": 4779,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file provides the command-line interface for the grep functionality, formatting results for user-friendly output.",+ "crux": {+ "code": "export function formatGrepResult(result: GrepResult): string {\n const blocks = [formatGrepHeader(result), \"\", ...result.groups.map((g) => formatGroup(g) + \"\\n\")];\n let out = blocks.join(\"\\n\").replace(/\\n+$/, \"\\n\");\n const note = truncationNote(result);\n if (note) out += note + \"\\n\";\n return out;\n}",+ "span": "L53-L59"+ }},{"id": "src/search/grep-cli.ts#formatGrepHeader",@@ -7445,9 +8864,12 @@"exported": true,"origin": "ast","body_hash": "eb6324d18b820f95e0423005738f3a8ec5da095849e5934e82ca512c75f1e4f4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a header for the grep results, summarizing the total hits and files searched.",+ "crux": {+ "code": "export function formatGrepHeader(result: GrepResult): string {\n const filesHit = new Set(result.groups.map((g) => g.path)).size;\n return `\"${result.pattern}\" — ${result.totalHits} hits in ${result.groups.length} symbols across ${filesHit} files (searched ${result.filesSearched} indexed files)`;\n}",+ "span": "L36-L39"+ }},{"id": "src/search/grep-cli.ts#formatGrepResult",@@ -7459,9 +8881,12 @@"exported": true,"origin": "ast","body_hash": "e59d3613490b4b2c02381befb02b8c63946845a5073e7ae13298a4b156f43123",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Compiles the full human-readable report of grep results, including headers and formatted groups.",+ "crux": {+ "code": "export function formatGrepResult(result: GrepResult): string {\n const blocks = [formatGrepHeader(result), \"\", ...result.groups.map((g) => formatGroup(g) + \"\\n\")];\n let out = blocks.join(\"\\n\").replace(/\\n+$/, \"\\n\");\n const note = truncationNote(result);\n if (note) out += note + \"\\n\";\n return out;\n}",+ "span": "L53-L59"+ }},{"id": "src/search/grep-cli.ts#formatGroup",@@ -7473,9 +8898,12 @@"exported": false,"origin": "ast","body_hash": "c6901df49ecdcf11c258a32a5e8acf90c887eee405673b9877f0d241ddd7d24d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Formats a group of grep results into a human-readable string, including hit lines.",+ "crux": {+ "code": "function formatGroup(g: GrepGroup): string {\n const lines = [groupHeader(g)];\n for (const h of g.hits) lines.push(` L${h.line}: ${h.text}`);\n return lines.join(\"\\n\");\n}",+ "span": "L29-L33"+ }},{"id": "src/search/grep-cli.ts#GrepCliOptions",@@ -7487,8 +8915,8 @@"exported": true,"origin": "ast","body_hash": "45fbe9e85b94fe0054f047d74a5888cadb3c80836e3f9be8fe9e3074f3efdc5a",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Defines options for the grep command-line interface, allowing customization of search behavior.","crux": null},{@@ -7501,9 +8929,12 @@"exported": false,"origin": "ast","body_hash": "49c6bc64382bd6a38a856a25d53b4f14ce0cb771fe4e9a34acfb07a6a2a85d46",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a header string for a group of grep results, summarizing the group's metadata.",+ "crux": {+ "code": "function groupHeader(g: GrepGroup): string {\n if (g.symbol) return `${g.symbol.name} · ${g.symbol.kind} · ${g.symbol.path}:${g.symbol.span} · ${g.inDegree} in-edges`;\n return `${g.path} (module level) · ${g.inDegree} in-edges`;\n}",+ "span": "L24-L27"+ }},{"id": "src/search/grep-cli.ts#runGrepCommand",@@ -7515,9 +8946,12 @@"exported": true,"origin": "ast","body_hash": "3161968bd9ae55839fa14ad57a480382b2251ce81b5efd31822247079b3759bc",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes the grep command, handling graph resolution, pattern searching, and output formatting.",+ "crux": {+ "code": "export function runGrepCommand(pattern: string, dir: string, opts: GrepCliOptions): void {\n const root = resolve(dir);\n const contextDir = contextDirFor(root, opts.globalDir);\n const graph = loadGraphCached(contextDir);\n if (!graph) {\n console.error(\"✗ no graph — run graft build first\");\n process.exit(1);\n }\n\n let result: GrepResult;\n try {\n result = grepGraph(graph, root, pattern, { ignoreCase: opts.ignoreCase, fixed: opts.fixed, in: opts.in });",+ "span": "L83-L94"+ }},{"id": "src/search/grep-cli.ts#truncationNote",@@ -7529,9 +8963,12 @@"exported": false,"origin": "ast","body_hash": "9cbadb17b0273dea383d0ef0676d8477d369fc7a2231c5b379039c3a96b46517",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a note about any truncation in the grep results, indicating unreadable files or additional hits beyond the cap.",+ "crux": {+ "code": "function truncationNote(result: GrepResult): string | null {\n const { files, hits } = result.truncated;\n if (files === 0 && hits === 0) return null;\n const parts: string[] = [];\n if (hits > 0) parts.push(`${hits} more hit${hits === 1 ? \"\" : \"s\"} beyond the cap`);\n if (files > 0) parts.push(`${files} indexed file${files === 1 ? \"\" : \"s\"} unreadable`);\n return `(truncated: ${parts.join(\", \")} — narrow with --in or refine the pattern)`;\n}",+ "span": "L42-L49"+ }},{"id": "src/search/grep-cli.ts#zeroHitNote",@@ -7543,9 +8980,12 @@"exported": true,"origin": "ast","body_hash": "358cfca22f9a047a4df8b6e452ca54936ac672908468fba2a3dddd7017505cce",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Provides a detailed message for zero-hit results, explaining the absence of matches and potential issues.",+ "crux": {+ "code": "export function zeroHitNote(result: GrepResult): string {\n const base = `no hits for \"${result.pattern}\" in ${result.filesSearched} indexed files — unindexed files (docs, configs, new files) aren't searched; try grep -rn \"${result.pattern}\" for those`;\n const { files } = result.truncated;\n if (files === 0) return base;\n return `${base} — note: ${files} indexed file${files === 1 ? \"\" : \"s\"} could not be read (stale graph? run graft build)`;\n}",+ "span": "L69-L74"+ }},{"id": "src/search/grep.ts",@@ -7558,9 +8998,12 @@"origin": "ast","body_hash": "e0ba3aaa565892e2772e4de0492931a568fc3f3724f8fca44b2a188a24e5eeb4","chars": 6525,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file implements a regex search over indexed files in a graph, grouping results by their enclosing symbols and ranking them by their importance based on incoming edges.",+ "crux": {+ "code": " * `graft grep` core: regex search over the graph's indexed files, with hits\n * grouped by their innermost enclosing symbol and ranked by incoming-edge\n * count (coupling) — a grep that answers \"which of these hits matters\",\n * because plain `grep -rn` gives no way to tell a hit inside a\n * heavily-depended-on function from one inside dead code.",+ "span": "L2-L6"+ }},{"id": "src/search/grep.ts#computeInDegree",@@ -7572,9 +9015,12 @@"exported": false,"origin": "ast","body_hash": "614d2e67e179ee5a934d6c1b03134ca1e1c394d3036a1754bd41dd7ee8dcc1b7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Calculates the incoming edge count for each symbol in the graph, which is used to rank grep hits by importance.",+ "crux": {+ "code": "function computeInDegree(graph: GraphV1): Map<string, number> {\n const deg = new Map<string, number>();\n for (const e of graph.edges) {\n if (!WALK_RELATIONS.has(e.relation)) continue;\n deg.set(e.target, (deg.get(e.target) ?? 0) + 1);\n }\n return deg;\n}",+ "span": "L119-L126"+ }},{"id": "src/search/grep.ts#enclosingSymbol",@@ -7586,9 +9032,12 @@"exported": false,"origin": "ast","body_hash": "980763724d7cfb9637d1a82b38f90ee4c1659a6ad4e06eb8b42ce19d6df771b0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Finds the innermost symbol that contains a specified line number, returning the corresponding node from the graph.",+ "crux": {+ "code": "function enclosingSymbol(symbols: SymbolSpan[], line: number): NodeV1 | null {\n let found: NodeV1 | null = null;\n for (const s of symbols) {\n if (s.start > line) break;\n if (line <= s.end) found = s.node;\n }\n return found;\n}",+ "span": "L108-L115"+ }},{"id": "src/search/grep.ts#escapeRegExp",@@ -7600,9 +9049,12 @@"exported": false,"origin": "ast","body_hash": "4c6310d2cd2f62c68b872392c4843cb011bea7ced8f1ff4db8c010c952f60ba7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Escapes special characters in a string to create a safe regex pattern for searching.",+ "crux": {+ "code": "function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}",+ "span": "L75-L77"+ }},{"id": "src/search/grep.ts#grepGraph",@@ -7614,9 +9066,12 @@"exported": true,"origin": "ast","body_hash": "a18090820283ca87714b7e993b34c5af73234a6aa03759f1829d1d825be58931",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Performs the grep search on the graph, collecting and returning results based on the specified pattern and options.",+ "crux": {+ "code": "export function grepGraph(graph: GraphV1, repoRoot: string, pattern: string, opts: GrepOptions = {}): GrepResult {\n const maxHits = opts.maxHits ?? DEFAULT_MAX_HITS;\n const source = opts.fixed ? escapeRegExp(pattern) : pattern;\n const regex = new RegExp(source, opts.ignoreCase ? \"i\" : \"\");\n\n const inDegree = computeInDegree(graph);\n const fileNodes = graph.nodes.filter((n) => n.kind === \"file\" && (!opts.in || n.path.includes(opts.in)));\n\n const groups = new Map<string, GrepGroup>();\n let collected = 0;\n let truncatedHits = 0;\n let truncatedFiles = 0;",+ "span": "L133-L144"+ }},{"id": "src/search/grep.ts#GrepGroup",@@ -7628,9 +9083,12 @@"exported": true,"origin": "ast","body_hash": "f6498adee93c3a0c7386dd6fd4ffb9ad0e73c2ce5fc6e13c041cdc1c495bdf1d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Groups grep hits by their enclosing symbol, providing context such as the symbol's in-degree and the path of the file.",+ "crux": {+ "code": " /** null → file-level: the hit lies outside every indexed symbol's span\n * (module-level code — imports, top-level statements, module constants). */\n symbol: GrepSymbolRef | null;\n path: string;\n /** Incoming WALK_RELATIONS edges targeting the symbol — always 0 for\n * file-level groups (there's no single symbol id to count edges against). */\n inDegree: number;\n hits: GrepHit[];\n}",+ "span": "L34-L42"+ }},{"id": "src/search/grep.ts#GrepHit",@@ -7642,9 +9100,12 @@"exported": true,"origin": "ast","body_hash": "5a03009952d496614e173831d994debd5b88d66861aa8b4ebb0617e5fb792a5f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Represents a single hit found during the grep search, including the line number and trimmed text of the line.",+ "crux": {+ "code": " line: number;\n /** Trimmed line text, capped at 160 chars. */\n text: string;",+ "span": "L18-L20"+ }},{"id": "src/search/grep.ts#GrepOptions",@@ -7656,9 +9117,12 @@"exported": true,"origin": "ast","body_hash": "0d3f66c959733069e27d33cb53e110dd9f6606d3e77b71362b3c95e9c5a86646",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Holds options for configuring the grep search, such as case sensitivity and maximum hits to collect.",+ "crux": {+ "code": "export interface GrepOptions {\n ignoreCase?: boolean;\n /** Treat `pattern` as a literal string (regex-escaped), not a regex. */\n fixed?: boolean;\n /** Narrow to file nodes whose path contains this substring. */\n in?: string;\n /** Stop collecting hits after this many; the rest are tallied into\n * `truncated.hits`. Default 300. */\n maxHits?: number;\n}",+ "span": "L60-L69"+ }},{"id": "src/search/grep.ts#GrepResult",@@ -7670,9 +9134,12 @@"exported": true,"origin": "ast","body_hash": "0e16fb84e869bb3443c681dd6c4f18ca395c415858fb8800a8024b4118474ca2",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Encapsulates the results of a grep operation, including the pattern searched, total hits, and grouped results.",+ "crux": {+ "code": "export interface GrepResult {\n pattern: string;\n /** Indexed file nodes considered (after the `in` filter), whether or not\n * each was actually readable — matches the CLI's \"searched N indexed\n * files\" wording. */\n filesSearched: number;\n /** Hits actually collected (<= maxHits). */\n totalHits: number;\n /** Sorted: inDegree desc, then path asc. */\n groups: GrepGroup[];\n /** Dropped counts — never silent. `files`: indexed file nodes that\n * couldn't be read from disk. `hits`: matches found beyond `maxHits`,",+ "span": "L44-L55"+ }},{"id": "src/search/grep.ts#GrepSymbolRef",@@ -7684,9 +9151,12 @@"exported": true,"origin": "ast","body_hash": "021dcfb0dffc4d64379a0dd13b7f8ba1c31d66ed199cd35a08b0d877fa39e0e4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines a reference to a symbol in the graph, including its qualified name and span, to facilitate grouping grep hits by their enclosing symbols.",+ "crux": {+ "code": " id: string;\n /** Qualified scope-joined name (e.g. `FastAPI.include_router`), not just\n * the bare symbol name — the id's segment after the file-path `#`. */\n name: string;\n kind: string;\n path: string;\n span: string;",+ "span": "L24-L30"+ }},{"id": "src/search/grep.ts#spanBounds",@@ -7698,9 +9168,12 @@"exported": false,"origin": "ast","body_hash": "07501d016c2decb33d98ef556db8322d35e7753945a15803d9579b03bd80d5a1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Extracts the start and end line numbers from a span string, returning null if the format is invalid.",+ "crux": {+ "code": "function spanBounds(span: string): { start: number; end: number } | null {\n const m = SPAN_RE.exec(span);\n if (!m) return null;\n return { start: Number(m[1]), end: Number(m[2]) };\n}",+ "span": "L79-L83"+ }},{"id": "src/search/grep.ts#symbolsOf",@@ -7712,9 +9185,12 @@"exported": false,"origin": "ast","body_hash": "26481c2032801b2e8e12980416a4d10b1a1bddb66c0d6d4bfa97cb918c94f0c4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Retrieves and sorts the symbols of a given file in the graph, based on their span start lines.",+ "crux": {+ "code": "function symbolsOf(graph: GraphV1, path: string): SymbolSpan[] {\n const out: SymbolSpan[] = [];\n for (const n of graph.nodes) {\n if (n.kind === \"file\" || n.path !== path) continue;\n const b = spanBounds(n.span);\n if (b) out.push({ node: n, start: b.start, end: b.end });\n }\n out.sort((a, b) => a.start - b.start);\n return out;\n}",+ "span": "L93-L102"+ }},{"id": "src/search/grep.ts#SymbolSpan",@@ -7726,9 +9202,12 @@"exported": false,"origin": "ast","body_hash": "ed659214924ee7e720952748e5e217835cb3988e58c0a840f85800c1207cd6f3",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Represents a span of a symbol in the graph, including its start and end lines, to assist in finding enclosing symbols.",+ "crux": {+ "code": "interface SymbolSpan {\n node: NodeV1;\n start: number;\n end: number;\n}",+ "span": "L85-L89"+ }},{"id": "src/search/grep.ts#toSymbolRef",@@ -7740,9 +9219,12 @@"exported": false,"origin": "ast","body_hash": "f527f108414f4112517e03e555c78d998f5d3cea3a6bf89b2f9b383bc73aa732",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Converts a node in the graph to a GrepSymbolRef, providing a structured representation of the symbol.",+ "crux": {+ "code": "function toSymbolRef(n: NodeV1): GrepSymbolRef {\n const hash = n.id.indexOf(\"#\");\n return { id: n.id, name: hash >= 0 ? n.id.slice(hash + 1) : n.name, kind: n.kind, path: n.path, span: n.span };\n}",+ "span": "L128-L131"+ }},{"id": "src/util/id.ts",@@ -8060,8 +9542,8 @@"origin": "ast","body_hash": "c9cd7c011ebd661f35488c59dcd34801079f2786d56e96833f4da7c45dfa37d7","chars": 16112,- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "This file contains tests to ensure the integrity and correctness of the `ask` sidecar functionality, verifying that it accurately reproduces live tokenization results and handles various edge cases without failure.","crux": null},{@@ -8074,9 +9556,12 @@"exported": false,"origin": "ast","body_hash": "c90c21864f82921d79c49a3ab3b523d234323a0850a634de37d08abced8fd0f8",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a temporary multi-file fixture with overlapping vocabulary to facilitate meaningful tests on tokenization and scoring.",+ "crux": {+ "code": "function makeFixture(): string {\n const dir = mkdtempSync(join(tmpdir(), \"graft-ask-index-\"));\n writeFileSync(\n join(dir, \"auth.ts\"),\n `/** Validate an incoming API request's auth token. */\\n` +\n `export function validateAuthToken(token: string): boolean {\\n` +\n ` return token.length > 0;\\n` +\n `}\\n\\n` +\n `export function authMiddleware(req: unknown): boolean {\\n` +\n ` return validateAuthToken(\"x\");\\n` +\n `}\\n`,\n );",+ "span": "L26-L37"+ }},{"id": "test/ask-index.test.ts#reinjectBodyText",@@ -8088,9 +9573,12 @@"exported": false,"origin": "ast","body_hash": "dd2e01921c74775b79f94544f814554415656ca604983fbcd14b10a0fea1a6b0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Reconstructs the body text for nodes in the wiring.json to ensure accurate tokenization results during tests.",+ "crux": {+ "code": " const wpath = wiringPath(outDir);\n const graph = JSON.parse(readFileSync(wpath, \"utf8\")) as GraphV1;\n const bodyById = new Map<string, string>();\n for (const entry of readdirSync(dir)) {\n const lang = languageOf(entry);\n if (!lang) continue;\n const source = readFileSync(join(dir, entry), \"utf8\");\n const { nodes } = extractFile(entry, source, lang);\n for (const n of nodes) if (n.body_text !== undefined) bodyById.set(n.id, n.body_text);\n }\n for (const n of graph.nodes as NodeV1[]) {\n const bt = bodyById.get(n.id);",+ "span": "L70-L81"+ }},{"id": "test/ask-index.test.ts#sortPairs",@@ -8102,9 +9590,12 @@"exported": false,"origin": "ast","body_hash": "67de2733865dd8e5d635892fb085c3781a9a541c49ad2d112c8c150aaef655b6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sorts an array of pairs by the first element, ensuring consistent ordering for comparison in tests.",+ "crux": {+ "code": " const sortPairs = (p: [string, number][]) => [...p].sort((a, b) => a[0].localeCompare(b[0]));",+ "span": "L106-L106"+ }},{"id": "test/ask.test.ts",@@ -8117,11 +9608,11 @@"origin": "ast","body_hash": "3445f8b156ba6b2f0e9123e9fc45781da352ec6d5baeb985ee144fe5aecaafb3","chars": 11713,- "summary_state": "stale",- "summary": "This file contains tests for the `graft ask` functionality, ensuring that the source option correctly inlines code from disk when requested.",+ "summary_state": "ready",+ "summary": "Contains tests for the `ask` functionality, validating its behavior with various options and scenarios.","crux": {"code": "test(\"ask without source returns pointers but no inlined code\", async () => {\n const dir = makeFixture();\n try {\n await buildGraph(dir); // $0, structure-only — cards + wiring.json\n const r = ask(dir, \"addNumbers\");\n const hit = r.hits.find((h) => h.title.startsWith(\"addNumbers\"));\n assert.ok(hit, \"should locate the addNumbers symbol\");\n assert.match(hit.pointer, /^math\\.ts:L\\d+-L\\d+$/);\n assert.equal(hit.code, undefined, \"no source inlined without the option\");\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }",- "span": "L26-L37"+ "span": "L27-L38"}},{@@ -8151,9 +9642,12 @@"exported": false,"origin": "ast","body_hash": "9d1086ae8f0a6226d68cdbf7006c21e891972897ebe7510d188f913958306ca2",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sets up a temporary directory with a cache implementation to test structural resolution of function calls.",+ "crux": {+ "code": " `export function loadItem(key: string): string {\\n` +\n ` const c = new Cache();\\n` +\n ` return c.get(key);\\n` +",+ "span": "L198-L200"+ }},{"id": "test/ask.test.ts#stampCrux",@@ -8165,9 +9659,12 @@"exported": false,"origin": "ast","body_hash": "88e65ff2cd0c7e96135c81d1072a15b210a7b2ddad022394ea8f59f6842dcbf4",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Updates the wiring.json file to include a crux for the specified node, allowing for inlined source retrieval.",+ "crux": {+ "code": " n.crux = { code, span: \"L2-L2\" };",+ "span": "L47-L47"+ }},{"id": "test/claude-format.test.ts",@@ -8180,9 +9677,12 @@"origin": "ast","body_hash": "cfaa9f489dd95956e3c9917ebe29a46992dfdbab943b5971eecbd98f18b3268c","chars": 7267,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite verifies the functionality of various formatting and retrieval functions related to the status line and enriched segments in a codebase, ensuring correct rendering based on different states and inputs.",+ "crux": {+ "code": "test('not-built state', () => {\n const lines = renderStatusline(null, null, { ctxPct: null });\n assert.match(strip(lines[0]), /not built/);\n});\n\ntest('enriched segment hidden when zero ready', () => {\n assert.equal(enrichedSegment({ ...emptyStats(), totalCount: 10, readyCount: 0 }), null);\n});\n\ntest('enriched segment shown when >=1 ready', () => {\n const seg = enrichedSegment({ ...emptyStats(), totalCount: 4, readyCount: 2 });\n assert.equal(strip(seg!), '50% enriched');",+ "span": "L8-L19"+ }},{"id": "test/claude-format.test.ts#freshSession",@@ -8194,9 +9694,12 @@"exported": false,"origin": "ast","body_hash": "61509362f702d01df4dfd7777521ae04e30c0dbc1656070024e4712c763314ee",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Initializes a fresh session state for testing the relevant retrieval process.",+ "crux": {+ "code": "const freshSession = () => ({ lastQuery: null, perAgentQuery: {}, graftReads: 0, sourceReads: 0, savedTokens: 0, injectedPointers: [] as string[] });",+ "span": "L105-L105"+ }},{"id": "test/claude-format.test.ts#gateAsk",@@ -8208,9 +9711,12 @@"exported": false,"origin": "ast","body_hash": "34d03c21985709ffe94de675b861d213c0d38d4794d221e1dd41f634f1837117",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a structured query object for testing relevant retrieval functionality with customizable parameters.",+ "crux": {+ "code": "const gateAsk = (over: Record<string, unknown> = {}) => ({\n query: 'pkce', mode: 'lexical', coverage: 1,\n hits: [\n { kind: 'symbol', title: 'verify', pointer: 'src/pkce.ts:L1-L4', snippet: 's', score: 1 },\n { kind: 'symbol', title: 'gen', pointer: 'src/pkce.ts:L6-L9', snippet: 's', score: 0.8 },\n ],\n ...over,\n}) as any;",+ "span": "L97-L104"+ }},{"id": "test/claude-format.test.ts#strip",@@ -8222,9 +9728,12 @@"exported": false,"origin": "ast","body_hash": "6381d72b2af2fa01d40d5fa8e463da782c5fe5655ad06caec8a3184ee6546edc",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Removes ANSI escape codes from a string to ensure clean output for assertions.",+ "crux": {+ "code": "const strip = (s: string) => s.replace(/\\x1b\\[[0-9;]*m/g, '');",+ "span": "L6-L6"+ }},{"id": "test/claude-hooks.test.ts",@@ -8237,9 +9746,12 @@"origin": "ast","body_hash": "875c10776da455499b58ebe861b3cb0ae797f751e4e838812cd0b4f3c13587c2","chars": 6930,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the functionality of the graft hooks in the Claude project, ensuring that edits are detected and state is managed correctly.",+ "crux": {+ "code": "test('underGraft detects edits inside graft/', () => {\n assert.equal(underGraft('/repo', '/repo/graft/x.md'), true);\n assert.equal(underGraft('/repo', '/repo/src/cli.ts'), false);\n});\n\ntest('post-edit marks dirty and records lastFile', async () => {\n const d = mkdtempSync(join(tmpdir(), 'graft-hooks-'));\n mkdirSync(join(d, 'graft', '.graph'), { recursive: true });\n writeFileSync(join(d, 'graft', '.graph', 'wiring.json'),\n JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));\n // graft check will fail (no dist/cli.js here) → staleCount falls back to 0, but dirty must still be set.\n process.env.CLAUDE_PROJECT_DIR = d;",+ "span": "L11-L22"+ }},{"id": "test/claude-hooks.test.ts#fakeBuild",@@ -8251,9 +9763,12 @@"exported": false,"origin": "ast","body_hash": "0eb606c28f6d7ec57d7fe9a9824b87942c0682ddb75d37fd911508366e5ac9e5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This function simulates a build process by writing a mock wiring.json file to the specified directory, allowing tests to verify behavior based on the build output.",+ "crux": {+ "code": " const fakeBuild = (dir: string) => writeFileSync(join(dir, 'graft', '.graph', 'wiring.json'),\n JSON.stringify({ meta: { nodeCount: 2, edgeCount: 1, languages: ['typescript'] },\n nodes: [{ id: 'a', summary_state: 'ready' }, { id: 'b', summary_state: 'pending' }],\n edges: [{ from: 'a', to: 'b' }] }));",+ "span": "L84-L87"+ }},{"id": "test/claude-hooks.test.ts#runWithStdin",@@ -8265,9 +9780,12 @@"exported": false,"origin": "ast","body_hash": "6bf4b171a46fcfcceccaedd45a273ed78fac5a1b4ae47bbd881df4e54c33b912",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This function sets up the environment to run a given asynchronous function with specified input from stdin, managing the environment variable for the duration of the execution.",+ "crux": {+ "code": " process.env.GRAFT_TEST_STDIN = text;\n try { await fn(); } finally { delete process.env.GRAFT_TEST_STDIN; }\n}",+ "span": "L39-L41"+ }},{"id": "test/claude-init.test.ts",@@ -8280,9 +9798,12 @@"origin": "ast","body_hash": "b582cd79b2a1e4952ff83ac1b2e85f742756443c2896e08d96a75dc76e2971a5","chars": 6213,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the initialization logic of the graft system, ensuring that settings and skills are correctly scaffolded and managed during the initialization process.",+ "crux": {+ "code": "test('runInit scaffolds settings + both shims + the skill (build skipped)', () => {\n const d = fresh();\n const r = runInit(d, { build: false });\n assert.ok(existsSync(join(d, '.claude', 'settings.json')));\n assert.ok(existsSync(join(d, '.claude', 'helpers', 'graft-statusline.cjs')));\n assert.ok(existsSync(join(d, '.claude', 'helpers', 'graft-hooks.cjs')));\n const skillPath = join(d, '.claude', 'skills', 'graft', 'SKILL.md');\n assert.ok(existsSync(skillPath), 'writes the graft skill');\n assert.equal(r.skill, skillPath);\n assert.match(readFileSync(skillPath, 'utf8'), /name: graft/);\n assert.equal(r.built, false);\n const s = JSON.parse(readFileSync(join(d, '.claude', 'settings.json'), 'utf8'));",+ "span": "L19-L30"+ }},{"id": "test/claude-init.test.ts#col",@@ -8294,9 +9815,12 @@"exported": false,"origin": "ast","body_hash": "0b37f9523b6cb61e19981676c6eea4c39d624029fbc06e88392bb90dec866d68",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Determines the column alignment for specific text markers in the output, ensuring consistent formatting in the display.",+ "crux": {+ "code": " const col = (text: string, marker: string) => text.split('\\n').find((l) => l.includes(marker))!.indexOf('a new session');",+ "span": "L116-L116"+ }},{"id": "test/claude-init.test.ts#fresh",@@ -8308,9 +9832,12 @@"exported": false,"origin": "ast","body_hash": "e730884fcd6a9cadcca1e8a2f33564442c1ea4a2d1589c56af4b51b6de23d940",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a fresh temporary directory for testing purposes, ensuring isolation between test runs.",+ "crux": {+ "code": "function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-init-')); }",+ "span": "L10-L10"+ }},{"id": "test/claude-init.test.ts#runPostinstall",@@ -8322,9 +9849,12 @@"exported": false,"origin": "ast","body_hash": "a9ee9b51b2acd9ee930e28e5c0968dc94c648d848eac513230143d3acadae7e7",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes the post-installation script, which sets up necessary configurations after the main initialization process.",+ "crux": {+ "code": "function runPostinstall(env: Record<string, string>): string {\n try {\n return execFileSync(process.execPath, ['scripts/postinstall.mjs'],\n { encoding: 'utf8', env: { ...process.env, ...env } });\n } catch { return ''; }",+ "span": "L12-L16"+ }},{"id": "test/claude-paths.test.ts",@@ -8337,9 +9867,12 @@"origin": "ast","body_hash": "205740f8110e72e4cb24652c09f763fad5e056dc77776bcfa95a1953731ed2c8","chars": 1063,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test file verifies that the paths for the graft CLI and Claude script are correctly resolved relative to the module structure, ensuring they are independent of the current working directory.",+ "crux": {+ "code": "test('graftCliPath is module-relative (cwd-independent) and points at a sibling cli.js', () => {\n const a = graftCliPath();\n const orig = process.cwd();\n try { process.chdir('/'); assert.equal(graftCliPath(), a, 'must not depend on cwd / project dir'); }\n finally { process.chdir(orig); }\n assert.match(a, /[/\\\\]cli\\.js$/);\n // cli.js sits one level above the claude module dir → its parent dir is src (tsx) or dist (built)\n assert.match(basename(dirname(a)), /^(src|dist)$/);\n});\n\ntest('claudeScriptPath resolves a sibling script in the claude dir (cwd-independent)', () => {\n const a = claudeScriptPath('sync-run.js');",+ "span": "L6-L17"+ }},{"id": "test/claude-settings-merge.test.ts",@@ -8352,9 +9885,12 @@"origin": "ast","body_hash": "4c8b800f02d1b72050082bdbcdcda0878e5d9760563d2e1ca4a31cb06ffaaabb","chars": 4109,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite verifies the behavior of merging Graft settings, ensuring that defaults are applied correctly, existing configurations are preserved, and no duplicates are introduced during re-initialization.",+ "crux": {+ "code": "test('empty settings gets the full Graft blocks', () => {\n const { merged, warnings } = mergeGraftSettings({});\n assert.equal(merged.statusLine.command, SL);\n assert.equal(merged.subagentStatusLine.command, SL);\n assert.ok(Array.isArray(merged.hooks.PostToolUse));\n assert.equal(merged.hooks.PostToolUse[0].matcher, 'Write|Edit|MultiEdit');\n for (const e of ['PostToolUse', 'UserPromptSubmit', 'SessionStart', 'Stop']) {\n assert.ok(merged.hooks[e][0].hooks[0].command.includes('graft-hooks.cjs'), `${e} wired`);\n }\n assert.ok(merged.footerLinksRegexes.includes('graft/[\\\\w./-]+\\\\.md'));\n assert.deepEqual(warnings, []);\n});",+ "span": "L7-L18"+ }},{"id": "test/claude-shim-template.test.ts",@@ -8367,9 +9903,12 @@"origin": "ast","body_hash": "f787f99fef2dc6a5ed366419fc470e8e4f825e0bc590cf3550d39e01995e7619","chars": 1585,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test file validates the behavior of the statusline and hooks shims to ensure they correctly parse and resolve module paths in a Node.js environment.",+ "crux": {+ "code": " const body = src.replace(/^#!.*\\n/, ''); // strip shebang for vm\n assert.doesNotThrow(() => new vm.Script(body), 'valid JS');\n\n // 1. baked dir is present as the first candidate\n assert.match(src, new RegExp(`const BAKED = \"${BAKED}\"`));\n // 2. repo node_modules via require.resolve from the project dir\n assert.match(src, /require\\.resolve\\('@nanonets\\/graft\\/package\\.json', \\{ paths: \\[base\\] \\}\\)/);\n assert.match(src, /fromPkg\\(dir\\)/);\n // 3. legacy execPath/../lib guess retained\n assert.match(src, /path\\.join\\(path\\.dirname\\(process\\.execPath\\), '\\.\\.', 'lib'\\)/);\n // 4. npm root -g catch-all, queried on demand (no on-disk cache)\n assert.match(src, /execFileSync\\('npm', \\['root', '-g'\\]/);",+ "span": "L10-L21"+ }},{"id": "test/claude-skill-template.test.ts",@@ -8382,9 +9921,12 @@"origin": "ast","body_hash": "49f60183a51f9c307a33b5d4da3a7ded2f55509407e6a85778f3512b27db7cde","chars": 1188,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test ensures that the generated skill template adheres to the expected format and contains the necessary components for functionality.",+ "crux": {+ "code": " assert.ok(src.startsWith('---\\n'), 'starts with YAML frontmatter');\n assert.match(src, /^name: graft$/m, 'declares name: graft');\n assert.match(src, /^description:/m, 'has a description');\n const body = src.split(/\\n---\\n/)[1] ?? '';\n assert.ok(body.trim().length > 0, 'has a non-empty body');\n assert.match(body, /graft ask/, 'body tells the agent to use `graft ask`');\n assert.match(body, /every occurrence/i, 'body teaches the exhaustive-task grep rule');\n assert.match(body, /graft callers/, 'body teaches the callers command');\n assert.match(body, /graft callees/, 'body teaches the callees command');\n assert.match(body, /graft impact/, 'body teaches the impact command');\n assert.match(body, /truncated/i, 'body tells the agent to follow up on truncated spans');\n assert.match(body, /graft grep/, 'body routes sweeps to graft grep');",+ "span": "L7-L18"+ }},{"id": "test/claude-state.test.ts",@@ -8397,9 +9939,12 @@"origin": "ast","body_hash": "78e6a81af7642ea788072457ea181bc626c7a8a898cfebb882ab42fed7e9dd2e","chars": 1991,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite verifies the functionality of state management, including stats and session handling, as well as lock acquisition and release mechanisms.",+ "crux": {+ "code": "test('stats round-trip and patch merge', () => {\n const d = fresh();\n assert.equal(readStats(d), null);\n writeStats(d, { ...emptyStats(), nodeCount: 319, edgeCount: 730 });\n assert.equal(readStats(d)!.nodeCount, 319);\n const patched = patchStats(d, { dirty: true, staleCount: 4 });\n assert.equal(patched.dirty, true);\n assert.equal(patched.staleCount, 4);\n assert.equal(readStats(d)!.edgeCount, 730, 'patch preserves other fields');\n});\n\ntest('session defaults and round-trip', () => {",+ "span": "L13-L24"+ }},{"id": "test/claude-state.test.ts#fresh",@@ -8411,9 +9956,12 @@"exported": false,"origin": "ast","body_hash": "49e9f70f3b52532360521760ee5e0e5c907bdf3f55d1ed2c90bb3c3e48d93cda",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a unique temporary directory for testing purposes to ensure isolation between test cases.",+ "crux": {+ "code": "function fresh(): string { return mkdtempSync(join(tmpdir(), 'graft-state-')); }",+ "span": "L11-L11"+ }},{"id": "test/claude-stats.test.ts",@@ -8426,9 +9974,12 @@"origin": "ast","body_hash": "f625d026d152a65017699e37e27534043dc0af0f43ba2d3ea778bac8ddab82c3","chars": 983,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test file verifies the functionality of the computeStats function to ensure it accurately calculates node and edge counts, as well as the count of ready nodes from a given wiring structure.",+ "crux": {+ "code": "test('computeStats derives counts and readyCount', () => {\n const s = computeStats(wiring);\n assert.equal(s.nodeCount, 3);\n assert.equal(s.edgeCount, 2);\n assert.deepEqual(s.languages, ['typescript']);\n assert.equal(s.totalCount, 3);\n assert.equal(s.readyCount, 2);",+ "span": "L15-L21"+ }},{"id": "test/claude-statusline.test.ts",@@ -8441,9 +9992,12 @@"origin": "ast","body_hash": "07128b5b195af3a37c1e170a35c18378e36160d1a6f8e17be362bac315811cac","chars": 2137,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the resolveStats function, ensuring it correctly retrieves and prioritizes cached statistics or falls back to graph data as needed.",+ "crux": {+ "code": "test('resolveStats returns the hook-maintained cache when present and non-empty', () => {\n const d = repo();\n writeStats(d, { ...emptyStats(), nodeCount: 5, edgeCount: 9, dirty: true, staleCount: 2 });\n const s = resolveStats(d)!;\n assert.equal(s.nodeCount, 5);\n assert.equal(s.dirty, true, 'cache is the source of truth when present');\n});\n\ntest('resolveStats falls back to wiring.json when no cache (manual graft build / fresh checkout)', () => {\n const d = repo();\n writeWiring(d, {\n meta: { nodeCount: 42, edgeCount: 100, languages: ['typescript'] },",+ "span": "L15-L26"+ }},{"id": "test/claude-statusline.test.ts#repo",@@ -8455,9 +10009,12 @@"exported": false,"origin": "ast","body_hash": "121eb027efad697b8021b3a994a7f977441a0a34c0e92fd9a1792851368850e5",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a temporary directory for testing purposes, ensuring a clean environment for each test run.",+ "crux": {+ "code": "function repo(): string { return mkdtempSync(join(tmpdir(), 'graft-sl-')); }",+ "span": "L9-L9"+ }},{"id": "test/claude-statusline.test.ts#writeWiring",@@ -8469,9 +10026,12 @@"exported": false,"origin": "ast","body_hash": "2e1f37e4395b142a5e04d343c3d72366ed3c3245acc13afc8eef46df21b1df21",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Writes a wiring.json file to a specified directory, setting up the necessary structure for graph data in tests.",+ "crux": {+ "code": "function writeWiring(dir: string, obj: unknown): void {\n mkdirSync(join(dir, 'graft', '.graph'), { recursive: true });\n writeFileSync(join(dir, 'graft', '.graph', 'wiring.json'), JSON.stringify(obj));",+ "span": "L10-L12"+ }},{"id": "test/cli-meta.test.ts",@@ -8484,9 +10044,12 @@"origin": "ast","body_hash": "e7a05bf838e876a317276f94a26d92b0b1526e1ea7eabda4e68b804bdb0334e5","chars": 3338,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for formatting version and upgrade reports, resolving package.json paths, reading the current version, and detecting if a script is running via npx, ensuring correct behavior of the CLI meta functionalities.",+ "crux": {+ "code": "test('formatVersionReport: up to date', () => {\n const out = formatVersionReport('0.4.4', { ok: true, version: '0.4.4' });\n assert.equal(out, 'graft 0.4.4\\nlatest on npm: 0.4.4 ✓ up to date');\n});\n\ntest('formatVersionReport: newer version available', () => {\n const out = formatVersionReport('0.4.4', { ok: true, version: '0.4.5' });\n assert.equal(out, 'graft 0.4.4\\nlatest on npm: 0.4.5 — run graft upgrade');\n});\n\ntest('formatVersionReport: offline / unreachable', () => {\n const out = formatVersionReport('0.4.4', { ok: false });",+ "span": "L16-L27"+ }},{"id": "test/context.test.ts",@@ -8499,11 +10062,11 @@"origin": "ast","body_hash": "126861c136d48ed6a148e50226c96ec2935c52cf83ef56fbd43392e0d271db1f","chars": 7976,- "summary_state": "stale",- "summary": "This file contains end-to-end tests for the markdown-graph pipeline to ensure proper functionality and integrity of the context building and checking processes.",+ "summary_state": "ready",+ "summary": "This file contains end-to-end tests for the markdown-graph pipeline, ensuring that the initialization and checking processes work correctly with various scenarios.","crux": {"code": "test(\"init builds one markdown node per entity, with links and a manifest\", async () => {\n const dir = makeFixture();\n try {\n const r = await buildContext(dir, buildOpts());\n // Auth Service, Token Store, Billing.\n assert.equal(r.nodes, 3);\n assert.equal(r.links, 2);\n assert.equal(r.files, 2);\n\n const ctx = join(dir, \"graft\");\n assert.ok(existsSync(join(ctx, \"auth-service.md\")));\n assert.ok(existsSync(join(ctx, \"token-store.md\")));",- "span": "L31-L42"+ "span": "L49-L60"}},{@@ -8547,9 +10110,12 @@"exported": false,"origin": "ast","body_hash": "f6727f675d8cb599692eabff8675faa168c515b6cfe5d91fbc1092f31371e31f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This function executes a command-line interface (CLI) command and captures its output, allowing tests to verify the behavior of the CLI under different conditions.",+ "crux": {+ "code": " const stdout = execFileSync(process.execPath, [\"--import\", \"tsx\", \"src/cli.ts\", ...args], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n return { stdout, stderr: \"\", status: 0 };\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string; status?: number };\n return { stdout: e.stdout ?? \"\", stderr: e.stderr ?? \"\", status: e.status ?? 1 };",+ "span": "L21-L28"+ }},{"id": "test/covers.test.ts",@@ -8597,9 +10163,12 @@"origin": "ast","body_hash": "b6892b1b6982547fc67d5b0e7812a536e47018ab3e38e4eda35a0f12f24ab8db","chars": 4267,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests that validate the behavior of type bindings in different programming languages' code snippets.",+ "crux": {+ "code": "test(\"py: constructor assignment binds receiver type\", () => {\n const edges = callEdges(\"class A:\\n def m(self): pass\\napp = A()\\ndef f():\\n app.m()\\n\", \"python\");\n const call = edges.find((e) => e.name === \"m\" && e.viaMember);\n assert.equal(call?.recvType, \"A\");\n});\n\ntest(\"py: parameter annotation binds\", () => {\n const edges = callEdges(\"def f(app: FastAPI):\\n app.include_router()\\n\", \"python\");\n assert.equal(edges.find((e) => e.name === \"include_router\")?.recvType, \"FastAPI\");\n});\n\ntest(\"py: self binds to enclosing class; self.attr via __init__ assignment\", () => {",+ "span": "L9-L20"+ }},{"id": "test/graph-bindings.test.ts#callEdges",@@ -8611,9 +10180,12 @@"exported": false,"origin": "ast","body_hash": "835bab16fc5593e4c29ca25d3accec71d790d08f8d0127043711501b6ba94e2d",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This function extracts call edges from source code based on the specified programming language, filtering for 'calls' relations.",+ "crux": {+ "code": " return extractFile(file, src, lang).rawEdges.filter((e) => e.relation === \"calls\");",+ "span": "L6-L6"+ }},{"id": "test/graph-go.test.ts",@@ -8626,9 +10198,12 @@"origin": "ast","body_hash": "bf11085a7edb03c00d52dca090af9c1ca4eb3cb34bb88904bbdd478171d3483d","chars": 5664,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for verifying the extraction of Go code structures and their relationships in a code graph.",+ "crux": {+ "code": "test(\"Go extraction: funcs, methods, structs, interfaces, type aliases\", async () => {\n const dir = makeFixture();\n try {\n const result = await buildGraph(dir); // $0, Tier-1 only\n assert.ok(result.languages.includes(\"go\"), \"languages should include go\");\n\n const graph = readGraph(wiringPath(join(dir, \"graft\")));\n assert.ok(graph, \"wiring graph should be written\");\n\n // functions — exported by leading-uppercase\n const foo = nodeById(graph!, \"main.go#Foo\");\n assert.equal(foo?.kind, \"function\");",+ "span": "L66-L77"+ }},{"id": "test/graph-go.test.ts#makeFixture",@@ -8640,9 +10215,12 @@"exported": false,"origin": "ast","body_hash": "76b9a9cf518c965694990ed9cbfa55da12a5eb1bdc5b662c6b0550fb038dbb04",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a temporary Go module directory with necessary files for testing graph extraction.",+ "crux": {+ "code": " const dir = mkdtempSync(join(tmpdir(), \"graft-go-\"));\n writeFileSync(join(dir, \"go.mod\"), \"module mymod\\n\\ngo 1.21\\n\");\n writeFileSync(join(dir, \"main.go\"), MAIN_GO);\n mkdirSync(join(dir, \"pkg\", \"util\"), { recursive: true });\n writeFileSync(join(dir, \"pkg\", \"util\", \"util.go\"), UTIL_GO);\n return dir;\n}",+ "span": "L54-L60"+ }},{"id": "test/graph-go.test.ts#nodeById",@@ -8654,8 +10232,8 @@"exported": false,"origin": "ast","body_hash": "7d35f3037365876a2bedd0af5973ec5cc0b3871e3bce7f310993d907ae378c67",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Retrieves a node from the graph by its unique identifier, facilitating graph traversal and assertions in tests.","crux": null},{@@ -8669,9 +10247,12 @@"origin": "ast","body_hash": "8df11988d049b5243d8c7a0d55045163b714965897448797b40c8ef458b0896b","chars": 5524,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for caching mechanisms in the graph loading functionality to improve performance by avoiding unnecessary re-parsing of files.",+ "crux": {+ "code": "test(\"loadGraphCached: two loads of an unchanged file return the same parsed object\", () => {\n const dir = fixtureDir();\n writeGraph({ version: 1, nodes: [node(\"a\")], edges: [] } as GraphV1, dir);\n __resetParseCounts();\n\n const g1 = loadGraphCached(dir);\n const g2 = loadGraphCached(dir);\n assert.ok(g1);\n assert.strictEqual(g1, g2, \"second load must reuse the cached object, not re-parse\");\n assert.equal(__parseCount.graph, 1);\n});\n",+ "span": "L52-L63"+ }},{"id": "test/graph-load.test.ts#bump",@@ -8683,9 +10264,12 @@"exported": false,"origin": "ast","body_hash": "8779dc90b4ac3a22fe19faeeb81277a8a6b3cfa975a943ea81eaae7057c8ff91",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Updates the modification time of a file to ensure that caching mechanisms recognize changes, preventing stale data usage.",+ "crux": {+ "code": "function bump(path: string): void {\n const st = statSync(path);\n const future = new Date(st.mtimeMs + 1000);\n utimesSync(path, future, future);\n}",+ "span": "L46-L50"+ }},{"id": "test/graph-load.test.ts#fixtureDir",@@ -8697,9 +10281,12 @@"exported": false,"origin": "ast","body_hash": "3f567c59fa24284eaa46cfde4904ae179e1dae786288df2256d80d65721c95c9",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a temporary directory for use in tests, ensuring isolation and preventing interference between test cases.",+ "crux": {+ "code": "function fixtureDir(): string {\n return mkdtempSync(join(tmpdir(), \"graft-load-\"));\n}",+ "span": "L40-L42"+ }},{"id": "test/graph-load.test.ts#node",@@ -8711,9 +10298,12 @@"exported": false,"origin": "ast","body_hash": "50c83e997e60e662392960d89cc6c5b421a65cfd8c166084e4c5f3c8ea9a9bd6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a node representation for the graph with specified properties, facilitating the construction of graph structures in tests.",+ "crux": {+ "code": " return {\n id,\n name: id,\n kind: \"function\",\n path: `${id}.ts`,\n span: \"L1-L1\",\n signature: null,\n exported: true,\n origin: \"ast\",\n body_hash: id,\n summary_state: \"pending\",\n summary: null,",+ "span": "L24-L35"+ }},{"id": "test/graph-map.test.ts",@@ -8726,9 +10316,12 @@"origin": "ast","body_hash": "97c06030735d5dbb15270b73a594e1de8fb3ffba5c6551b6303a5357b8da31be","chars": 11746,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the `buildRepoMap` and `formatRepoMap` functions, ensuring they correctly process and format repository data.",+ "crux": {+ "code": "test(\"buildRepoMap: totals count files, symbols, edges, and languages across the whole graph\", () => {\n const nodes = [\n fileNode(\"src/a.ts\"),\n symNode(\"src/a.ts\", \"fnA\"),\n fileNode(\"docs/readme.py\"), // deliberately mixed languages\n symNode(\"docs/readme.py\", \"fnB\"),\n ];\n const edges = [edge(\"src/a.ts#fnA\", \"docs/readme.py#fnB\")];\n const map = buildRepoMap(graphOf(nodes, edges));\n\n assert.equal(map.totals.files, 2);\n assert.equal(map.totals.symbols, 2);",+ "span": "L65-L76"+ }},{"id": "test/graph-map.test.ts#bigFixture",@@ -8740,9 +10333,12 @@"exported": false,"origin": "ast","body_hash": "36aa3a253a2bbeb21b090b155800f0354efd0e279bcf199a768d0cd9b8f66aac",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a large fixture graph for testing, simulating a repository with multiple directories and symbols.",+ "crux": {+ "code": "function bigFixture(): GraphV1 {\n const nodes: NodeV1[] = [];\n const edges: EdgeV1[] = [];\n const dirs = [\"alpha\", \"beta\", \"gamma\", \"delta\"];\n for (const dir of dirs) {\n for (let f = 0; f < 3; f++) {\n const path = `${dir}/file${f}.ts`;\n nodes.push(fileNode(path));\n for (let s = 0; s < 4; s++) {\n const name = `${dir}Sym${f}_${s}`;\n nodes.push(symNode(path, name));\n // Give the first symbol in each file a bunch of callers so it's a hub.",+ "span": "L240-L251"+ }},{"id": "test/graph-map.test.ts#edge",@@ -8754,9 +10350,12 @@"exported": false,"origin": "ast","body_hash": "123ba52d4dfdf593b1dd056eb9c949165a0ba7fd06eaf374cf1bf1bd797baee8",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines a connection between two nodes in the graph, representing relationships such as function calls.",+ "crux": {+ "code": "function edge(source: string, target: string, relation: Relation = \"calls\"): EdgeV1 {\n return { source, target, relation, confidence: \"extracted\" };\n}",+ "span": "L51-L53"+ }},{"id": "test/graph-map.test.ts#fileNode",@@ -8768,9 +10367,12 @@"exported": false,"origin": "ast","body_hash": "cb831beea5577f48e8bd82886ecb0467eccc24e399316f742291c59d63d580de",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a file node representation for the graph, encapsulating file metadata for processing.",+ "crux": {+ "code": "function fileNode(path: string): NodeV1 {\n return {\n id: path,\n name: path.slice(path.lastIndexOf(\"/\") + 1),\n kind: \"file\",\n path,\n span: \"L1-L1\",\n signature: null,\n exported: true,\n origin: \"ast\",\n body_hash: `h${counter++}`,\n summary_state: \"pending\",",+ "span": "L16-L27"+ }},{"id": "test/graph-map.test.ts#graphOf",@@ -8782,9 +10384,12 @@"exported": false,"origin": "ast","body_hash": "11c79a80294cef88be10408d30c430dbdc2440d9b80b4611d426503f279261a8",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs a graph structure from nodes and edges, serving as the foundational data for repository mapping.",+ "crux": {+ "code": "function graphOf(nodes: NodeV1[], edges: EdgeV1[]): GraphV1 {\n return {\n meta: { version: 1, nodeCount: nodes.length, edgeCount: edges.length, languages: [] },\n nodes,\n edges,\n };\n}",+ "span": "L55-L61"+ }},{"id": "test/graph-map.test.ts#symNode",@@ -8796,9 +10401,12 @@"exported": false,"origin": "ast","body_hash": "819353898b73f80877d6102fc06f582cec736379220bb864d8be47c3a5107314",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a symbol node representation for the graph, allowing for the inclusion of function or variable symbols with associated metadata.",+ "crux": {+ "code": "function symNode(path: string, name: string, opts: { kind?: Kind; span?: string } = {}): NodeV1 {\n const id = `${path}#${name}`;\n return {\n id,\n name,\n kind: opts.kind ?? \"function\",\n path,\n span: opts.span ?? \"L1-L10\",\n signature: `${name}()`,\n exported: true,\n origin: \"ast\",\n body_hash: `h${counter++}`,",+ "span": "L33-L44"+ }},{"id": "test/graph-resolve-typed.test.ts",@@ -8811,9 +10419,12 @@"origin": "ast","body_hash": "0c3760525cc61ee97de448fa26b4a5b9a3bb07c03b4acfbdf3608541b189cf81","chars": 4908,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test file verifies the resolution of method calls and inheritance in a graph of nodes representing code elements, ensuring correct behavior in various scenarios.",+ "crux": {+ "code": "test(\"typed member call resolves despite global name ambiguity\", () => {\n const edges = resolveEdges(NODES, [\n { source: \"t.py#test_x\", relation: \"calls\", name: \"include_router\", viaMember: true, recvType: \"FastAPI\", file: \"t.py\" },\n ]);\n const call = edges.find((e) => e.relation === \"calls\");\n assert.equal(call?.target, \"app.py#FastAPI.include_router\");\n assert.equal(call?.confidence, \"inferred\");\n});\n\ntest(\"untyped ambiguous member call still drops (regression guard)\", () => {\n const edges = resolveEdges(NODES, [\n { source: \"t.py#test_x\", relation: \"calls\", name: \"include_router\", viaMember: true, file: \"t.py\" },",+ "span": "L18-L29"+ }},{"id": "test/graph-resolve-typed.test.ts#n",@@ -8825,9 +10436,12 @@"exported": false,"origin": "ast","body_hash": "25448bda72366b6bf9233cc1f03e63aa5ef4e1c2253c876b7c2223db09c163fc",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a NodeV1 object representing a code element with its associated metadata, facilitating the construction of a node graph for resolution tests.",+ "crux": {+ "code": " const name = id.includes(\"#\") ? id.split(\"#\")[1].split(\".\").pop()! : id;\n return { id, name, kind, path: id.split(\"#\")[0], span: \"L1-L1\", signature: null,\n exported: true, origin: \"ast\", body_hash: \"h\", summary_state: \"pending\", summary: null, crux: null } as NodeV1;",+ "span": "L7-L9"+ }},{"id": "test/graph-traverse-cli.test.ts",@@ -8840,9 +10454,12 @@"origin": "ast","body_hash": "d79347b0640178631235552105c0518029305ead4990726470d3adf5a1b52f09","chars": 5030,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the CLI commands related to graph traversal, ensuring correct functionality and output for various scenarios.",+ "crux": {+ "code": "test('graft callers: happy path shows header and the caller hit', () => {\n const d = builtRepo();\n const r = runCli(['callers', 'add', d]);\n assert.equal(r.status, 0);\n assert.match(r.stdout, /add · function · src\\/math\\.ts:/);\n assert.match(r.stdout, /calls ← sub \\(src\\/math\\.ts:/);\n});\n\ntest('graft callers --json: shape matches {query, matches:[{symbol,hits}]}', () => {\n const d = builtRepo();\n const r = runCli(['callers', 'add', d, '--json']);\n assert.equal(r.status, 0);",+ "span": "L42-L53"+ }},{"id": "test/graph-traverse-cli.test.ts#builtRepo",@@ -8854,9 +10471,12 @@"exported": false,"origin": "ast","body_hash": "8c3de9f35f0d7a39cf5bd38c0462e92cb65cb762d5285e6cd637ef423631ea43",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sets up a temporary repository with a sample math module for testing CLI commands.",+ "crux": {+ "code": " 'export function add(a: number, b: number): number {\\n return a + b;\\n}\\n' +\n 'export function sub(a: number, b: number): number {\\n return add(a, -b);\\n}\\n' +\n 'export function compute(a: number, b: number): number {\\n return sub(a, b);\\n}\\n',",+ "span": "L21-L23"+ }},{"id": "test/graph-traverse-cli.test.ts#runCli",@@ -8868,9 +10488,12 @@"exported": false,"origin": "ast","body_hash": "3aae0bf33b1d771d8677050168cec54ed0b21cf245a4c04c715f6a520b61a7b0",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes the CLI command with given arguments and captures the output and status code.",+ "crux": {+ "code": " const stdout = execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return { stdout, stderr: '', status: 0 };\n } catch (err) {\n const e = err as { stdout?: string; stderr?: string; status?: number };\n return { stdout: e.stdout ?? '', stderr: e.stderr ?? '', status: e.status ?? 1 };",+ "span": "L31-L38"+ }},{"id": "test/graph-traverse.test.ts",@@ -8883,9 +10506,12 @@"origin": "ast","body_hash": "9683b55f739af4afbb3840cee333eed0b1869494b66fe9cddfae1153df246947","chars": 10972,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Contains tests for graph traversal functionalities, ensuring correct symbol resolution and edge walking behavior.",+ "crux": {+ "code": "test(\"resolveSymbol: bare name match is case-insensitive\", () => {\n const g = baseGraph();\n const matches = resolveSymbol(g, \"RENDER\");\n assert.deepEqual(matches.map((n) => n.id), [\"src/widget.ts#Widget.render\"]);\n});\n\ntest(\"resolveSymbol: qualified Class.method resolves via id suffix\", () => {\n const g = baseGraph();\n const matches = resolveSymbol(g, \"Cache.get\");\n assert.deepEqual(matches.map((n) => n.id), [\"src/cache.ts#Cache.get\"]);\n});\n",+ "span": "L70-L81"+ }},{"id": "test/graph-traverse.test.ts#baseGraph",@@ -8897,9 +10523,12 @@"exported": false,"origin": "ast","body_hash": "6d809e9b571f2f9529bce4e42392b36e09b8bb9050633f2daaa90f202ff47bab",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a base graph fixture used for testing symbol resolution and edge walking.",+ "crux": {+ "code": "function baseGraph(): GraphV1 {\n return graphOf(\n [cacheGet, widgetRender, otherGet, hashFn, fileNode],\n [\n edge(\"src/cache.ts\", \"src/cache.ts#Cache.get\", \"contains\"),\n edge(\"src/cache.ts#Cache.get\", \"src/widget.ts#Widget.render\", \"calls\"),\n edge(\"src/cache.ts#Cache.get\", \"npm:lodash\", \"imports\"),\n ],\n );\n}",+ "span": "L57-L66"+ }},{"id": "test/graph-traverse.test.ts#diamondGraph",@@ -8911,9 +10540,12 @@"exported": false,"origin": "ast","body_hash": "5f778e8292d09729865a06efd50026df15ba7da5a5fb6980e3dd814036db0aca",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs a diamond-shaped graph for testing the impact of nodes based on incoming edges.",+ "crux": {+ "code": "function diamondGraph(): GraphV1 {\n const X = nodeStub({ id: \"X\", name: \"X\" });\n const A = nodeStub({ id: \"A\", name: \"A\" });\n const B = nodeStub({ id: \"B\", name: \"B\" });\n const C = nodeStub({ id: \"C\", name: \"C\" });\n return {\n node: X,\n graph: graphOf(\n [X, A, B, C],\n [edge(\"A\", \"X\", \"calls\"), edge(\"B\", \"X\", \"calls\"), edge(\"C\", \"A\", \"calls\"), edge(\"C\", \"B\", \"calls\")],\n ),\n } as unknown as { node: NodeV1; graph: GraphV1 };",+ "span": "L167-L178"+ }},{"id": "test/graph-traverse.test.ts#edge",@@ -8925,9 +10557,12 @@"exported": false,"origin": "ast","body_hash": "123ba52d4dfdf593b1dd056eb9c949165a0ba7fd06eaf374cf1bf1bd797baee8",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs an edge between two nodes in the graph, defining their relationship type.",+ "crux": {+ "code": "function edge(source: string, target: string, relation: Relation = \"calls\"): EdgeV1 {\n return { source, target, relation, confidence: \"extracted\" };\n}",+ "span": "L32-L34"+ }},{"id": "test/graph-traverse.test.ts#fileAndSymbolGraph",@@ -8939,9 +10574,12 @@"exported": false,"origin": "ast","body_hash": "8d46dcd8a65e23d4490137683c72016c5380080da91bc2cdb643dec3df6a637b",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a graph that includes both file and symbol nodes to test their interactions in dependency resolution.",+ "crux": {+ "code": "function fileAndSymbolGraph() {\n const fileA = nodeStub({ id: \"src/a.ts\", name: \"a.ts\", kind: \"file\", path: \"src/a.ts\" });\n const helper = nodeStub({ id: \"src/a.ts#helper\", name: \"helper\", kind: \"function\", path: \"src/a.ts\" });\n const fileB = nodeStub({ id: \"src/b.ts\", name: \"b.ts\", kind: \"file\", path: \"src/b.ts\" });\n const useB = nodeStub({ id: \"src/b.ts#useB\", name: \"useB\", kind: \"function\", path: \"src/b.ts\" });\n const graph = graphOf(\n [fileA, helper, fileB, useB],\n [edge(\"src/b.ts\", \"src/a.ts\", \"imports\"), edge(\"src/b.ts#useB\", \"src/a.ts#helper\", \"calls\")],\n );\n return { fileA, helper, fileB, useB, graph };\n}",+ "span": "L221-L231"+ }},{"id": "test/graph-traverse.test.ts#graphOf",@@ -8953,9 +10591,12 @@"exported": false,"origin": "ast","body_hash": "3e1c1fd8cd1838095c47e9e0e80c0dac69a49091787a166d61858315c7ee4c63",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a graph structure from an array of nodes and edges, encapsulating metadata about the graph.",+ "crux": {+ "code": "function graphOf(nodes: NodeV1[], edges: EdgeV1[]): GraphV1 {\n return {\n meta: { version: 1, nodeCount: nodes.length, edgeCount: edges.length, languages: [\"ts\"] },\n nodes,\n edges,\n };\n}",+ "span": "L36-L42"+ }},{"id": "test/graph-traverse.test.ts#nodeStub",@@ -8967,9 +10608,12 @@"exported": false,"origin": "ast","body_hash": "7e4a8788936b6b4d198eb93113a428318b00f2276e01fd31d89f8c9cf3f81ccb",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a stub node for testing purposes, encapsulating essential properties of a NodeV1 object.",+ "crux": {+ "code": "function nodeStub(partial: Partial<NodeV1> & { id: string }): NodeV1 {\n return {\n name: partial.id,\n kind: \"function\",\n path: partial.id.split(\"#\")[0],\n span: \"L1-L1\",\n signature: null,\n exported: true,\n origin: \"ast\",\n body_hash: partial.id,\n summary_state: \"pending\",\n summary: null,",+ "span": "L15-L26"+ }},{"id": "test/graph-write.test.ts",@@ -8982,9 +10626,12 @@"origin": "ast","body_hash": "cbbf9c3591519993ec89298444d34732f08eb16f90ba1c1cd33bd39d5512f9ff","chars": 4839,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests to ensure that the `writeGraph` function correctly handles the serialization of graph nodes, specifically that the `body_text` field is omitted when unnecessary, while preserving other fields and the integrity of the original node object.",+ "crux": {+ "code": "test(\"writeGraph strips body_text from the serialized node but keeps every other field\", () => {\n const dir = mkdtempSync(join(tmpdir(), \"graft-write-\"));\n try {\n const node = makeNode({ body_text: \"some searchable definition body\" });\n const graph: GraphV1 = {\n meta: { version: 1, nodeCount: 1, edgeCount: 0, languages: [\"typescript\"] },\n nodes: [node],\n edges: [],\n };\n const path = writeGraph(graph, dir);\n\n const raw = JSON.parse(readFileSync(path, \"utf8\"));",+ "span": "L37-L48"+ }},{"id": "test/graph-write.test.ts#makeNode",@@ -8994,11 +10641,14 @@"span": "L19-L35","signature": "function makeNode(overrides: Partial<NodeV1> = {}): NodeV1","exported": false,- "origin": "ast",- "body_hash": "41ebbf74745569c7f08bdc2d7a852617987e439975ac045b640252aa0684fc7e",- "summary_state": "pending",- "summary": null,- "crux": null+ "origin": "ast",+ "body_hash": "41ebbf74745569c7f08bdc2d7a852617987e439975ac045b640252aa0684fc7e",+ "summary_state": "ready",+ "summary": "Creates a node object with default properties, allowing for optional overrides, to facilitate testing of graph serialization and deserialization.",+ "crux": {+ "code": " return {\n id: \"a.ts#f\",\n name: \"f\",\n kind: \"function\",\n path: \"a.ts\",\n span: \"L1-L3\",\n signature: \"f(): void\",\n exported: true,\n origin: \"ast\",\n body_hash: \"hash\",\n summary_state: \"pending\",\n summary: null,",+ "span": "L20-L31"+ }},{"id": "test/graphrank.test.ts",@@ -9011,9 +10661,12 @@"origin": "ast","body_hash": "9b6450a705fd5bbe7ddead7ae29f87fcb839599d34b6bd0c8ebcb0091ee70c47","chars": 8780,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains unit and integration tests for the personalizedPageRank function, ensuring it correctly ranks nodes based on their connectivity in a graph.",+ "crux": {+ "code": "test(\"PageRank: a seed wired to the cluster outranks an isolated seed\", () => {\n // hub calls a, b, c; lone is a disconnected seed with equal restart weight.\n const g = graphOf(\n [\"hub\", \"a\", \"b\", \"c\", \"lone\"],\n [edge(\"hub\", \"a\"), edge(\"hub\", \"b\"), edge(\"hub\", \"c\")],\n );\n const pr = personalizedPageRank(g, new Map([[\"hub\", 1], [\"lone\", 1]]));\n assert.ok((pr.get(\"hub\") ?? 0) > (pr.get(\"lone\") ?? 0), \"connected seed beats isolated seed\");\n assert.equal([...pr.values()].some((v) => v === 1), true, \"top node normalized to 1\");\n});\n\ntest(\"PageRank: neighbours of a seed accrue mass even with zero restart weight\", () => {",+ "span": "L50-L61"+ }},{"id": "test/graphrank.test.ts#edge",@@ -9025,9 +10678,12 @@"exported": false,"origin": "ast","body_hash": "123ba52d4dfdf593b1dd056eb9c949165a0ba7fd06eaf374cf1bf1bd797baee8",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Defines an edge between two nodes in the graph, establishing a relationship.",+ "crux": {+ "code": "function edge(source: string, target: string, relation: Relation = \"calls\"): EdgeV1 {\n return { source, target, relation, confidence: \"extracted\" };\n}",+ "span": "L39-L41"+ }},{"id": "test/graphrank.test.ts#graphOf",@@ -9039,9 +10695,12 @@"exported": false,"origin": "ast","body_hash": "bf3b5a40bcc1fa81ff40b720adeff034d332bbbb831f3e2f7528e2f667146ce1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs a graph object from given nodes and edges, encapsulating their relationships.",+ "crux": {+ "code": "function graphOf(nodes: string[], edges: EdgeV1[]): GraphV1 {\n return {\n meta: { version: 1, nodeCount: nodes.length, edgeCount: edges.length, languages: [\"ts\"] },\n nodes: nodes.map(node),\n edges,\n };\n}",+ "span": "L42-L48"+ }},{"id": "test/graphrank.test.ts#makeCollisionFixture",@@ -9053,9 +10712,12 @@"exported": false,"origin": "ast","body_hash": "2177edb69c1857665ec38d0fadebf5147cc7c3e71b39d026ee7f33e0c07865f8",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sets up a temporary file structure to simulate a collision scenario for testing graph ranking.",+ "crux": {+ "code": "function makeCollisionFixture(): string {\n const dir = mkdtempSync(join(tmpdir(), \"graft-graphrank-\"));\n writeFileSync(\n join(dir, \"connected.ts\"),\n `export function fooHandler() {\\n helperAlpha();\\n helperBeta();\\n}\\n` +\n `export function helperAlpha() { return 1; }\\n` +\n `export function helperBeta() { return 2; }\\n`,\n );\n writeFileSync(join(dir, \"isolated.ts\"), `export function fooWidget() { return 0; }\\n`);\n return dir;\n}",+ "span": "L128-L138"+ }},{"id": "test/graphrank.test.ts#node",@@ -9067,9 +10729,12 @@"exported": false,"origin": "ast","body_hash": "50c83e997e60e662392960d89cc6c5b421a65cfd8c166084e4c5f3c8ea9a9bd6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a node representation for the graph with specified properties.",+ "crux": {+ "code": "function node(id: string): NodeV1 {\n return {\n id,\n name: id,\n kind: \"function\",\n path: `${id}.ts`,\n span: \"L1-L1\",\n signature: null,\n exported: true,\n origin: \"ast\",\n body_hash: id,\n summary_state: \"pending\",",+ "span": "L23-L34"+ }},{"id": "test/graphrank.test.ts#rank",@@ -9081,9 +10746,12 @@"exported": false,"origin": "ast","body_hash": "5bf6fb6a4dc37b257683b4ab9b24ff4838cf94cd3404123bb383861163c4bbec",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Executes the ask function with specified parameters to retrieve ranked results based on graph connectivity.",+ "crux": {+ "code": "const rank = (dir: string, gr: boolean) =>\n ask(dir, \"foo\", { graphRank: gr }).hits.map((h) => h.title.split(\" ·\")[0]);",+ "span": "L140-L141"+ }},{"id": "test/helpers.ts",@@ -9210,9 +10878,12 @@"origin": "ast","body_hash": "ed49a8a106eeb458ad2dd071071cefae17dd4d0eabd1b74006047feadef9a89a","chars": 3738,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite verifies the behavior of the installCodexHooks function, ensuring it correctly manages hook installations and configurations in various scenarios.",+ "crux": {+ "code": "test('no-op when the CLI home dir is absent', () => {\n assert.deepEqual(installCodexHooks(fresh()), []);\n});\n\ntest('writes shim + hooks.json entry, idempotent on re-run', () => {\n const home = fresh();\n mkdirSync(join(home, '.codex'), { recursive: true });\n const w = installCodexHooks(home);\n assert.equal(w.length, 2);\n const shim = join(home, '.codex', 'hooks', 'graft', 'graft-hooks.cjs');\n assert.ok(existsSync(shim));\n assert.ok(statSync(shim).mode & 0o111, 'shim is executable');",+ "span": "L10-L21"+ }},{"id": "test/hosts-codex-hooks.test.ts#fresh",@@ -9224,8 +10895,8 @@"exported": false,"origin": "ast","body_hash": "c75405ab5617c9e32684bf0530549edf2833d88ee5e6c955308b46c9f4e14c46",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Generates a unique temporary directory for testing purposes.","crux": null},{@@ -9239,9 +10910,12 @@"origin": "ast","body_hash": "56f8988468cb716296b40c939bf58d079015d135fcb3f2c1481e64bce7f67324","chars": 5922,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite verifies the behavior of the runHostsInit function in various scenarios, ensuring it correctly handles host initialization, agent detection, and configuration management.",+ "crux": {+ "code": "test('writes only detected hosts by default', () => {\n const home = fresh(); const repo = fresh();\n mkdirSync(join(home, '.cursor'));\n const r = runHostsInit(repo, { home });\n assert.deepEqual(r.written.map((w) => w.id), ['cursor']);\n const mdc = readFileSync(join(repo, '.cursor', 'rules', 'graft.mdc'), 'utf8');\n assert.match(mdc, /alwaysApply: true/);\n assert.ok(!existsSync(join(repo, 'AGENTS.md')));\n});\n\ntest('explicit agents list overrides detection and flags unknown ids', () => {\n const home = fresh(); const repo = fresh();",+ "span": "L11-L22"+ }},{"id": "test/hosts-init.test.ts#fresh",@@ -9253,8 +10927,8 @@"exported": false,"origin": "ast","body_hash": "9da796af39ee7c44e2c780ded8bc297fc37f854834c5ecdab7819298b3df9cce",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Generates a unique temporary directory for testing purposes to avoid conflicts between test runs.","crux": null},{@@ -9268,9 +10942,12 @@"origin": "ast","body_hash": "37ae3aae1157c1e1eb39ef5670b363d517aaf3028ca8fb56581193b81a83cad7","chars": 1479,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite verifies the structure and content of various instruction bodies to ensure they meet specified formatting and inclusion criteria.",+ "crux": {+ "code": "test('canonical body names the three essentials', () => {\n const b = instructionBody();\n assert.match(b, /^## Graft — repo context graph/m);\n assert.match(b, /graft ask \"/);\n assert.match(b, /graft\\/INDEX\\.md/);\n assert.match(b, /graft build/);\n assert.match(b, /every occurrence|enumerate with grep/i, 'teaches the exhaustive-task grep rule');\n assert.match(b, /callers/, 'teaches the callers/callees/impact commands');\n assert.match(b, /truncated/i, 'tells the agent to follow up on truncated spans');\n assert.match(b, /graft grep/, 'routes sweeps to graft grep');\n assert.match(b, /graft map/, 'tells the agent to orient with graft map before exploring');\n assert.ok(!/\\bhook|statusline\\b/i.test(b), 'no host-specific machinery in the shared body');",+ "span": "L5-L16"+ }},{"id": "test/hosts-mcp-config.test.ts",@@ -9283,9 +10960,12 @@"origin": "ast","body_hash": "5b3ec5afd61079f051d8063f06701ddac608f48b706e72f9ee607e8da673fb06","chars": 3982,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite verifies the behavior of the registerMcpConfigs function in handling various configurations and edge cases.",+ "crux": {+ "code": "test('cursor/gemini/kiro get repo-local JSON entries', () => {\n const repo = fresh(); const home = fresh();\n const w = registerMcpConfigs(repo, ['cursor', 'gemini', 'kiro'], { home });\n assert.deepEqual(w.map((x) => x.action), ['created', 'created', 'created']);\n const cursor = JSON.parse(readFileSync(join(repo, '.cursor', 'mcp.json'), 'utf8'));\n assert.deepEqual(cursor.mcpServers.graft, { command: 'npx', args: ['-y', '@nanonets/graft', 'mcp'] });\n assert.ok(existsSync(join(repo, '.gemini', 'settings.json')));\n assert.ok(existsSync(join(repo, '.kiro', 'settings', 'mcp.json')));\n});\n\ntest('existing config keys are preserved; re-run is unchanged', () => {\n const repo = fresh(); const home = fresh();",+ "span": "L10-L21"+ }},{"id": "test/hosts-mcp-config.test.ts#fresh",@@ -9297,8 +10977,8 @@"exported": false,"origin": "ast","body_hash": "5d57935fd93aed6bacff9481af82c74f353c4928d0c3cf15efbfa038c85dad5a",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Generates a fresh temporary directory for testing purposes.","crux": null},{@@ -9312,9 +10992,12 @@"origin": "ast","body_hash": "6490cbdc54b870d670adf28b5b469e07360a474073b08d692601ef1c4b7ea47e","chars": 1632,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the hosts registry functionality, ensuring that the correct hosts are detected based on the presence of specific directories.",+ "crux": {+ "code": "test('registry exposes the six phase-1 hosts', () => {\n assert.deepEqual(hostIds().sort(), ['agents', 'copilot', 'cursor', 'gemini', 'kiro', 'windsurf']);\n for (const h of HOSTS) {\n assert.ok(h.relPath.length > 0);\n assert.ok(h.content().length > 0);\n }\n});\n\ntest('nothing detected on a bare machine and bare repo', () => {\n assert.deepEqual(detectHosts(probeFor(fresh(), fresh())), []);\n});\n",+ "span": "L17-L28"+ }},{"id": "test/hosts-registry.test.ts#fresh",@@ -9326,8 +11009,8 @@"exported": false,"origin": "ast","body_hash": "4b7e71149dfcf083709a98bd3f04eb92af9a722c7d567dcd4288be6119afc6ea",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Generates a temporary directory for testing purposes, ensuring a clean environment for each test case.","crux": null},{@@ -9340,9 +11023,12 @@"exported": false,"origin": "ast","body_hash": "7653739002fda057d1517f18bfe77dfb0dcf78ab6cb9716ceb7624601eec1f7f",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a probe object that checks for the existence of a directory, facilitating host detection based on the file system state.",+ "crux": {+ "code": " dirExists: (p) => { try { return statSync(p).isDirectory(); } catch { return false; } },\n };",+ "span": "L12-L13"+ }},{"id": "test/hosts-sections.test.ts",@@ -9355,9 +11041,12 @@"origin": "ast","body_hash": "a780abe63074737d40bcd556df06b7b541d2694df75c307daabd280f64f9dba4","chars": 4777,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the upsertSection function, ensuring it correctly creates, appends, replaces, and reports on sections in markdown files.",+ "crux": {+ "code": "test('creates the file with a fenced block when missing', () => {\n const f = join(fresh(), 'AGENTS.md');\n const r = upsertSection(f, '## Graft\\nuse graft ask');\n assert.equal(r.action, 'created');\n const text = readFileSync(f, 'utf8');\n assert.ok(text.includes('<!-- graft:start -->'));\n assert.ok(text.includes('use graft ask'));\n assert.ok(text.endsWith('\\n'));\n});\n\ntest('appends after existing content, separated by a blank line', () => {\n const f = join(fresh(), 'AGENTS.md');",+ "span": "L10-L21"+ }},{"id": "test/hosts-sections.test.ts#fresh",@@ -9369,10 +11058,162 @@"exported": false,"origin": "ast","body_hash": "5fbf8aed98c1fd26d88217061c491d534e161b32a06df5c80d376de4eb1171a3",- "summary_state": "pending",- "summary": null,+ "summary_state": "ready",+ "summary": "Generates a fresh temporary directory for testing purposes.",+ "crux": null+ },+ {+ "id": "test/llm-adapters.test.ts",+ "name": "llm-adapters.test.ts",+ "kind": "file",+ "path": "test/llm-adapters.test.ts",+ "span": "L1-L216",+ "signature": null,+ "exported": true,+ "origin": "ast",+ "body_hash": "53081583f9a2ef8a7f925fcce6554201fb8a10184ac835f3879cb3f04700f346",+ "chars": 8829,+ "summary_state": "ready",+ "summary": "This file contains tests for network-free adapters that simulate interactions with OpenAI and Anthropic SDKs, ensuring correct request handling and response formatting.",+ "crux": {+ "code": "test(\"openai: plain text — system/user map to strings, usage is uncached-only\", async () => {\n const { client, box } = fakeOpenAI(openAiResp());\n const m = new OpenAIChatModel({ apiKey: \"x\", model: \"gpt-x\", client });\n const res = await m.create({\n messages: [\n { role: \"system\", content: \"sys\" },\n { role: \"user\", content: \"hi\" },\n ],\n temperature: 0,\n });\n assert.equal(box.params.model, \"gpt-x\");\n assert.equal(box.params.messages[0].content, \"sys\"); // plain string, no cache parts",+ "span": "L33-L44"+ }+ },+ {+ "id": "test/llm-adapters.test.ts#anthropicResp",+ "name": "anthropicResp",+ "kind": "function",+ "path": "test/llm-adapters.test.ts",+ "span": "L127-L134",+ "signature": "function anthropicResp(over: Partial<any> = {}): any",+ "exported": false,+ "origin": "ast",+ "body_hash": "510e5ddfab3f4b864398e600e0a6a9e786c164cb2ca583e48fa5eb617305e366",+ "summary_state": "ready",+ "summary": "Generates a mock response structure for Anthropic API calls, aiding in the testing of response processing.",+ "crux": {+ "code": " content: [{ type: \"text\", text: \"hi there\" }],\n stop_reason: \"end_turn\",\n usage: { input_tokens: 70, output_tokens: 20, cache_read_input_tokens: 30, cache_creation_input_tokens: 5 },\n ...over,",+ "span": "L129-L132"+ }+ },+ {+ "id": "test/llm-adapters.test.ts#fakeAnthropic",+ "name": "fakeAnthropic",+ "kind": "function",+ "path": "test/llm-adapters.test.ts",+ "span": "L119-L125",+ "signature": "function fakeAnthropic(resp: unknown)",+ "exported": false,+ "origin": "ast",+ "body_hash": "389c2181f2f3596989f46febc959ccdb5daf6c8faf71d739e0e6341c49faa323",+ "summary_state": "ready",+ "summary": "Creates a mock Anthropic client for testing purposes, enabling verification of the parameters it receives.",+ "crux": {+ "code": " messages: { create: async (params: any) => ((box.params = params), resp) },\n } as unknown as Anthropic;",+ "span": "L122-L123"+ }+ },+ {+ "id": "test/llm-adapters.test.ts#fakeOpenAI",+ "name": "fakeOpenAI",+ "kind": "function",+ "path": "test/llm-adapters.test.ts",+ "span": "L17-L23",+ "signature": "function fakeOpenAI(resp: unknown)",+ "exported": false,+ "origin": "ast",+ "body_hash": "1df77ef154b74d8a146666026f8598c84891a3fad31a785932884d867b7348a8",+ "summary_state": "ready",+ "summary": "Creates a mock OpenAI client for testing purposes, allowing assertions on the parameters sent to it.",+ "crux": {+ "code": " chat: { completions: { create: async (params: any) => ((box.params = params), resp) } },\n } as unknown as OpenAI;",+ "span": "L20-L21"+ }+ },+ {+ "id": "test/llm-adapters.test.ts#openAiResp",+ "name": "openAiResp",+ "kind": "function",+ "path": "test/llm-adapters.test.ts",+ "span": "L25-L31",+ "signature": "function openAiResp(over: Partial<any> = {}): any",+ "exported": false,+ "origin": "ast",+ "body_hash": "97c63c00348e9d80c2ddccf50e21e28de7379123cdc570757b21857c67364268",+ "summary_state": "ready",+ "summary": "Generates a mock response structure for OpenAI API calls, facilitating the testing of response handling.",+ "crux": {+ "code": " choices: [{ message: { content: \"hello\", tool_calls: [] }, finish_reason: \"stop\" }],\n usage: { prompt_tokens: 100, completion_tokens: 20, prompt_tokens_details: { cached_tokens: 30 } },\n ...over,\n };",+ "span": "L27-L30"+ }+ },+ {+ "id": "test/llm-ops.test.ts",+ "name": "llm-ops.test.ts",+ "kind": "file",+ "path": "test/llm-ops.test.ts",+ "span": "L1-L82",+ "signature": null,+ "exported": true,+ "origin": "ast",+ "body_hash": "ef3ba575506602feeb3048a6bded8bd2a92e9a59054c569352e82d1a847b80af",+ "chars": 3303,+ "summary_state": "ready",+ "summary": "Tests the behavior of three engine operations (summarize, synthesize, crux) using a fake transport to ensure they build the correct requests and handle responses appropriately.",+ "crux": {+ "code": "test(\"ChatSummarizer sends plain text and returns trimmed content\", async () => {\n const m = new FakeChatModel({ text: \" a prose summary \" });\n const out = await new ChatSummarizer(m).summarize(\"code\", { path: \"a.ts\" });\n assert.equal(out, \"a prose summary\");\n assert.equal(m.last?.responseFormat, undefined); // plain text\n assert.equal(m.last?.messages[0].role, \"system\");\n});\n\ntest(\"ChatSynthesizer forces record_graph and cleans parsed args\", async () => {\n const m = new FakeChatModel({\n toolCalls: [\n {",+ "span": "L31-L42"+ }+ },+ {+ "id": "test/llm-ops.test.ts#FakeChatModel",+ "name": "FakeChatModel",+ "kind": "class",+ "path": "test/llm-ops.test.ts",+ "span": "L15-L29",+ "signature": "class FakeChatModel implements ChatModel",+ "exported": false,+ "origin": "ast",+ "body_hash": "eda253622c2c5165804dbff88e4833ec0cfd0f45f9326916108aae84f2932905",+ "summary_state": "ready",+ "summary": "Simulates a chat model to test the behavior of chat operations without network dependency.",+ "crux": {+ "code": " this.last = req;\n return {\n text: this.reply.text ?? \"\",\n toolCalls: this.reply.toolCalls ?? [],\n usage: { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 },\n stopReason: \"stop\",\n assistant: { role: \"assistant\", content: this.reply.text ?? \"\" },\n };",+ "span": "L20-L27"+ }+ },+ {+ "id": "test/llm-ops.test.ts#FakeChatModel.constructor",+ "name": "constructor",+ "kind": "method",+ "path": "test/llm-ops.test.ts",+ "span": "L18-L18",+ "signature": "constructor(private reply: { text?: string; toolCalls?: ToolCall[] })",+ "exported": false,+ "origin": "ast",+ "body_hash": "edce87b8798c8e867446b2b7970f4c97f1f8eba762255e690daea9453d10e630",+ "summary_state": "ready",+ "summary": "Initializes the fake chat model with a predefined reply for testing purposes.","crux": null},+ {+ "id": "test/llm-ops.test.ts#FakeChatModel.create",+ "name": "create",+ "kind": "method",+ "path": "test/llm-ops.test.ts",+ "span": "L19-L28",+ "signature": "async create(req: ChatRequest): Promise<ChatResponse>",+ "exported": false,+ "origin": "ast",+ "body_hash": "e90179ccabec3472e4184b3a1147383e87c3de3f42b8757304dbb33b36547488",+ "summary_state": "ready",+ "summary": "Processes a chat request and returns a simulated chat response based on predefined data.",+ "crux": {+ "code": " this.last = req;\n return {\n text: this.reply.text ?? \"\",\n toolCalls: this.reply.toolCalls ?? [],\n usage: { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 },\n stopReason: \"stop\",\n assistant: { role: \"assistant\", content: this.reply.text ?? \"\" },\n };",+ "span": "L20-L27"+ }+ },{"id": "test/mcp-server.test.ts","name": "mcp-server.test.ts",@@ -9384,9 +11225,12 @@"origin": "ast","body_hash": "4d828181f0a8c645f00097ab43c2bdcf5bc65da276e83b7503bc2888ae09f254","chars": 2604,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This file contains tests for the RPC functionality of the MCP server, ensuring that various methods return expected results and handle errors correctly.",+ "crux": {+ "code": "test('initialize → tools/list → tools/call round-trip', async () => {\n const dir = mkdtempSync(join(tmpdir(), 'graft-mcpsrv-'));\n const rs = await rpc(\n [\n { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 't', version: '0' } } },\n { jsonrpc: '2.0', method: 'notifications/initialized' },\n { jsonrpc: '2.0', id: 2, method: 'tools/list' },\n { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'graft_blast_radius', arguments: { file: 'x.ts' } } },\n ],\n dir,\n 3,\n );",+ "span": "L30-L41"+ }},{"id": "test/mcp-server.test.ts#rpc",@@ -9398,9 +11242,12 @@"exported": false,"origin": "ast","body_hash": "a83e1cfe6b7af8f6c87c6c9756d4ca8d61c0122c956f24b5b80a2249b2e950b1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "The rpc function facilitates communication with the MCP server by sending messages and collecting responses, handling asynchronous interactions effectively.",+ "crux": {+ "code": " for (const m of messages) child.stdin.write(`${JSON.stringify(m)}\\n`);\n const deadline = Date.now() + 15000;\n while (responses.length < expected && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));\n child.kill();\n await once(child, 'exit').catch(() => {});\n return responses;",+ "span": "L22-L27"+ }},{"id": "test/mcp-tools.test.ts",@@ -9413,9 +11260,12 @@"origin": "ast","body_hash": "22d3a32a85a0ba1542969786e8bda07d3df02ee068554d4070f705d30d7239dc","chars": 12646,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "This test suite validates the functionality of various tools in the MCP codebase, ensuring they operate correctly on built repositories and handle errors appropriately.",+ "crux": {+ "code": "test('TOOLS lists all eight tools with schemas', () => {\n assert.deepEqual(TOOLS.map((t) => t.name), [\n 'graft_ask',\n 'graft_skeleton',\n 'graft_check',\n 'graft_blast_radius',\n 'graft_callers',\n 'graft_callees',\n 'graft_grep',\n 'graft_map',\n ]);\n for (const t of TOOLS) {",+ "span": "L75-L86"+ }},{"id": "test/mcp-tools.test.ts#builtRepo",@@ -9427,9 +11277,12 @@"exported": false,"origin": "ast","body_hash": "2e8d1ef9e31662a9e1a2e64630378d64979be157310df30d3e97900015426178",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a temporary repository structure for testing the tools with a basic math implementation.",+ "crux": {+ "code": " const d = mkdtempSync(join(tmpdir(), 'graft-mcptools-'));\n mkdirSync(join(d, 'src'), { recursive: true });\n writeFileSync(join(d, 'src', 'math.ts'),\n 'export function add(a: number, b: number): number {\\n return a + b;\\n}\\nexport function sub(a: number, b: number): number {\\n return add(a, -b);\\n}\\n');\n execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'build', d], { stdio: 'pipe' });",+ "span": "L10-L14"+ }},{"id": "test/mcp-tools.test.ts#chainRepo",@@ -9441,9 +11294,12 @@"exported": false,"origin": "ast","body_hash": "15d62ff8440102dce21a2647a706a4307c540acecc930810e29307b72defe3b6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sets up a repository with a three-deep function call structure to test depth-related functionality in tools.",+ "crux": {+ "code": " 'export function compute(a: number, b: number): number {\\n return sub(a, b);\\n}\\n',",+ "span": "L29-L29"+ }},{"id": "test/mcp-tools.test.ts#customDirRepo",@@ -9455,9 +11311,12 @@"exported": false,"origin": "ast","body_hash": "def8983a39f4cc761bf0d89b5f58bb41eff230621ebb4894b7f9007c75af1227",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Establishes a repository in a custom directory to validate the handling of non-default graph locations.",+ "crux": {+ "code": " execFileSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'build', d, '--dir', graphDir], { stdio: 'pipe' });",+ "span": "L43-L43"+ }},{"id": "test/mcp-tools.test.ts#fileScopeRepo",@@ -9469,9 +11328,12 @@"exported": false,"origin": "ast","body_hash": "c3e730fb2a68c37167f29ebcf6a14eab2650fde246b3b2fd611cf96b58c55cbd",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a repository to test the interaction between file imports and function calls across files.",+ "crux": {+ "code": " writeFileSync(join(d, 'src', 'a.ts'), 'export function helper(): number {\\n return 42;\\n}\\n');\n writeFileSync(\n join(d, 'src', 'b.ts'),",+ "span": "L53-L55"+ }},{"id": "test/mcp-tools.test.ts#multiDirRepo",@@ -9483,9 +11345,12 @@"exported": false,"origin": "ast","body_hash": "1ba610952a7f039e9715046c0e81e62fb5a0fcb2bb3d62e5435321252679a0bf",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Generates a repository with multiple directories to test the handling of directory limits in tool operations.",+ "crux": {+ "code": " writeFileSync(join(d, dir, 'x.ts'), `export function ${dir}Fn(): number {\\n return 1;\\n}\\n`);\n }",+ "span": "L69-L70"+ }},{"id": "test/search-grep.test.ts",@@ -9498,9 +11363,12 @@"origin": "ast","body_hash": "a23b17c1a455374c4b4172834c51bb6c5e5ed5abbc891df16ee7cb4aeae9b5c0","chars": 9704,- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Contains core tests for the `graft grep` functionality, ensuring accurate symbol attribution and search results in a parsed graph.",+ "crux": {+ "code": "test('WALK_RELATIONS (shared, src/graph/relations.ts): exactly the five dependency relations', () => {\n assert.deepEqual(\n [...WALK_RELATIONS].sort(),\n ['calls', 'extends', 'implements', 'imports', 'references'].sort(),\n );\n // Excluded on purpose: contains is structural (file->symbol), not dependency wiring.\n assert.equal(WALK_RELATIONS.has('contains' as never), false);\n});\n\ntest('grepGraph: groups are ordered by inDegree desc, then path asc', () => {\n const repo = needleRepo();\n const graph = loadBuiltGraph(repo);",+ "span": "L93-L104"+ }},{"id": "test/search-grep.test.ts#fileNode",@@ -9512,9 +11380,12 @@"exported": false,"origin": "ast","body_hash": "a97b45c7d03f4c753851a32b055aa77614f568140588edcbea2757291188a02e",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Creates a file node representation for a given path and number of lines, facilitating graph construction.",+ "crux": {+ "code": "function fileNode(path: string, lines: number): NodeV1 {\n return {\n id: path,\n name: path,\n kind: 'file',\n path,\n span: `L1-L${lines}`,\n signature: null,\n exported: true,\n origin: 'ast',\n body_hash: '',\n summary_state: 'pending',",+ "span": "L24-L35"+ }},{"id": "test/search-grep.test.ts#graphOf",@@ -9526,9 +11397,12 @@"exported": false,"origin": "ast","body_hash": "14ab0ac438fbede56f702c479b6f7fc1bc8d146c4b36242dab7d25fbcb8cf5c6",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Constructs a graph representation from nodes and edges, encapsulating metadata about the graph structure.",+ "crux": {+ "code": "function graphOf(nodes: NodeV1[], edges: GraphV1['edges'] = []): GraphV1 {\n return { meta: { version: 1, nodeCount: nodes.length, edgeCount: edges.length, languages: [] }, nodes, edges };\n}",+ "span": "L41-L43"+ }},{"id": "test/search-grep.test.ts#loadBuiltGraph",@@ -9540,9 +11414,12 @@"exported": false,"origin": "ast","body_hash": "39d7dbe4e44d4a83bb1b4d13836e4b230a8c709a09e7ff116b77190a82eb16c1",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Loads a built graph from a specified repository, ensuring the graph is correctly constructed for testing.",+ "crux": {+ "code": "function loadBuiltGraph(repo: string): GraphV1 {\n const g = readGraph(wiringPath(join(repo, 'graft')));\n assert.ok(g, 'expected a built graph.json');\n return g!;\n}",+ "span": "L87-L91"+ }},{"id": "test/search-grep.test.ts#needleRepo",@@ -9554,9 +11431,12 @@"exported": false,"origin": "ast","body_hash": "ddbfa733e3076db220939ab5efd2ec90a8250b54170f03bb9d23c28751467b01",- "summary_state": "pending",- "summary": null,- "crux": null+ "summary_state": "ready",+ "summary": "Sets up a temporary repository with TypeScript files to test the grep functionality, simulating real-world usage scenarios.",+ "crux": {+ "code": "function needleRepo(): string {\n const d = mkdtempSync(join(tmpdir(), 'graft-grep-'));\n mkdirSync(join(d, 'src'), { recursive: true });\n writeFileSync(\n join(d, 'src', 'a.ts'),\n [\n 'export function heavilyCalled(): void {',\n ' console.log(\"NEEDLE hit in heavilyCalled\");',\n '}',\n '',\n 'export function rarelyCalled(): void {',\n ' console.log(\"NEEDLE hit in rarelyCalled\");',",+ "span": "L50-L61"+ }},{"id": "test/viz-assemble.test.ts",@@ -10726,7 +12606,7 @@},{"source": "bench/agent.ts",- "target": "openai",+ "target": "src/ai/llm/types.ts","relation": "imports","confidence": "extracted"},@@ -10774,7 +12654,7 @@},{"source": "bench/agent.ts#runAgent",- "target": "bench/llm.ts#makeClient",+ "target": "bench/llm.ts#makeChatModel","relation": "calls","confidence": "inferred"},@@ -10858,7 +12738,7 @@},{"source": "bench/judge.ts",- "target": "openai",+ "target": "src/ai/llm/types.ts","relation": "imports","confidence": "extracted"},@@ -10870,22 +12750,46 @@},{"source": "bench/judge.ts#judge",- "target": "bench/llm.ts#makeClient",+ "target": "bench/llm.ts#makeChatModel","relation": "calls","confidence": "inferred"},{"source": "bench/llm.ts",- "target": "bench/llm.ts#makeClient",+ "target": "bench/llm.ts#makeChatModel","relation": "contains","confidence": "extracted"},{"source": "bench/llm.ts",- "target": "openai",+ "target": "src/ai/llm/factory.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "bench/llm.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "bench/llm.ts",+ "target": "src/ai/providers.ts","relation": "imports","confidence": "extracted"},+ {+ "source": "bench/llm.ts#makeChatModel",+ "target": "src/ai/llm/factory.ts#createChatModel",+ "relation": "calls",+ "confidence": "inferred"+ },+ {+ "source": "bench/llm.ts#makeChatModel",+ "target": "src/ai/providers.ts#resolveConfig",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "bench/report.ts","target": "bench/report.ts#aggregate",@@ -11096,6 +13000,12 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "bench/run.ts",+ "target": "src/ai/providers.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "bench/run.ts","target": "src/ask/ask.ts",@@ -11116,7 +13026,7 @@},{"source": "bench/run.ts#main",- "target": "bench/llm.ts#makeClient",+ "target": "bench/llm.ts#makeChatModel","relation": "calls","confidence": "inferred"},@@ -11138,6 +13048,12 @@"relation": "calls","confidence": "extracted"},+ {+ "source": "bench/run.ts#main",+ "target": "src/ai/providers.ts#resolveConfig",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "bench/run.ts#main","target": "src/ask/ask.ts#ask",@@ -11176,7 +13092,7 @@},{"source": "bench/selfcheck.ts",- "target": "bench/selfcheck.ts#makeStubClient",+ "target": "bench/selfcheck.ts#makeStubModel","relation": "contains","confidence": "extracted"},@@ -11222,6 +13138,12 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "bench/selfcheck.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "bench/selfcheck.ts#main","target": "bench/judge.ts#judge",@@ -11236,10 +13158,16 @@},{"source": "bench/selfcheck.ts#main",- "target": "bench/selfcheck.ts#makeStubClient",+ "target": "bench/selfcheck.ts#makeStubModel","relation": "calls","confidence": "extracted"},+ {+ "source": "bench/selfcheck.ts#makeStubModel",+ "target": "bench/selfcheck.ts#makeStubModel.create",+ "relation": "contains",+ "confidence": "extracted"+ },{"source": "bench/tasks.ts","target": "bench/tasks.ts#repoPath",@@ -11276,6 +13204,12 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "bench/token-ab.ts",+ "target": "bench/llm.ts#makeChatModel",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "bench/token-ab.ts","target": "bench/token-ab.ts#main",@@ -11330,6 +13264,12 @@"relation": "contains","confidence": "extracted"},+ {+ "source": "bench/token-ab.ts",+ "target": "bench/llm.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "bench/token-ab.ts","target": "dotenv/config",@@ -11356,7 +13296,7 @@},{"source": "bench/token-ab.ts",- "target": "openai",+ "target": "src/ai/llm/types.ts","relation": "imports","confidence": "extracted"},@@ -11434,112 +13374,424 @@},{"source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#ChatCruxSummarizer",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#CruxSummarizer",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#FileCruxInput",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#NodeCrux",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#NodeRef",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#numberLines",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#parseResults",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/crux.ts#userContent",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts",+ "target": "src/graph/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#ChatCruxSummarizer",+ "target": "src/ai/crux.ts#ChatCruxSummarizer.constructor",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#ChatCruxSummarizer",+ "target": "src/ai/crux.ts#ChatCruxSummarizer.describeFile",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#ChatCruxSummarizer","target": "src/ai/crux.ts#CruxSummarizer",+ "relation": "implements",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#ChatCruxSummarizer.describeFile",+ "target": "src/ai/crux.ts#parseResults",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#ChatCruxSummarizer.describeFile",+ "target": "src/ai/crux.ts#userContent",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#parseResults",+ "target": "src/ai/crux.ts#parseResults.num",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#parseResults",+ "target": "src/ai/crux.ts#parseResults.num",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/crux.ts#userContent",+ "target": "src/ai/crux.ts#numberLines",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModelOptions",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "src/ai/llm/anthropic.ts#CacheControl",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "src/ai/llm/anthropic.ts#cc",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "src/ai/llm/anthropic.ts#normalizeUsage",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "src/ai/llm/anthropic.ts#toAnthropicTool",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "@anthropic-ai/sdk",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.assistantParam",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.constructor",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.fromResponse",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel",+ "target": "src/ai/llm/types.ts#ChatModel",+ "relation": "implements",+ "confidence": "inferred"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.assistantParam",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.fromResponse",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "target": "src/ai/llm/anthropic.ts#cc",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/anthropic.ts#AnthropicChatModel.fromResponse",+ "target": "src/ai/llm/anthropic.ts#normalizeUsage",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/factory.ts",+ "target": "src/ai/llm/factory.ts#ChatModelConfig",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/factory.ts",+ "target": "src/ai/llm/factory.ts#createChatModel",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/factory.ts",+ "target": "src/ai/llm/factory.ts#ProviderKind",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/factory.ts",+ "target": "src/ai/llm/anthropic.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/factory.ts",+ "target": "src/ai/llm/openai.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/factory.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#ChatMessage","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/ai/crux.ts#FileCruxInput",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#ChatParams","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/ai/crux.ts#NodeCrux",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#normalizeUsage","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/ai/crux.ts#NodeRef",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/ai/crux.ts#numberLines",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#OpenAIChatModelOptions","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/ai/crux.ts#OpenRouterCruxSummarizer",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#textPart","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/ai/crux.ts#parseResults",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#toChatMessage","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/ai/crux.ts#userContent",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/openai.ts#toChatTool","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts",+ "source": "src/ai/llm/openai.ts","target": "openai","relation": "imports","confidence": "extracted"},{- "source": "src/ai/crux.ts",- "target": "src/graph/types.ts",+ "source": "src/ai/llm/openai.ts",+ "target": "src/ai/llm/types.ts","relation": "imports","confidence": "extracted"},{- "source": "src/ai/crux.ts#OpenRouterCruxSummarizer",- "target": "src/ai/crux.ts#OpenRouterCruxSummarizer.constructor",+ "source": "src/ai/llm/openai.ts#OpenAIChatModel",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.constructor","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts#OpenRouterCruxSummarizer",- "target": "src/ai/crux.ts#OpenRouterCruxSummarizer.describeFile",+ "source": "src/ai/llm/openai.ts#OpenAIChatModel",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.create","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts#OpenRouterCruxSummarizer",- "target": "src/ai/crux.ts#CruxSummarizer",+ "source": "src/ai/llm/openai.ts#OpenAIChatModel",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/openai.ts#OpenAIChatModel",+ "target": "src/ai/llm/types.ts#ChatModel","relation": "implements",+ "confidence": "inferred"+ },+ {+ "source": "src/ai/llm/openai.ts#OpenAIChatModel.create",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.create",+ "relation": "calls","confidence": "extracted"},{- "source": "src/ai/crux.ts#OpenRouterCruxSummarizer.describeFile",- "target": "src/ai/crux.ts#parseResults",+ "source": "src/ai/llm/openai.ts#OpenAIChatModel.create",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse","relation": "calls","confidence": "extracted"},{- "source": "src/ai/crux.ts#OpenRouterCruxSummarizer.describeFile",- "target": "src/ai/crux.ts#userContent",+ "source": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse",+ "target": "src/ai/llm/openai.ts#normalizeUsage","relation": "calls","confidence": "extracted"},{- "source": "src/ai/crux.ts#parseResults",- "target": "src/ai/crux.ts#parseResults.num",+ "source": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse.parse","relation": "calls","confidence": "extracted"},{- "source": "src/ai/crux.ts#parseResults",- "target": "src/ai/crux.ts#parseResults.num",+ "source": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse.parse","relation": "contains","confidence": "extracted"},{- "source": "src/ai/crux.ts#userContent",- "target": "src/ai/crux.ts#numberLines",+ "source": "src/ai/llm/openai.ts#toChatMessage",+ "target": "src/ai/llm/openai.ts#textPart","relation": "calls","confidence": "extracted"},+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#ChatModel",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#ChatRequest",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#ChatResponse",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#Message",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#ResponseFormat",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#ToolCall",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#ToolSpec",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/llm/types.ts",+ "target": "src/ai/llm/types.ts#Usage",+ "relation": "contains",+ "confidence": "extracted"+ },{"source": "src/ai/providers.ts","target": "src/ai/providers.ts#EngineConfig",@@ -11558,6 +13810,24 @@"relation": "contains","confidence": "extracted"},+ {+ "source": "src/ai/providers.ts",+ "target": "src/ai/crux.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/providers.ts",+ "target": "src/ai/llm/factory.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/ai/providers.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "src/ai/providers.ts","target": "src/ai/summarize.ts",@@ -11572,7 +13842,7 @@},{"source": "src/ai/summarize.ts",- "target": "src/ai/summarize.ts#OpenRouterSummarizer",+ "target": "src/ai/summarize.ts#ChatSummarizer","relation": "contains","confidence": "extracted"},@@ -11590,49 +13860,49 @@},{"source": "src/ai/summarize.ts",- "target": "openai",+ "target": "src/ai/llm/types.ts","relation": "imports","confidence": "extracted"},{- "source": "src/ai/summarize.ts#OpenRouterSummarizer",- "target": "src/ai/summarize.ts#OpenRouterSummarizer.constructor",+ "source": "src/ai/summarize.ts#ChatSummarizer",+ "target": "src/ai/summarize.ts#ChatSummarizer.constructor","relation": "contains","confidence": "extracted"},{- "source": "src/ai/summarize.ts#OpenRouterSummarizer",- "target": "src/ai/summarize.ts#OpenRouterSummarizer.summarize",+ "source": "src/ai/summarize.ts#ChatSummarizer",+ "target": "src/ai/summarize.ts#ChatSummarizer.summarize","relation": "contains","confidence": "extracted"},{- "source": "src/ai/summarize.ts#OpenRouterSummarizer",+ "source": "src/ai/summarize.ts#ChatSummarizer","target": "src/ai/summarize.ts#Summarizer","relation": "implements","confidence": "extracted"},{- "source": "src/ai/summarize.ts#OpenRouterSummarizer.summarize",+ "source": "src/ai/summarize.ts#ChatSummarizer.summarize","target": "src/ai/summarize.ts#userContent","relation": "calls","confidence": "extracted"},{"source": "src/ai/synthesize.ts",- "target": "src/ai/synthesize.ts#clean",+ "target": "src/ai/synthesize.ts#ChatSynthesizer","relation": "contains","confidence": "extracted"},{"source": "src/ai/synthesize.ts",- "target": "src/ai/synthesize.ts#FileSummary",+ "target": "src/ai/synthesize.ts#clean","relation": "contains","confidence": "extracted"},{"source": "src/ai/synthesize.ts",- "target": "src/ai/synthesize.ts#OpenRouterSynthesizer",+ "target": "src/ai/synthesize.ts#FileSummary","relation": "contains","confidence": "extracted"},@@ -11662,36 +13932,36 @@},{"source": "src/ai/synthesize.ts",- "target": "openai",+ "target": "src/ai/llm/types.ts","relation": "imports","confidence": "extracted"},{- "source": "src/ai/synthesize.ts#OpenRouterSynthesizer",- "target": "src/ai/synthesize.ts#OpenRouterSynthesizer.constructor",+ "source": "src/ai/synthesize.ts#ChatSynthesizer",+ "target": "src/ai/synthesize.ts#ChatSynthesizer.constructor","relation": "contains","confidence": "extracted"},{- "source": "src/ai/synthesize.ts#OpenRouterSynthesizer",- "target": "src/ai/synthesize.ts#OpenRouterSynthesizer.synthesize",+ "source": "src/ai/synthesize.ts#ChatSynthesizer",+ "target": "src/ai/synthesize.ts#ChatSynthesizer.synthesize","relation": "contains","confidence": "extracted"},{- "source": "src/ai/synthesize.ts#OpenRouterSynthesizer",+ "source": "src/ai/synthesize.ts#ChatSynthesizer","target": "src/ai/synthesize.ts#Synthesizer","relation": "implements","confidence": "extracted"},{- "source": "src/ai/synthesize.ts#OpenRouterSynthesizer.synthesize",+ "source": "src/ai/synthesize.ts#ChatSynthesizer.synthesize","target": "src/ai/synthesize.ts#clean","relation": "calls","confidence": "extracted"},{- "source": "src/ai/synthesize.ts#OpenRouterSynthesizer.synthesize",+ "source": "src/ai/synthesize.ts#ChatSynthesizer.synthesize","target": "src/ai/synthesize.ts#userContent","relation": "calls","confidence": "extracted"@@ -13574,6 +15844,12 @@"relation": "calls","confidence": "inferred"},+ {+ "source": "src/cli.ts",+ "target": "src/cli.ts#cliConfig",+ "relation": "calls",+ "confidence": "extracted"+ },{"source": "src/cli.ts","target": "src/cli.ts#engineFrom",@@ -13688,6 +15964,12 @@"relation": "calls","confidence": "inferred"},+ {+ "source": "src/cli.ts",+ "target": "src/cli.ts#cliConfig",+ "relation": "contains",+ "confidence": "extracted"+ },{"source": "src/cli.ts","target": "src/cli.ts#engineFrom",@@ -13700,6 +15982,12 @@"relation": "contains","confidence": "extracted"},+ {+ "source": "src/cli.ts",+ "target": "src/cli.ts#GlobalOpts",+ "relation": "contains",+ "confidence": "extracted"+ },{"source": "src/cli.ts","target": "src/cli.ts#traverseAction",@@ -13730,6 +16018,12 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "src/cli.ts",+ "target": "src/ai/llm/factory.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "src/cli.ts","target": "src/ai/providers.ts",@@ -13796,6 +16090,12 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "src/cli.ts#engineFrom",+ "target": "src/cli.ts#cliConfig",+ "relation": "calls",+ "confidence": "extracted"+ },{"source": "src/cli.ts#traverseAction","target": "src/graph/traverse-cli.ts#runTraverseCommand",@@ -14378,6 +16678,18 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "src/engine.ts",+ "target": "src/ai/llm/factory.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "src/engine.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },{"source": "src/engine.ts","target": "src/ai/providers.ts",@@ -14432,6 +16744,12 @@"relation": "contains","confidence": "extracted"},+ {+ "source": "src/engine.ts#Graft",+ "target": "src/engine.ts#Graft.chatModel",+ "relation": "contains",+ "confidence": "extracted"+ },{"source": "src/engine.ts#Graft","target": "src/engine.ts#Graft.check",@@ -14474,12 +16792,6 @@"relation": "contains","confidence": "extracted"},- {- "source": "src/engine.ts#Graft",- "target": "src/engine.ts#Graft.requireKey",- "relation": "contains",- "confidence": "extracted"- },{"source": "src/engine.ts#Graft","target": "src/engine.ts#Graft.summarizer",@@ -14498,6 +16810,12 @@"relation": "calls","confidence": "inferred"},+ {+ "source": "src/engine.ts#Graft.chatModel",+ "target": "src/ai/llm/factory.ts#createChatModel",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "src/engine.ts#Graft.check","target": "src/context/check.ts#checkContext",@@ -14518,7 +16836,7 @@},{"source": "src/engine.ts#Graft.cruxSummarizer",- "target": "src/engine.ts#Graft.requireKey",+ "target": "src/engine.ts#Graft.chatModel","relation": "calls","confidence": "extracted"},@@ -14560,13 +16878,13 @@},{"source": "src/engine.ts#Graft.summarizer",- "target": "src/engine.ts#Graft.requireKey",+ "target": "src/engine.ts#Graft.chatModel","relation": "calls","confidence": "extracted"},{"source": "src/engine.ts#Graft.synthesizer",- "target": "src/engine.ts#Graft.requireKey",+ "target": "src/engine.ts#Graft.chatModel","relation": "calls","confidence": "extracted"},@@ -15394,7 +17712,7 @@},{"source": "src/graph/enrich.ts#collectFileCrux",- "target": "src/ai/crux.ts#OpenRouterCruxSummarizer.describeFile",+ "target": "src/ai/crux.ts#ChatCruxSummarizer.describeFile","relation": "calls","confidence": "inferred"},@@ -15830,6 +18148,12 @@"relation": "calls","confidence": "extracted"},+ {+ "source": "src/graph/load.ts#loadCached",+ "target": "src/ai/llm/openai.ts#OpenAIChatModel.fromResponse.parse",+ "relation": "calls",+ "confidence": "inferred"+ },{"source": "src/graph/load.ts#loadCached","target": "src/graph/bindings.ts#FileBindings.set",@@ -20192,6 +22516,168 @@"relation": "imports","confidence": "extracted"},+ {+ "source": "test/llm-adapters.test.ts",+ "target": "src/ai/llm/anthropic.ts#AnthropicChatModel.create",+ "relation": "calls",+ "confidence": "inferred"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#anthropicResp",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#fakeAnthropic",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#fakeOpenAI",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#openAiResp",+ "relation": "calls",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#anthropicResp",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#fakeAnthropic",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#fakeOpenAI",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "test/llm-adapters.test.ts#openAiResp",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "@anthropic-ai/sdk",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "node:assert/strict",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "node:test",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "openai",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "src/ai/llm/anthropic.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "src/ai/llm/openai.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-adapters.test.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "src/ai/crux.ts#ChatCruxSummarizer.describeFile",+ "relation": "calls",+ "confidence": "inferred"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "test/llm-ops.test.ts#FakeChatModel",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "node:assert/strict",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "node:test",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "src/ai/crux.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "src/ai/llm/types.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "src/ai/summarize.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts",+ "target": "src/ai/synthesize.ts",+ "relation": "imports",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts#FakeChatModel",+ "target": "test/llm-ops.test.ts#FakeChatModel.constructor",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts#FakeChatModel",+ "target": "test/llm-ops.test.ts#FakeChatModel.create",+ "relation": "contains",+ "confidence": "extracted"+ },+ {+ "source": "test/llm-ops.test.ts#FakeChatModel",+ "target": "src/ai/llm/types.ts#ChatModel",+ "relation": "implements",+ "confidence": "inferred"+ },{"source": "test/mcp-server.test.ts","target": "test/mcp-server.test.ts#rpc",diff --git a/graft/INDEX.md b/graft/INDEX.mdindex 06faf2ab..e7125849 100644--- a/graft/INDEX.md+++ b/graft/INDEX.md@@ -6,20 +6,37 @@ filename here, or run `graft ask "<task>"`. Each node carries prose plus exact## Concepts-- [ai-model-integration](ai-model-integration.md) — AI Model Integration · bench/llm.ts-- [benchmarking-framework](benchmarking-framework.md) — Benchmarking Framework · bench/agent.ts, bench/judge.ts, bench/llm.ts, bench/report.ts, bench/run.ts, bench/selfcheck.ts, bench/tasks.ts-- [benchmarking-results-reporting](benchmarking-results-reporting.md) — Benchmarking Results Reporting · bench/report.ts-- [caching-mechanism](caching-mechanism.md) — Caching Mechanism · bench/agent.ts, bench/report.ts, src/context/build.ts-- [code-summarization-and-synthesis](code-summarization-and-synthesis.md) — Code Summarization and Synthesis · src/ai/crux.ts, src/ai/summarize.ts, src/ai/synthesize.ts-- [configuration-management](configuration-management.md) — Configuration Management · src/ai/providers.ts-- [error-handling-and-reporting](error-handling-and-reporting.md) — Error Handling and Reporting · bench/run.ts, src/graph/build.ts, src/graph/check.ts-- [graph-construction](graph-construction.md) — Graph Construction · src/context/build.ts, src/context/check.ts, src/graph/build.ts, src/graph/check.ts-- [graph-management](graph-management.md) — Graph Management · src/graph/write.ts+- [agent](agent.md) — Agent · bench/agent.ts+- [benchmarking-system](benchmarking-system.md) — Benchmarking System · bench/agent.ts, bench/judge.ts, bench/llm.ts, bench/report.ts, bench/run.ts, bench/selfcheck.ts, bench/tasks.ts, bench/token-ab.ts+- [code-summarization](code-summarization.md) — Code Summarization · src/ai/crux.ts, src/ai/summarize.ts, src/ai/synthesize.ts+- [configuration-management](configuration-management.md) — Configuration Management · src/ai/providers.ts, src/claude/settings-merge.ts+- [deterministic-testing](deterministic-testing.md) — Deterministic Testing · test/helpers.ts+- [error-handling-and-reporting](error-handling-and-reporting.md) — Error Handling and Reporting · bench/run.ts, src/engine.ts, src/graph/build.ts+- [graph-data-integrity](graph-data-integrity.md) — Graph Data Integrity · test/graph-write.test.ts+- [graph-extraction-and-loading](graph-extraction-and-loading.md) — Graph Extraction and Loading · src/graph/extract.ts, src/graph/load.ts, src/graph/relations.ts, src/graph/resolve.ts, src/graph/types.ts+- [graph-ranking](graph-ranking.md) — Graph Ranking · test/graphrank.test.ts+- [graph-representation](graph-representation.md) — Graph Representation · src/graph/relations.ts, src/graph/types.ts+- [graph-serialization](graph-serialization.md) — Graph Serialization · test/graph-write.test.ts+- [graph-synchronization](graph-synchronization.md) — Graph Synchronization · src/context/check.ts, src/graph/check.ts+- [graph-traversal-and-analysis](graph-traversal-and-analysis.md) — Graph Traversal and Analysis · src/graph/traverse-cli.ts, src/graph/traverse.ts, src/search/grep-cli.ts, src/search/grep.ts+- [graph-traversal-and-impact-analysis](graph-traversal-and-impact-analysis.md) — Graph Traversal and Impact Analysis · test/graph-traverse.test.ts+- [graph-visualization](graph-visualization.md) — Graph Visualization · viewer/data.ts, viewer/detail.ts, viewer/graph.ts, viewer/main.ts, viewer/tree.ts+- [host-configuration-management](host-configuration-management.md) — Host Configuration Management · test/hosts-codex-hooks.test.ts, test/hosts-init.test.ts, test/hosts-mcp-config.test.ts, test/hosts-registry.test.ts, test/hosts-sections.test.ts+- [host-management-and-configuration](host-management-and-configuration.md) — Host Management and Configuration · src/hosts/codex-hooks.ts, src/hosts/init.ts, src/hosts/instructions.ts, src/hosts/mcp-config.ts, src/hosts/registry.ts, src/hosts/sections.ts+- [idempotent-host-initialization](idempotent-host-initialization.md) — Idempotent Host Initialization · test/hosts-init.test.ts+- [judge](judge.md) — Judge · bench/judge.ts+- [llm-integration](llm-integration.md) — LLM Integration · bench/llm.ts+- [mcp-server-and-tools](mcp-server-and-tools.md) — MCP Server and Tools · test/mcp-server.test.ts, test/mcp-tools.test.ts+- [report](report.md) — Report · bench/report.ts- [self-check-mechanism](self-check-mechanism.md) — Self-Check Mechanism · bench/selfcheck.ts-- [task-management](task-management.md) — Task Management · bench/tasks.ts-- [visualization-layer](visualization-layer.md) — Visualization Layer · viewer/data.ts, viewer/detail.ts, viewer/graph.ts, viewer/main.ts, viewer/tree.ts+- [tasks](tasks.md) — Tasks · bench/tasks.ts+- [test-helpers](test-helpers.md) — Test Helpers · test/helpers.ts+- [testing-and-validation](testing-and-validation.md) — Testing and Validation · test/ask-index.test.ts, test/ask.test.ts, test/claude-format.test.ts, test/claude-hooks.test.ts, test/claude-init.test.ts, test/claude-paths.test.ts, test/claude-settings-merge.test.ts, test/claude-shim-template.test.ts, test/claude-skill-template.test.ts, test/claude-state.test.ts, test/claude-stats.test.ts, test/claude-statusline.test.ts, test/cli-meta.test.ts, test/context.test.ts, test/covers.test.ts, test/graph-bindings.test.ts, test/graph-go.test.ts, test/graph-load.test.ts, test/graph-map.test.ts, test/graph-resolve-typed.test.ts, test/graph-traverse-cli.test.ts+- [token-a-b-testing](token-a-b-testing.md) — Token A/B Testing · bench/token-ab.ts+- [user-interaction-in-visualization](user-interaction-in-visualization.md) — User Interaction in Visualization · viewer/detail.ts, viewer/graph.ts, viewer/main.ts+- [visualization-and-serving](visualization-and-serving.md) — Visualization and Serving · src/viz/assemble.ts, src/viz/serve.ts## Files-105 per-file wiring cards mirror the source tree under `graft/` (94 carry extracted symbols). They are deliberately not enumerated here —+111 per-file wiring cards mirror the source tree under `graft/` (100 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.diff --git a/graft/agent.md b/graft/agent.mdnew file mode 100644index 00000000..c57a0215--- /dev/null+++ b/graft/agent.md@@ -0,0 +1,60 @@+---+name: Agent+slug: agent+type: system+sources:+ - path: bench/agent.ts+ hash: 34a496d38f2dfc14688cb4f0981262d79dacef165bd1a4f9874b94c31e1819e9+sources_digest: 989950aca29644904bb9a7040d36a735534f3b0d1b3854912a2303e5b0831423+links:+ - to: llm-integration+ relation: uses+ description: The agent relies on language models for processing queries.+ - to: tasks+ relation: depends_on+ description: The agent executes tasks defined in the benchmark corpus.+generator:+ version: 1+covers:+ - symbol: AgentResult+ kind: interface+ at: 'bench/agent.ts:L20-L28'+ - symbol: RunAgentOptions+ kind: interface+ at: 'bench/agent.ts:L30-L42'+ - symbol: safePath+ kind: function+ at: 'bench/agent.ts:L51-L65'+ - symbol: listFiles+ kind: function+ at: 'bench/agent.ts:L67-L94'+ - symbol: walk+ kind: function+ at: 'bench/agent.ts:L69-L91'+ - symbol: globToRegExp+ kind: function+ at: 'bench/agent.ts:L97-L111'+ - symbol: runTool+ kind: function+ at: 'bench/agent.ts:L189-L259'+ - symbol: runAgent+ kind: function+ at: 'bench/agent.ts:L261-L341'+ - symbol: slideCacheBreakpoint+ kind: function+ at: 'bench/agent.ts:L289-L294'+---+<!-- context:generated:start -->+## Summary++The agent component implements a benchmark agent that processes questions using filesystem tools and a language model, tracking metrics such as token usage and tool calls. It emphasizes safety and correctness in its operations, ensuring secure filesystem access and accurate reporting of resource usage.++## Related++- uses [[llm-integration]] — The agent relies on language models for processing queries.+- depends on [[tasks]] — The agent executes tasks defined in the benchmark corpus.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/ai-model-integration.md b/graft/ai-model-integration.mddeleted file mode 100644index 28eac34d..00000000--- a/graft/ai-model-integration.md+++ /dev/null@@ -1,32 +0,0 @@-----name: AI Model Integration-slug: ai-model-integration-type: system-sources:- - path: bench/llm.ts- hash: 6c0d2a02ac6aa86de94f779355020700a4d9016e2f4b431bf75560e1d3c51229-sources_digest: 1bdc59307386b5187ea92242900b2c3b286de3f9f45a08a7dfcf1c2d11801b27-links:- - to: benchmarking-framework- relation: part_of- description: Forms a core part of the benchmarking framework.-generator:- version: 1-covers:- - symbol: makeClient- kind: function- at: 'bench/llm.ts:L14-L18'-----<!-- context:generated:start -->-## Summary--This component manages the integration of AI models, specifically through the OpenRouter service, allowing for flexible model configurations and interactions. It provides the necessary client setup for benchmarking tasks.--## Related--- part of [[benchmarking-framework]] — Forms a core part of the benchmarking framework.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/bench/agent.md b/graft/bench/agent.mdindex e1649152..6c8150ce 100644--- a/graft/bench/agent.md+++ b/graft/bench/agent.md@@ -1,13 +1,13 @@-# bench/agent.ts · [[benchmarking-framework]] [[caching-mechanism]]+# bench/agent.ts · [[agent]] [[benchmarking-system]]-This file implements a benchmark agent that processes questions about a codebase using filesystem tools and a language model.+This file implements a benchmark agent that executes a loop for evaluating the performance of different AI models in answering questions based on a codebase.- AgentResult · interface · L20-L28 — Defines the structure of the result returned by the agent, encapsulating the answer and various metrics.-- RunAgentOptions · interface · L30-L42 — Specifies the options for running the agent, including the root directory and the question to be answered.+- RunAgentOptions · interface · L30-L42 — Defines the options for running the agent, including the root directory and the question to be answered.- safePath · function · L51-L65 — Ensures that a given path is safely resolved within a specified root directory, preventing directory traversal attacks.- listFiles · function · L67-L94 — Recursively lists all files in a directory while respecting size limits and skipping specified directories.- walk · function · L69-L91 — A helper function that traverses a directory to collect file paths, avoiding hidden files and skipped directories.- globToRegExp · function · L97-L111 — Converts a glob pattern into a regular expression for matching file paths.-- runTool · function · L207-L277 — Executes a specified tool (like reading a file or listing a directory) based on the provided input parameters.-- runAgent · function · L279-L376 — Manages the execution of the agent's logic, including handling user questions and tool interactions.-- slideCacheBreakpoint · function · L308-L314 — Maintains the cache state by updating the cache control for the most recent tool result in the message history.+- runTool · function · L189-L259 — Executes a specified tool with given input, handling various file operations and queries within a defined root directory.+- runAgent · function · L261-L341 — Manages the execution of the agent, processing user questions and utilizing tools to generate answers while tracking performance metrics.+- slideCacheBreakpoint · function · L289-L294 — Maintains the cache breakpoint on the most recent tool result to optimize performance during the agent's execution.diff --git a/graft/bench/judge.md b/graft/bench/judge.mdindex a97e1b89..124ba8b2 100644--- a/graft/bench/judge.md+++ b/graft/bench/judge.md@@ -1,8 +1,8 @@-# bench/judge.ts · [[benchmarking-framework]]+# bench/judge.ts · [[benchmarking-system]] [[judge]]-This file implements a correctness scoring system that evaluates AI-generated answers against a reference answer using keyword checks and an LLM judge.+This file implements a correctness scoring system that evaluates AI-generated answers against a reference answer, ensuring both keyword requirements and factual accuracy are met.- Verdict · interface · L18-L24 — The Verdict interface encapsulates the scoring results and correctness evaluation of an AI agent's answer.-- JudgeInput · interface · L26-L32 — The JudgeInput interface defines the structure of input data required for the judging process, including the question and answers.+- JudgeInput · interface · L26-L32 — Defines the structure for input data required to evaluate an AI agent's answer, including the question, reference answer, and required keywords.- extractJson · function · L35-L49 — The extractJson function retrieves the first JSON object from a string, handling cases where the JSON is wrapped in additional text.-- judge · function · L51-L87 — The judge function evaluates an AI agent's answer against a reference answer, returning a Verdict based on keyword presence and LLM scoring.+- judge · function · L51-L86 — Evaluates an AI agent's answer against a reference answer, returning a verdict that indicates correctness based on both a judge's score and keyword requirements.diff --git a/graft/bench/llm.md b/graft/bench/llm.mdindex c6c3c398..9a544ed3 100644--- a/graft/bench/llm.md+++ b/graft/bench/llm.md@@ -1,5 +1,5 @@-# bench/llm.ts · [[ai-model-integration]] [[benchmarking-framework]]+# bench/llm.ts · [[benchmarking-system]] [[llm-integration]]-This file configures and provides access to the OpenRouter API for benchmarking LLMs without needing separate API keys.+This file provides a benchmark setup for LLMs, ensuring that the correct models and configurations are used based on environment variables.-- makeClient · function · L14-L18 — Creates an OpenAI client instance, ensuring that the necessary API key is provided for operation.+- makeChatModel · function · L16-L28 — Creates a chat model instance while enforcing the requirement of a valid API key for the provider.diff --git a/graft/bench/report.md b/graft/bench/report.mdindex 86e66daf..6c4ac056 100644--- a/graft/bench/report.md+++ b/graft/bench/report.md@@ -1,16 +1,16 @@-# bench/report.ts · [[benchmarking-framework]] [[benchmarking-results-reporting]] [[caching-mechanism]]+# bench/report.ts · [[benchmarking-system]] [[report]]-This file provides functionality for aggregating and reporting benchmark results for different agent configurations.+This file aggregates and reports benchmark results for different agent configurations, providing insights into performance metrics.-- Arm · type · L6-L6 — type Arm = "cold" | "graph" | "pull";-- Row · interface · L8-L30 — Defines the structure of a benchmark trial row, capturing various metrics related to agent performance.+- Arm · type · L6-L6 — Defines the possible execution arms for the benchmarking process, categorizing the types of agent runs.+- Row · interface · L8-L30 — Represents a single trial's data, encapsulating all relevant metrics for benchmarking an agent's performance.- costOf · function · L37-L42 — Calculates the approximate cost of running an agent based on input and output tokens and cache operations.- mean · function · L44-L46 — Computes the mean of an array of numbers, returning zero for an empty array.- ArmAgg · interface · L48-L58 — Represents aggregated metrics for a specific arm of the benchmark, including totals and averages.- aggregate · function · L60-L72 — Aggregates multiple benchmark rows into a single ArmAgg object, calculating averages for various metrics.- pctDelta · function · L74-L78 — Calculates the percentage delta between two values, handling the case where the first value is zero.- fmt · function · L80-L82 — Formats a number for display, adjusting for thousands and decimal precision.-- metricTable · function · L88-L114 — function metricTable(rows: Row[], arms: Arm[]): string[]-- cells · function · L93-L102 — cells = (label: string, value: (a: ArmAgg) => number, render: (v: number) => string, delta?: (c: number, x: number) => string)-- verdictFor · function · L117-L127 — function verdictFor(label: string, c: ArmAgg, g: ArmAgg): string-- buildMarkdown · function · L129-L175 — Generates a markdown report summarizing benchmark results across different corpora and arms.+- metricTable · function · L88-L114 — Generates a formatted metric table comparing performance across different agent arms, highlighting key metrics and deltas.+- cells · function · L93-L102 — Constructs individual cells for the metric table, calculating values and formatting them for display.+- verdictFor · function · L117-L127 — Evaluates and compares the cost and correctness of two agent configurations, providing a verdict on their performance.+- buildMarkdown · function · L129-L175 — Compiles the overall benchmark results into a markdown format for easy readability and presentation.diff --git a/graft/bench/run.md b/graft/bench/run.mdindex 4c3805c5..c30b3c5d 100644--- a/graft/bench/run.md+++ b/graft/bench/run.md@@ -1,9 +1,9 @@-# bench/run.ts · [[benchmarking-framework]] [[error-handling-and-reporting]]+# bench/run.ts · [[benchmarking-system]] [[error-handling-and-reporting]]-This file orchestrates the benchmarking process for various corpora and tasks, managing the execution and reporting of results.+Orchestrates benchmarking tasks across different configurations and trials, ensuring efficient execution and result collection.-- Args · interface · L38-L44 — Defines the structure for command-line arguments used to configure the benchmarking run.-- parseArgs · function · L46-L66 — Parses command-line arguments to extract configuration options for the benchmarking process.-- pool · function · L69-L80 — Executes a function on a set of items concurrently, limiting the number of simultaneous operations.-- worker · function · L72-L77 — Processes items in the pool function, handling each item asynchronously.-- main · function · L82-L202 — Coordinates the overall benchmarking process, including argument parsing, corpus ingestion, and result reporting.+- Args · interface · L39-L45 — Defines the structure for command-line arguments to configure the benchmarking process.+- parseArgs · function · L47-L67 — Parses command-line arguments to set up the benchmarking configuration, ensuring valid options are provided.+- pool · function · L70-L81 — Executes a function on a set of items concurrently, limiting the number of simultaneous operations.+- worker · function · L73-L78 — Processes items in the pool function, handling each item asynchronously.+- main · function · L83-L204 — Coordinates the overall benchmarking process, including argument parsing, corpus handling, and result generation.diff --git a/graft/bench/selfcheck.md b/graft/bench/selfcheck.mdindex 40e126a0..aa35e497 100644--- a/graft/bench/selfcheck.md+++ b/graft/bench/selfcheck.md@@ -1,6 +1,7 @@-# bench/selfcheck.ts · [[benchmarking-framework]] [[self-check-mechanism]]+# bench/selfcheck.ts · [[benchmarking-system]] [[self-check-mechanism]]-This file performs an offline verification of the harness plumbing to ensure control flow works correctly without needing an API key.+This file provides an offline verification mechanism for the harness plumbing, ensuring control flow integrity without requiring an API key.-- makeStubClient · function · L19-L48 — Creates a stub client that simulates responses for agent and judge interactions during testing.-- main · function · L50-L114 — Coordinates the self-check process by setting up a temporary environment, running the agent, and validating the results.+- makeStubModel · function · L20-L39 — Creates a stubbed ChatModel that simulates agent behavior for testing purposes, allowing for controlled responses during the agent loop.+- create · method · L24-L37 — Handles requests by returning predefined responses based on the request format, simulating the agent's decision-making process.+- main · function · L41-L105 — Coordinates the self-check process by setting up the environment, running the agent, and validating the results through assertions.diff --git a/graft/bench/tasks.md b/graft/bench/tasks.mdindex 3079954b..b938a14a 100644--- a/graft/bench/tasks.md+++ b/graft/bench/tasks.md@@ -1,7 +1,7 @@-# bench/tasks.ts · [[benchmarking-framework]] [[task-management]]+# bench/tasks.ts · [[benchmarking-system]] [[tasks]]-This file defines benchmark tasks and their corresponding reference answers for validating code understanding across multiple repositories.+This file defines benchmark tasks and their associated metadata to ensure verifiable answers for codebase questions.- repoPath · function · L30-L33 — This function determines the file path for sibling repositories, allowing for environment variable overrides.-- Task · interface · L35-L45 — This interface outlines the structure of a benchmark task, including its ID, question, reference answer, and required keywords.+- Task · interface · L35-L45 — The Task interface structures the data for individual benchmark questions, ensuring they include necessary details for validation.- Corpus · interface · L47-L53 — This interface defines a corpus of benchmark tasks, specifying its ID, type, path, and associated tasks.diff --git a/graft/bench/token-ab.md b/graft/bench/token-ab.mdindex 3b5d7d07..17273810 100644--- a/graft/bench/token-ab.md+++ b/graft/bench/token-ab.md@@ -1,11 +1,13 @@-# bench/token-ab.ts+# bench/token-ab.ts · [[benchmarking-system]] [[token-a-b-testing]]-- Metrics · interface · L59-L68 — interface Metrics-- runSearch · function · L108-L138 — function runSearch(pattern: string): string-- runRead · function · L140-L157 — function runRead(path: string, start?: number, end?: number): { text: string; resolved: string }-- runAgent · function · L160-L226 — async function runAgent(arm: string, extraContext: string | null): Promise<Metrics>-- graftPack · function · L229-L240 — function graftPack(): { pack: string; ms: number }-- cost · function · L242-L246 — function cost(m: Metrics): string-- row · function · L248-L250 — function row(label: string, a: string | number, b: string | number): string-- main · function · L252-L292 — async function main()-- pct · function · L272-L272 — pct = (a: number, b: number)+This script benchmarks the performance of an agent using two different approaches (COLD and GRAFT) to determine if providing pre-computed context saves tokens during code exploration.++- Metrics · interface · L55-L64 — Defines the structure for capturing metrics related to the A/B testing of the agent's performance.+- runSearch · function · L98-L128 — Executes a regex search across the repository to find relevant code snippets based on a given pattern.+- runRead · function · L130-L147 — Reads a specified source file or a range of lines from it, ensuring it is within the repository's bounds.+- runAgent · function · L150-L207 — Manages the agent's execution loop, handling user queries and tool calls while tracking performance metrics.+- graftPack · function · L210-L221 — Generates a context pack using the graft tool to provide pre-computed information for the agent.+- cost · function · L223-L227 — Calculates the estimated cost of the agent's operations based on token usage and pricing configuration.+- row · function · L229-L231 — Formats a row of metrics for display in the output table comparing the COLD and GRAFT arms.+- main · function · L233-L273 — Coordinates the overall execution of the A/B test, including generating the graft pack and running both agent arms.+- pct · function · L253-L253 — Calculates the percentage improvement in token usage between the COLD and GRAFT arms.diff --git a/graft/benchmarking-framework.md b/graft/benchmarking-framework.mddeleted file mode 100644index 3a9ec84b..00000000--- a/graft/benchmarking-framework.md+++ /dev/null@@ -1,157 +0,0 @@-----name: Benchmarking Framework-slug: benchmarking-framework-type: system-sources:- - path: bench/agent.ts- hash: e10d64f913c9517cef84cce58ea042d71bed3e94182c791245170eca54060e31- - path: bench/judge.ts- hash: 94c222341b066e4f3134b3d9d3f30f31b9ffe7b92967086b07c58f297d349936- - path: bench/llm.ts- hash: 6c0d2a02ac6aa86de94f779355020700a4d9016e2f4b431bf75560e1d3c51229- - path: bench/report.ts- hash: 775be8c40a8e4172521bba8f6a1f026fa23c4d24b9b5225da3ed5b745077a5b0- - path: bench/run.ts- hash: a0d2859628588f45ae31862f5f801d6219802449c23bbbdba9aa51b7b9febf47- - path: bench/selfcheck.ts- hash: 0eaf577938e20fa27d9cd0157bc8843fdc37165d85696789334b8605138f4bb4- - path: bench/tasks.ts- hash: d21168797f40d193a914aca0c438409d29d300441bc0a6a518c93869240b3b69-sources_digest: afaac16d744b84811efe1b826c2bab23737665e1e62fe39b1267f20f5451b4d0-links:- - to: ai-model-integration- relation: uses- description: Utilizes the OpenRouter service for model interactions.- - to: benchmarking-results-reporting- relation: produces- description: Generates reports summarizing benchmarking results.- - to: task-management- relation: depends_on- description: Relies on defined tasks and corpora for benchmarking.-generator:- version: 1-covers:- - symbol: AgentResult- kind: interface- at: 'bench/agent.ts:L20-L28'- - symbol: RunAgentOptions- kind: interface- at: 'bench/agent.ts:L30-L42'- - symbol: safePath- kind: function- at: 'bench/agent.ts:L51-L65'- - symbol: listFiles- kind: function- at: 'bench/agent.ts:L67-L94'- - symbol: walk- kind: function- at: 'bench/agent.ts:L69-L91'- - symbol: globToRegExp- kind: function- at: 'bench/agent.ts:L97-L111'- - symbol: runTool- kind: function- at: 'bench/agent.ts:L207-L277'- - symbol: runAgent- kind: function- at: 'bench/agent.ts:L279-L376'- - symbol: slideCacheBreakpoint- kind: function- at: 'bench/agent.ts:L308-L314'- - symbol: Verdict- kind: interface- at: 'bench/judge.ts:L18-L24'- - symbol: JudgeInput- kind: interface- at: 'bench/judge.ts:L26-L32'- - symbol: extractJson- kind: function- at: 'bench/judge.ts:L35-L49'- - symbol: judge- kind: function- at: 'bench/judge.ts:L51-L87'- - symbol: makeClient- kind: function- at: 'bench/llm.ts:L14-L18'- - symbol: Arm- kind: type- at: 'bench/report.ts:L6-L6'- - symbol: Row- kind: interface- at: 'bench/report.ts:L8-L30'- - symbol: costOf- kind: function- at: 'bench/report.ts:L37-L42'- - symbol: mean- kind: function- at: 'bench/report.ts:L44-L46'- - symbol: ArmAgg- kind: interface- at: 'bench/report.ts:L48-L58'- - symbol: aggregate- kind: function- at: 'bench/report.ts:L60-L72'- - symbol: pctDelta- kind: function- at: 'bench/report.ts:L74-L78'- - symbol: fmt- kind: function- at: 'bench/report.ts:L80-L82'- - symbol: metricTable- kind: function- at: 'bench/report.ts:L88-L114'- - symbol: cells- kind: function- at: 'bench/report.ts:L93-L102'- - symbol: verdictFor- kind: function- at: 'bench/report.ts:L117-L127'- - symbol: buildMarkdown- kind: function- at: 'bench/report.ts:L129-L175'- - symbol: Args- kind: interface- at: 'bench/run.ts:L38-L44'- - symbol: parseArgs- kind: function- at: 'bench/run.ts:L46-L66'- - symbol: pool- kind: function- at: 'bench/run.ts:L69-L80'- - symbol: worker- kind: function- at: 'bench/run.ts:L72-L77'- - symbol: main- kind: function- at: 'bench/run.ts:L82-L202'- - symbol: makeStubClient- kind: function- at: 'bench/selfcheck.ts:L19-L48'- - symbol: main- kind: function- at: 'bench/selfcheck.ts:L50-L114'- - symbol: repoPath- kind: function- at: 'bench/tasks.ts:L30-L33'- - symbol: Task- kind: interface- at: 'bench/tasks.ts:L35-L45'- - symbol: Corpus- kind: interface- at: 'bench/tasks.ts:L47-L53'-----<!-- context:generated:start -->-## Summary--This component orchestrates the benchmarking process, evaluating AI models through agents and judges, and reporting results. It integrates various modules for running benchmarks, scoring correctness, and managing configurations.--## Related--- uses [[ai-model-integration]] — Utilizes the OpenRouter service for model interactions.-- produces [[benchmarking-results-reporting]] — Generates reports summarizing benchmarking results.-- depends on [[task-management]] — Relies on defined tasks and corpora for benchmarking.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/benchmarking-system.md b/graft/benchmarking-system.mdnew file mode 100644index 00000000..deff437b--- /dev/null+++ b/graft/benchmarking-system.md@@ -0,0 +1,197 @@+---+name: Benchmarking System+slug: benchmarking-system+type: system+sources:+ - path: bench/agent.ts+ hash: 34a496d38f2dfc14688cb4f0981262d79dacef165bd1a4f9874b94c31e1819e9+ - path: bench/judge.ts+ hash: bb48a8012b929bc0237f4d900d0ab7aa9a98f96777d72a89ce5305c6c57e6c47+ - path: bench/llm.ts+ hash: 6fc86553ce48879cb28b411747fe3ffaa2ad5c269e5de50d83e4ed8b629cae2b+ - path: bench/report.ts+ hash: 17c0be550f9712165177d070f58cbe7a0f60fcb2c1dc5830eb1a4dde97ec12f3+ - path: bench/run.ts+ hash: fd4445eb0d6d3c1a8b994c7e4be42522c3214612a8499e4f76bfc10d0030f9da+ - path: bench/selfcheck.ts+ hash: 858ec7cce92c9105c4e111ae58f1d1a1b1b57372b96768804308009760c9b2f6+ - path: bench/tasks.ts+ hash: efb90e69f52adcb08bfe45fb5a983fc676df68befdc455513e2581a24f46807e+ - path: bench/token-ab.ts+ hash: b033a023d063cccc329103fbd11d4e1a6ab16c5eb027e1dd85c47a63a7df4ff1+sources_digest: 918b737414aae73bb0f84df38880140028a61e8bf27b89b544943394d05bb10f+links:+ - to: agent+ relation: part_of+ description: The agent is responsible for executing tasks and collecting metrics.+ - to: judge+ relation: part_of+ description: The judge evaluates the correctness of the agent's responses.+ - to: llm-integration+ relation: part_of+ description: Integrates various language models for benchmarking.+ - to: report+ relation: part_of+ description: The report aggregates and presents benchmarking results.+ - to: tasks+ relation: part_of+ description: Tasks define the benchmark questions and expected answers.+generator:+ version: 1+covers:+ - symbol: AgentResult+ kind: interface+ at: 'bench/agent.ts:L20-L28'+ - symbol: RunAgentOptions+ kind: interface+ at: 'bench/agent.ts:L30-L42'+ - symbol: safePath+ kind: function+ at: 'bench/agent.ts:L51-L65'+ - symbol: listFiles+ kind: function+ at: 'bench/agent.ts:L67-L94'+ - symbol: walk+ kind: function+ at: 'bench/agent.ts:L69-L91'+ - symbol: globToRegExp+ kind: function+ at: 'bench/agent.ts:L97-L111'+ - symbol: runTool+ kind: function+ at: 'bench/agent.ts:L189-L259'+ - symbol: runAgent+ kind: function+ at: 'bench/agent.ts:L261-L341'+ - symbol: slideCacheBreakpoint+ kind: function+ at: 'bench/agent.ts:L289-L294'+ - symbol: Verdict+ kind: interface+ at: 'bench/judge.ts:L18-L24'+ - symbol: JudgeInput+ kind: interface+ at: 'bench/judge.ts:L26-L32'+ - symbol: extractJson+ kind: function+ at: 'bench/judge.ts:L35-L49'+ - symbol: judge+ kind: function+ at: 'bench/judge.ts:L51-L86'+ - symbol: makeChatModel+ kind: function+ at: 'bench/llm.ts:L16-L28'+ - symbol: Arm+ kind: type+ at: 'bench/report.ts:L6-L6'+ - symbol: Row+ kind: interface+ at: 'bench/report.ts:L8-L30'+ - symbol: costOf+ kind: function+ at: 'bench/report.ts:L37-L42'+ - symbol: mean+ kind: function+ at: 'bench/report.ts:L44-L46'+ - symbol: ArmAgg+ kind: interface+ at: 'bench/report.ts:L48-L58'+ - symbol: aggregate+ kind: function+ at: 'bench/report.ts:L60-L72'+ - symbol: pctDelta+ kind: function+ at: 'bench/report.ts:L74-L78'+ - symbol: fmt+ kind: function+ at: 'bench/report.ts:L80-L82'+ - symbol: metricTable+ kind: function+ at: 'bench/report.ts:L88-L114'+ - symbol: cells+ kind: function+ at: 'bench/report.ts:L93-L102'+ - symbol: verdictFor+ kind: function+ at: 'bench/report.ts:L117-L127'+ - symbol: buildMarkdown+ kind: function+ at: 'bench/report.ts:L129-L175'+ - symbol: Args+ kind: interface+ at: 'bench/run.ts:L39-L45'+ - symbol: parseArgs+ kind: function+ at: 'bench/run.ts:L47-L67'+ - symbol: pool+ kind: function+ at: 'bench/run.ts:L70-L81'+ - symbol: worker+ kind: function+ at: 'bench/run.ts:L73-L78'+ - symbol: main+ kind: function+ at: 'bench/run.ts:L83-L204'+ - symbol: makeStubModel+ kind: function+ at: 'bench/selfcheck.ts:L20-L39'+ - symbol: create+ kind: method+ at: 'bench/selfcheck.ts:L24-L37'+ - symbol: main+ kind: function+ at: 'bench/selfcheck.ts:L41-L105'+ - symbol: repoPath+ kind: function+ at: 'bench/tasks.ts:L30-L33'+ - symbol: Task+ kind: interface+ at: 'bench/tasks.ts:L35-L45'+ - symbol: Corpus+ kind: interface+ at: 'bench/tasks.ts:L47-L53'+ - symbol: Metrics+ kind: interface+ at: 'bench/token-ab.ts:L55-L64'+ - symbol: runSearch+ kind: function+ at: 'bench/token-ab.ts:L98-L128'+ - symbol: runRead+ kind: function+ at: 'bench/token-ab.ts:L130-L147'+ - symbol: runAgent+ kind: function+ at: 'bench/token-ab.ts:L150-L207'+ - symbol: graftPack+ kind: function+ at: 'bench/token-ab.ts:L210-L221'+ - symbol: cost+ kind: function+ at: 'bench/token-ab.ts:L223-L227'+ - symbol: row+ kind: function+ at: 'bench/token-ab.ts:L229-L231'+ - symbol: main+ kind: function+ at: 'bench/token-ab.ts:L233-L273'+ - symbol: pct+ kind: function+ at: 'bench/token-ab.ts:L253-L253'+---+<!-- context:generated:start -->+## Summary++This system orchestrates the benchmarking of AI agents and language models, facilitating comparisons of performance metrics such as token usage, latency, and correctness across different execution arms. It integrates various components including agents, judges, and reporting tools to provide a comprehensive evaluation framework.++## Related++- part of [[agent]] — The agent is responsible for executing tasks and collecting metrics.+- part of [[judge]] — The judge evaluates the correctness of the agent's responses.+- part of [[llm-integration]] — Integrates various language models for benchmarking.+- part of [[report]] — The report aggregates and presents benchmarking results.+- part of [[tasks]] — Tasks define the benchmark questions and expected answers.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/caching-mechanism.md b/graft/caching-mechanism.mddeleted file mode 100644index f4b0ef4a..00000000--- a/graft/caching-mechanism.md+++ /dev/null@@ -1,144 +0,0 @@-----name: Caching Mechanism-slug: caching-mechanism-type: concept-sources:- - path: bench/agent.ts- hash: e10d64f913c9517cef84cce58ea042d71bed3e94182c791245170eca54060e31- - path: bench/report.ts- hash: 775be8c40a8e4172521bba8f6a1f026fa23c4d24b9b5225da3ed5b745077a5b0- - path: src/context/build.ts- hash: 8c614e5dc6b1ef2d6949016ce7480099f95f021ea6b0882f2919397f97a68ce7-sources_digest: 0393dee6bf242715500eeac001ca94cd9c7ff05d644d8e36d58e9c7fd2e0eab9-links:- - to: benchmarking-framework- relation: validates- description: Ensures that caching is effectively utilized in benchmarking.-generator:- version: 1-covers:- - symbol: AgentResult- kind: interface- at: 'bench/agent.ts:L20-L28'- - symbol: RunAgentOptions- kind: interface- at: 'bench/agent.ts:L30-L42'- - symbol: safePath- kind: function- at: 'bench/agent.ts:L51-L65'- - symbol: listFiles- kind: function- at: 'bench/agent.ts:L67-L94'- - symbol: walk- kind: function- at: 'bench/agent.ts:L69-L91'- - symbol: globToRegExp- kind: function- at: 'bench/agent.ts:L97-L111'- - symbol: runTool- kind: function- at: 'bench/agent.ts:L207-L277'- - symbol: runAgent- kind: function- at: 'bench/agent.ts:L279-L376'- - symbol: slideCacheBreakpoint- kind: function- at: 'bench/agent.ts:L308-L314'- - symbol: Arm- kind: type- at: 'bench/report.ts:L6-L6'- - symbol: Row- kind: interface- at: 'bench/report.ts:L8-L30'- - symbol: costOf- kind: function- at: 'bench/report.ts:L37-L42'- - symbol: mean- kind: function- at: 'bench/report.ts:L44-L46'- - symbol: ArmAgg- kind: interface- at: 'bench/report.ts:L48-L58'- - symbol: aggregate- kind: function- at: 'bench/report.ts:L60-L72'- - symbol: pctDelta- kind: function- at: 'bench/report.ts:L74-L78'- - symbol: fmt- kind: function- at: 'bench/report.ts:L80-L82'- - symbol: metricTable- kind: function- at: 'bench/report.ts:L88-L114'- - symbol: cells- kind: function- at: 'bench/report.ts:L93-L102'- - symbol: verdictFor- kind: function- at: 'bench/report.ts:L117-L127'- - symbol: buildMarkdown- kind: function- at: 'bench/report.ts:L129-L175'- - symbol: BuildProgress- kind: interface- at: 'src/context/build.ts:L47-L52'- - symbol: BuildOptions- kind: interface- at: 'src/context/build.ts:L54-L64'- - symbol: BuildResult- kind: interface- at: 'src/context/build.ts:L66-L75'- - symbol: BuildCache- kind: interface- at: 'src/context/build.ts:L78-L81'- - symbol: FileWork- kind: interface- at: 'src/context/build.ts:L83-L87'- - symbol: NodeDraft- kind: interface- at: 'src/context/build.ts:L90-L97'- - symbol: buildContext- kind: function- at: 'src/context/build.ts:L99-L266'- - symbol: batchBySize- kind: function- at: 'src/context/build.ts:L269-L285'- - symbol: batchKey- kind: function- at: 'src/context/build.ts:L288-L295'- - symbol: registerName- kind: function- at: 'src/context/build.ts:L297-L300'- - symbol: resolveSlug- kind: function- at: 'src/context/build.ts:L302-L304'- - symbol: errMsg- kind: function- at: 'src/context/build.ts:L306-L308'- - symbol: cachePath- kind: function- at: 'src/context/build.ts:L310-L312'- - symbol: loadCache- kind: function- at: 'src/context/build.ts:L314-L325'- - symbol: saveCache- kind: function- at: 'src/context/build.ts:L327-L331'- - symbol: mapWithConcurrency- kind: function- at: 'src/context/build.ts:L334-L349'-----<!-- context:generated:start -->-## Summary--This concept involves the use of caching to optimize performance and reduce costs associated with repeated prompts in the benchmarking process.--## Related--- validates [[benchmarking-framework]] — Ensures that caching is effectively utilized in benchmarking.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/code-summarization-and-synthesis.md b/graft/code-summarization.mdsimilarity index 55%rename from graft/code-summarization-and-synthesis.mdrename to graft/code-summarization.mdindex 12cdb4f6..995acb47 100644--- a/graft/code-summarization-and-synthesis.md+++ b/graft/code-summarization.md@@ -1,19 +1,19 @@----name: Code Summarization and Synthesis-slug: code-summarization-and-synthesis-type: system+name: Code Summarization+slug: code-summarization+type: conceptsources:- path: src/ai/crux.ts- hash: e81750029e4c8641cdaf2b4894f595297839e07a73076e4cdac1522515f923a8+ hash: 81323b622400aadae1fd584ea09c2016ccf1bf4f14654b648ee50b1b13bd4c68- path: src/ai/summarize.ts- hash: 6e67f3866c75d88a8b1d265e510578f3e3014d9cfd8b2469e6e4afbd67977f93+ hash: 8dbec8d421f079ec67c81701d28ed1eb648b64e074b338538d03b9063941cffd- path: src/ai/synthesize.ts- hash: 982ab91da10ae51fdba64466cbb614db14a51f2e100bb12a72178961d8dd97d7-sources_digest: 1916d34902c4bd664703e6c5da273beb26c2be5f55e971b3cc3f590f65cde3c7+ hash: 7c6124323d5112abb15f0adea21962e083ea38234a8771832a71a59350fdc362+sources_digest: 2df073fd00fbefc26907027a923c10609cf005d9cbb727ff2917374d03b251dclinks:- - to: graph-construction- relation: produces- description: Generates structured nodes for the architecture graph.+ - to: benchmarking-system+ relation: validates+ description: Summarization is validated through benchmarking results.generator:version: 1covers:@@ -31,40 +31,40 @@ covers:at: 'src/ai/crux.ts:L42-L44'- symbol: numberLineskind: function- at: 'src/ai/crux.ts:L63-L70'+ at: 'src/ai/crux.ts:L81-L88'- symbol: userContentkind: function- at: 'src/ai/crux.ts:L72-L81'+ at: 'src/ai/crux.ts:L90-L99'- symbol: parseResultskind: function- at: 'src/ai/crux.ts:L84-L98'+ at: 'src/ai/crux.ts:L102-L114'- symbol: numkind: function- at: 'src/ai/crux.ts:L88-L88'- - symbol: OpenRouterCruxSummarizer+ at: 'src/ai/crux.ts:L104-L104'+ - symbol: ChatCruxSummarizerkind: class- at: 'src/ai/crux.ts:L101-L127'+ at: 'src/ai/crux.ts:L117-L140'- symbol: constructorkind: method- at: 'src/ai/crux.ts:L105-L112'+ at: 'src/ai/crux.ts:L118-L118'- symbol: describeFilekind: method- at: 'src/ai/crux.ts:L114-L126'+ at: 'src/ai/crux.ts:L120-L139'- symbol: Summarizerkind: interfaceat: 'src/ai/summarize.ts:L13-L15'- symbol: userContentkind: functionat: 'src/ai/summarize.ts:L28-L34'- - symbol: OpenRouterSummarizer+ - symbol: ChatSummarizerkind: class- at: 'src/ai/summarize.ts:L37-L61'+ at: 'src/ai/summarize.ts:L37-L51'- symbol: constructorkind: method- at: 'src/ai/summarize.ts:L41-L48'+ at: 'src/ai/summarize.ts:L38-L38'- symbol: summarizekind: method- at: 'src/ai/summarize.ts:L50-L60'+ at: 'src/ai/summarize.ts:L40-L50'- symbol: SynthLinkkind: interfaceat: 'src/ai/synthesize.ts:L12-L16'@@ -83,24 +83,24 @@ covers:- symbol: cleankind: functionat: 'src/ai/synthesize.ts:L101-L123'- - symbol: OpenRouterSynthesizer+ - symbol: ChatSynthesizerkind: class- at: 'src/ai/synthesize.ts:L135-L164'+ at: 'src/ai/synthesize.ts:L128-L154'- symbol: constructorkind: method- at: 'src/ai/synthesize.ts:L139-L142'+ at: 'src/ai/synthesize.ts:L129-L129'- symbol: synthesizekind: method- at: 'src/ai/synthesize.ts:L144-L163'+ at: 'src/ai/synthesize.ts:L131-L153'---<!-- context:generated:start -->## Summary-This component focuses on summarizing code definitions and synthesizing a structured architecture graph from file summaries, enhancing the understanding of the codebase's architecture.+This concept encompasses the methods and strategies used to summarize code definitions and generate meaningful insights from source files, enhancing code navigation and understanding for engineers.## Related-- produces [[graph-construction]] — Generates structured nodes for the architecture graph.+- validates [[benchmarking-system]] — Summarization is validated through benchmarking results.<!-- context:generated:end -->## Notesdiff --git a/graft/configuration-management.md b/graft/configuration-management.mdindex 734a5b35..7d1ea85d 100644--- a/graft/configuration-management.md+++ b/graft/configuration-management.md@@ -4,33 +4,50 @@ slug: configuration-managementtype: conceptsources:- path: src/ai/providers.ts- hash: c0d1294d6fa49f6d06ff9bb137b34ea897f94a67810a839cd5705a1fa5995483-sources_digest: a131fc0c197424e0b9a6a1da0c7e97f8aaa37eb06f6720480e7959923c918071+ hash: ba27e2c6d98b088685946371971e9f82c7a54bba9eaa432d44881880274eb1d6+ - path: src/claude/settings-merge.ts+ hash: eda59409ff8c470e7d3726a6740ba19e36e511ab40c67234aa794fabd9eacb8d+sources_digest: cbca57735b2ad73fb6d62dde432844f8879809265ad6f5274082ab955c08b5b8links:- - to: ai-model-integration+ - to: llm-integrationrelation: configures- description: Allows users to specify configurations for AI model interactions.+ description: Configuration management affects how language models are instantiated.generator:version: 1covers:- symbol: EngineConfigkind: interface- at: 'src/ai/providers.ts:L9-L25'+ at: 'src/ai/providers.ts:L17-L39'- symbol: ResolvedConfigkind: interface- at: 'src/ai/providers.ts:L28-L35'+ at: 'src/ai/providers.ts:L42-L55'- symbol: resolveConfigkind: function- at: 'src/ai/providers.ts:L43-L55'+ at: 'src/ai/providers.ts:L71-L106'+ - symbol: Json+ kind: type+ at: 'src/claude/settings-merge.ts:L1-L1'+ - symbol: hookCmd+ kind: function+ at: 'src/claude/settings-merge.ts:L7-L9'+ - symbol: graftBlocks+ kind: function+ at: 'src/claude/settings-merge.ts:L10-L17'+ - symbol: isGraftHookEntry+ kind: function+ at: 'src/claude/settings-merge.ts:L18-L20'+ - symbol: mergeGraftSettings+ kind: function+ at: 'src/claude/settings-merge.ts:L22-L55'---<!-- context:generated:start -->## Summary-This concept encompasses the management of user-facing configurations for the AI engine, allowing for customization of settings and components without code changes.+This concept involves managing and merging configuration settings for various AI model providers, ensuring that user-defined settings are correctly applied and integrated into the system.## Related-- configures [[ai-model-integration]] — Allows users to specify configurations for AI model interactions.+- configures [[llm-integration]] — Configuration management affects how language models are instantiated.<!-- context:generated:end -->## Notesdiff --git a/graft/deterministic-testing.md b/graft/deterministic-testing.mdnew file mode 100644index 00000000..7c16a36d--- /dev/null+++ b/graft/deterministic-testing.md@@ -0,0 +1,49 @@+---+name: Deterministic Testing+slug: deterministic-testing+type: concept+sources:+ - path: test/helpers.ts+ hash: e45af1d38d7c6d4abc804fc74e9ae4c3373cf78769c17b16b185c3ee0e2c3228+sources_digest: ddc97a2b9b5b7ea60c6a55b3c250ddc0dffa3b335c4b43ddc9152dc900f56744+links:+ - to: test-helpers+ relation: implements+ description: >-+ The test helpers embody the principles of deterministic testing by+ providing controlled environments.+generator:+ version: 1+covers:+ - symbol: PassthroughSummarizer+ kind: class+ at: 'test/helpers.ts:L9-L13'+ - symbol: summarize+ kind: method+ at: 'test/helpers.ts:L10-L12'+ - symbol: BracketSynthesizer+ kind: class+ at: 'test/helpers.ts:L21-L50'+ - symbol: synthesize+ kind: method+ at: 'test/helpers.ts:L22-L49'+ - symbol: ensure+ kind: function+ at: 'test/helpers.ts:L24-L31'+ - symbol: fakeProviders+ kind: function+ at: 'test/helpers.ts:L52-L54'+---+<!-- context:generated:start -->+## Summary++This concept emphasizes the importance of creating tests that are isolated from external dependencies, ensuring that tests can be reliably executed without variability in results.++## Related++- implements [[test-helpers]] — The test helpers embody the principles of deterministic testing by providing controlled environments.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/error-handling-and-reporting.md b/graft/error-handling-and-reporting.mdindex 9ab842b3..829e404e 100644--- a/graft/error-handling-and-reporting.md+++ b/graft/error-handling-and-reporting.md@@ -4,34 +4,81 @@ slug: error-handling-and-reportingtype: conceptsources:- path: bench/run.ts- hash: a0d2859628588f45ae31862f5f801d6219802449c23bbbdba9aa51b7b9febf47+ hash: fd4445eb0d6d3c1a8b994c7e4be42522c3214612a8499e4f76bfc10d0030f9da+ - path: src/engine.ts+ hash: 55e2191dd67d1e4369c2a872f1b908937bd6034ce6f8f4b03e6c86a059e271c7- path: src/graph/build.ts- hash: b18f5fc18dffd77771f39722eb19963c1188fd298cbb5cfd5d71ef8dc45658c6- - path: src/graph/check.ts- hash: 5358023fe498fb2878e3aa9b6756272c39926dda865c6495d8f33d13c5ceb376-sources_digest: 1386bf6efb7992fa69cd12a578fcd62b16f5332693ce2d7020e4050ba354f2f7+ hash: 10ae2a085b299a56cb90d41289a956065dd8eef358ae2abbc39db59b82a12dc9+sources_digest: 616914a6531c73b635ea2da8eba71b3f12bdae64d0e10c2618cdd7c1ebfc658blinks:- - to: graph-construction+ - to: benchmarking-systemrelation: validates- description: Ensures that errors in graph construction are reported effectively.+ description: >-+ Error handling is crucial for maintaining the integrity of benchmarking+ results.generator:version: 1covers:- symbol: Argskind: interface- at: 'bench/run.ts:L38-L44'+ at: 'bench/run.ts:L39-L45'- symbol: parseArgskind: function- at: 'bench/run.ts:L46-L66'+ at: 'bench/run.ts:L47-L67'- symbol: poolkind: function- at: 'bench/run.ts:L69-L80'+ at: 'bench/run.ts:L70-L81'- symbol: workerkind: function- at: 'bench/run.ts:L72-L77'+ at: 'bench/run.ts:L73-L78'- symbol: mainkind: function- at: 'bench/run.ts:L82-L202'+ at: 'bench/run.ts:L83-L204'+ - symbol: InitOptions+ kind: interface+ at: 'src/engine.ts:L28-L33'+ - symbol: CheckRunOptions+ kind: interface+ at: 'src/engine.ts:L35-L37'+ - symbol: GraphRunOptions+ kind: interface+ at: 'src/engine.ts:L39-L45'+ - symbol: Graft+ kind: class+ at: 'src/engine.ts:L47-L140'+ - symbol: constructor+ kind: method+ at: 'src/engine.ts:L50-L52'+ - symbol: init+ kind: method+ at: 'src/engine.ts:L55-L64'+ - symbol: check+ kind: method+ at: 'src/engine.ts:L67-L69'+ - symbol: checkGraph+ kind: method+ at: 'src/engine.ts:L72-L74'+ - symbol: graph+ kind: method+ at: 'src/engine.ts:L81-L88'+ - symbol: ask+ kind: method+ at: 'src/engine.ts:L95-L97'+ - symbol: chatModel+ kind: method+ at: 'src/engine.ts:L102-L119'+ - symbol: synthesizer+ kind: method+ at: 'src/engine.ts:L121-L123'+ - symbol: cruxSummarizer+ kind: method+ at: 'src/engine.ts:L126-L128'+ - symbol: summarizer+ kind: method+ at: 'src/engine.ts:L130-L132'+ - symbol: modelLabel+ kind: method+ at: 'src/engine.ts:L135-L139'- symbol: GraphBuildOptionskind: interfaceat: 'src/graph/build.ts:L23-L36'@@ -47,27 +94,15 @@ covers:- symbol: buildGraphkind: functionat: 'src/graph/build.ts:L78-L183'- - symbol: GraphCheckResult- kind: interface- at: 'src/graph/check.ts:L27-L37'- - symbol: GraphCheckOptions- kind: interface- at: 'src/graph/check.ts:L39-L41'- - symbol: checkGraph- kind: function- at: 'src/graph/check.ts:L43-L101'- - symbol: formatGraphCheckReport- kind: function- at: 'src/graph/check.ts:L104-L135'---<!-- context:generated:start -->## Summary-This concept focuses on the strategies employed to handle errors gracefully during benchmarking and graph construction, ensuring robust performance and user feedback.+This concept focuses on the strategies employed to handle errors gracefully throughout the system, ensuring that failures do not disrupt the user experience and that meaningful feedback is provided.## Related-- validates [[graph-construction]] — Ensures that errors in graph construction are reported effectively.+- validates [[benchmarking-system]] — Error handling is crucial for maintaining the integrity of benchmarking results.<!-- context:generated:end -->## Notesdiff --git a/graft/graph-construction.md b/graft/graph-construction.mddeleted file mode 100644index a0607b72..00000000--- a/graft/graph-construction.md+++ /dev/null@@ -1,129 +0,0 @@-----name: Graph Construction-slug: graph-construction-type: system-sources:- - path: src/context/build.ts- hash: 8c614e5dc6b1ef2d6949016ce7480099f95f021ea6b0882f2919397f97a68ce7- - path: src/context/check.ts- hash: 2444e1f4dfd78208a9b54942364ee1811d064459857c6d6cee178426e278d481- - path: src/graph/build.ts- hash: b18f5fc18dffd77771f39722eb19963c1188fd298cbb5cfd5d71ef8dc45658c6- - path: src/graph/check.ts- hash: 5358023fe498fb2878e3aa9b6756272c39926dda865c6495d8f33d13c5ceb376-sources_digest: 542278c320dfc3ba4690fe870e4222ebb3eb9fa87d9c1cd94780003d54e72141-links:- - to: code-summarization-and-synthesis- relation: depends_on- description: Relies on summarization and synthesis for node creation.- - to: graph-management- relation: part_of- description: Forms a core part of the graph management system.-generator:- version: 1-covers:- - symbol: BuildProgress- kind: interface- at: 'src/context/build.ts:L47-L52'- - symbol: BuildOptions- kind: interface- at: 'src/context/build.ts:L54-L64'- - symbol: BuildResult- kind: interface- at: 'src/context/build.ts:L66-L75'- - symbol: BuildCache- kind: interface- at: 'src/context/build.ts:L78-L81'- - symbol: FileWork- kind: interface- at: 'src/context/build.ts:L83-L87'- - symbol: NodeDraft- kind: interface- at: 'src/context/build.ts:L90-L97'- - symbol: buildContext- kind: function- at: 'src/context/build.ts:L99-L266'- - symbol: batchBySize- kind: function- at: 'src/context/build.ts:L269-L285'- - symbol: batchKey- kind: function- at: 'src/context/build.ts:L288-L295'- - symbol: registerName- kind: function- at: 'src/context/build.ts:L297-L300'- - symbol: resolveSlug- kind: function- at: 'src/context/build.ts:L302-L304'- - symbol: errMsg- kind: function- at: 'src/context/build.ts:L306-L308'- - symbol: cachePath- kind: function- at: 'src/context/build.ts:L310-L312'- - symbol: loadCache- kind: function- at: 'src/context/build.ts:L314-L325'- - symbol: saveCache- kind: function- at: 'src/context/build.ts:L327-L331'- - symbol: mapWithConcurrency- kind: function- at: 'src/context/build.ts:L334-L349'- - symbol: CheckResult- kind: interface- at: 'src/context/check.ts:L22-L30'- - symbol: CheckOptions- kind: interface- at: 'src/context/check.ts:L32-L35'- - symbol: checkContext- kind: function- at: 'src/context/check.ts:L37-L107'- - symbol: formatCheckReport- kind: function- at: 'src/context/check.ts:L110-L135'- - symbol: short- kind: function- at: 'src/context/check.ts:L137-L139'- - symbol: GraphBuildOptions- kind: interface- at: 'src/graph/build.ts:L23-L36'- - symbol: GraphBuildResult- kind: interface- at: 'src/graph/build.ts:L38-L51'- - symbol: listSourceFiles- kind: function- at: 'src/graph/build.ts:L54-L56'- - symbol: readGoModules- kind: function- at: 'src/graph/build.ts:L62-L76'- - symbol: buildGraph- kind: function- at: 'src/graph/build.ts:L78-L183'- - symbol: GraphCheckResult- kind: interface- at: 'src/graph/check.ts:L27-L37'- - symbol: GraphCheckOptions- kind: interface- at: 'src/graph/check.ts:L39-L41'- - symbol: checkGraph- kind: function- at: 'src/graph/check.ts:L43-L101'- - symbol: formatGraphCheckReport- kind: function- at: 'src/graph/check.ts:L104-L135'-----<!-- context:generated:start -->-## Summary--This component constructs a context graph from the code repository, managing the relationships between code elements and ensuring synchronization with the source code.--## Related--- depends on [[code-summarization-and-synthesis]] — Relies on summarization and synthesis for node creation.-- part of [[graph-management]] — Forms a core part of the graph management system.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-data-integrity.md b/graft/graph-data-integrity.mdnew file mode 100644index 00000000..1db1eadd--- /dev/null+++ b/graft/graph-data-integrity.md@@ -0,0 +1,34 @@+---+name: Graph Data Integrity+slug: graph-data-integrity+type: concept+sources:+ - path: test/graph-write.test.ts+ hash: cbbf9c3591519993ec89298444d34732f08eb16f90ba1c1cd33bd39d5512f9ff+sources_digest: 34c4a4eb40884a5f3072352f37d7efb647f89cb7fe8b9ba43d91eacbbad0c0c0+links:+ - to: graph-serialization+ relation: implements+ description: >-+ The serialization process must ensure that in-memory node objects remain+ unchanged.+generator:+ version: 1+covers:+ - symbol: makeNode+ kind: function+ at: 'test/graph-write.test.ts:L19-L35'+---+<!-- context:generated:start -->+## Summary++This principle focuses on maintaining the integrity of graph data during serialization and deserialization processes, ensuring that no unintended mutations occur.++## Related++- implements [[graph-serialization]] — The serialization process must ensure that in-memory node objects remain unchanged.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-extraction-and-loading.md b/graft/graph-extraction-and-loading.mdnew file mode 100644index 00000000..08dce6d9--- /dev/null+++ b/graft/graph-extraction-and-loading.md@@ -0,0 +1,179 @@+---+name: Graph Extraction and Loading+slug: graph-extraction-and-loading+type: system+sources:+ - path: src/graph/extract.ts+ hash: 8449958d4b5fd74c8eafeb488ae16cb60dcaf3e5fcaf1e3069cebf4cf9ef48d9+ - path: src/graph/load.ts+ hash: 115b75e947618be7755ac59310f898943cb4c1d8266bdf5a4a30fdca4956914a+ - path: src/graph/relations.ts+ hash: e62bc9934057bf232f86edcf942e71b0a2f4c44b57ffd78ddb935b85ab75aca8+ - path: src/graph/resolve.ts+ hash: 23e2e29f6e907f079f0d214ac6ce24b6105c403a51da30c2f4d39494f4b6b110+ - path: src/graph/types.ts+ hash: 27a9bdbef7783e5da94c860bc83525ef788e38a2176bc1184c8adbee539b1b51+sources_digest: acfd590d81e375dfc632bbf862a013b910daf352d7ff1739e70ef80fd841fcfa+links:+ - to: graph-representation+ relation: part_of+ description: This system is part of the overall graph representation architecture.+ - to: graph-representation+ relation: produces+ description: It produces structured graph representations from source code.+generator:+ version: 1+covers:+ - symbol: Language+ kind: type+ at: 'src/graph/extract.ts:L18-L18'+ - symbol: languageOf+ kind: function+ at: 'src/graph/extract.ts:L21-L28'+ - symbol: RawEdge+ kind: interface+ at: 'src/graph/extract.ts:L34-L45'+ - symbol: ExtractResult+ kind: interface+ at: 'src/graph/extract.ts:L47-L50'+ - symbol: searchBody+ kind: function+ at: 'src/graph/extract.ts:L67-L70'+ - symbol: fileResidual+ kind: function+ at: 'src/graph/extract.ts:L78-L89'+ - symbol: WalkCtx+ kind: interface+ at: 'src/graph/extract.ts:L136-L147'+ - symbol: DefDescriptor+ kind: interface+ at: 'src/graph/extract.ts:L150-L156'+ - symbol: parseSource+ kind: function+ at: 'src/graph/extract.ts:L164-L166'+ - symbol: extractFile+ kind: function+ at: 'src/graph/extract.ts:L168-L209'+ - symbol: walk+ kind: function+ at: 'src/graph/extract.ts:L211-L278'+ - symbol: describe+ kind: function+ at: 'src/graph/extract.ts:L282-L313'+ - symbol: describeGo+ kind: function+ at: 'src/graph/extract.ts:L318-L356'+ - symbol: goReceiverType+ kind: function+ at: 'src/graph/extract.ts:L360-L366'+ - symbol: goExported+ kind: function+ at: 'src/graph/extract.ts:L370-L374'+ - symbol: heritageEdges+ kind: function+ at: 'src/graph/extract.ts:L376-L403'+ - symbol: calleeName+ kind: function+ at: 'src/graph/extract.ts:L405-L428'+ - symbol: pyReceiver+ kind: function+ at: 'src/graph/extract.ts:L432-L441'+ - symbol: tsReceiver+ kind: function+ at: 'src/graph/extract.ts:L444-L454'+ - symbol: isImport+ kind: function+ at: 'src/graph/extract.ts:L456-L461'+ - symbol: importSpecifier+ kind: function+ at: 'src/graph/extract.ts:L463-L479'+ - symbol: clean+ kind: function+ at: 'src/graph/extract.ts:L482-L489'+ - symbol: tsExported+ kind: function+ at: 'src/graph/extract.ts:L492-L499'+ - symbol: CacheEntry+ kind: interface+ at: 'src/graph/load.ts:L31-L35'+ - symbol: __resetParseCounts+ kind: function+ at: 'src/graph/load.ts:L45-L48'+ - symbol: statOf+ kind: function+ at: 'src/graph/load.ts:L50-L57'+ - symbol: loadCached+ kind: function+ at: 'src/graph/load.ts:L59-L81'+ - symbol: loadGraphCached+ kind: function+ at: 'src/graph/load.ts:L86-L91'+ - symbol: loadAskIndexCached+ kind: function+ at: 'src/graph/load.ts:L95-L100'+ - symbol: GoModule+ kind: interface+ at: 'src/graph/resolve.ts:L39-L42'+ - symbol: ResolveOptions+ kind: interface+ at: 'src/graph/resolve.ts:L44-L49'+ - symbol: resolveEdges+ kind: function+ at: 'src/graph/resolve.ts:L51-L140'+ - symbol: add+ kind: function+ at: 'src/graph/resolve.ts:L97-L102'+ - symbol: push+ kind: function+ at: 'src/graph/resolve.ts:L142-L146'+ - symbol: resolveName+ kind: function+ at: 'src/graph/resolve.ts:L152-L164'+ - symbol: resolveTypedMember+ kind: function+ at: 'src/graph/resolve.ts:L180-L213'+ - symbol: resolveImport+ kind: function+ at: 'src/graph/resolve.ts:L219-L231'+ - symbol: resolveGoImport+ kind: function+ at: 'src/graph/resolve.ts:L243-L258'+ - symbol: Kind+ kind: type+ at: 'src/graph/types.ts:L15-L23'+ - symbol: Confidence+ kind: type+ at: 'src/graph/types.ts:L26-L26'+ - symbol: SummaryState+ kind: type+ at: 'src/graph/types.ts:L29-L29'+ - symbol: Crux+ kind: interface+ at: 'src/graph/types.ts:L33-L36'+ - symbol: NodeV1+ kind: interface+ at: 'src/graph/types.ts:L38-L63'+ - symbol: Relation+ kind: type+ at: 'src/graph/types.ts:L65-L71'+ - symbol: EdgeV1+ kind: interface+ at: 'src/graph/types.ts:L73-L78'+ - symbol: GraphV1+ kind: interface+ at: 'src/graph/types.ts:L80-L89'+---+<!-- context:generated:start -->+## Summary++This component encompasses the extraction and loading of source code into a structured graph format, utilizing tree-sitter for parsing and caching mechanisms to optimize performance. It includes functionalities for tier-1 extraction, caching of graphs, and efficient loading of ask indices, ensuring that changes in source files are accurately reflected in the graph representation.++## Related++- part of [[graph-representation]] — This system is part of the overall graph representation architecture.+- produces [[graph-representation]] — It produces structured graph representations from source code.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-management.md b/graft/graph-management.mddeleted file mode 100644index ac04a166..00000000--- a/graft/graph-management.md+++ /dev/null@@ -1,44 +0,0 @@-----name: Graph Management-slug: graph-management-type: system-sources:- - path: src/graph/write.ts- hash: 55dd6ea840135ade4db7f49042234bee0db07a9c8c959ab57767deb8bebc6345-sources_digest: fa6cd161fd547a03ecad2649fbb2b6094b5a6a64b10dcc1bdd6244e5157d4d48-links:- - to: graph-construction- relation: part_of- description: Supports the construction of the context graph.-generator:- version: 1-covers:- - symbol: wiringPath- kind: function- at: 'src/graph/write.ts:L20-L22'- - symbol: readGraph- kind: function- at: 'src/graph/write.ts:L28-L34'- - symbol: writeGraph- kind: function- at: 'src/graph/write.ts:L36-L46'- - symbol: stripBodyText- kind: function- at: 'src/graph/write.ts:L57-L61'- - symbol: edgeOrder- kind: function- at: 'src/graph/write.ts:L63-L69'-----<!-- context:generated:start -->-## Summary--This component manages the on-disk representation of the context graph, handling serialization, reading, and writing of graph data while ensuring data integrity and versioning.--## Related--- part of [[graph-construction]] — Supports the construction of the context graph.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-ranking.md b/graft/graph-ranking.mdnew file mode 100644index 00000000..94172aaa--- /dev/null+++ b/graft/graph-ranking.md@@ -0,0 +1,46 @@+---+name: Graph Ranking+slug: graph-ranking+type: system+sources:+ - path: test/graphrank.test.ts+ hash: 9b6450a705fd5bbe7ddead7ae29f87fcb839599d34b6bd0c8ebcb0091ee70c47+sources_digest: 891283b4808759d18bf39767763a60e2529b6e7559323f4115f409ab61912eaa+links:+ - to: graph-traversal-and-impact-analysis+ relation: depends_on+ description: >-+ The ranking algorithm relies on the graph structure established by the+ traversal utilities.+generator:+ version: 1+covers:+ - symbol: node+ kind: function+ at: 'test/graphrank.test.ts:L23-L38'+ - symbol: edge+ kind: function+ at: 'test/graphrank.test.ts:L39-L41'+ - symbol: graphOf+ kind: function+ at: 'test/graphrank.test.ts:L42-L48'+ - symbol: makeCollisionFixture+ kind: function+ at: 'test/graphrank.test.ts:L128-L138'+ - symbol: rank+ kind: function+ at: 'test/graphrank.test.ts:L140-L141'+---+<!-- context:generated:start -->+## Summary++This component implements the personalized PageRank algorithm to rank nodes based on their connectivity, enhancing the query results by prioritizing relevant nodes in the graph.++## Related++- depends on [[graph-traversal-and-impact-analysis]] — The ranking algorithm relies on the graph structure established by the traversal utilities.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-representation.md b/graft/graph-representation.mdnew file mode 100644index 00000000..43afe138--- /dev/null+++ b/graft/graph-representation.md@@ -0,0 +1,61 @@+---+name: Graph Representation+slug: graph-representation+type: system+sources:+ - path: src/graph/relations.ts+ hash: e62bc9934057bf232f86edcf942e71b0a2f4c44b57ffd78ddb935b85ab75aca8+ - path: src/graph/types.ts+ hash: 27a9bdbef7783e5da94c860bc83525ef788e38a2176bc1184c8adbee539b1b51+sources_digest: 45b44b0500854924c7bf69043e5f45af360c55776bcf957442700620d7a3b1f4+links:+ - to: graph-extraction-and-loading+ relation: depends_on+ description: >-+ This system relies on the types defined here for graph extraction and+ loading.+ - to: graph-traversal-and-analysis+ relation: part_of+ description: It serves as the foundational structure for graph traversal and analysis.+generator:+ version: 1+covers:+ - symbol: Kind+ kind: type+ at: 'src/graph/types.ts:L15-L23'+ - symbol: Confidence+ kind: type+ at: 'src/graph/types.ts:L26-L26'+ - symbol: SummaryState+ kind: type+ at: 'src/graph/types.ts:L29-L29'+ - symbol: Crux+ kind: interface+ at: 'src/graph/types.ts:L33-L36'+ - symbol: NodeV1+ kind: interface+ at: 'src/graph/types.ts:L38-L63'+ - symbol: Relation+ kind: type+ at: 'src/graph/types.ts:L65-L71'+ - symbol: EdgeV1+ kind: interface+ at: 'src/graph/types.ts:L73-L78'+ - symbol: GraphV1+ kind: interface+ at: 'src/graph/types.ts:L80-L89'+---+<!-- context:generated:start -->+## Summary++This component defines the schema and types for the graph representation, including nodes and edges that represent programming constructs and their relationships. It ensures that the graph can accommodate multiple programming languages and maintains a clear structure for graph traversal and manipulation.++## Related++- depends on [[graph-extraction-and-loading]] — This system relies on the types defined here for graph extraction and loading.+- part of [[graph-traversal-and-analysis]] — It serves as the foundational structure for graph traversal and analysis.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-serialization.md b/graft/graph-serialization.mdnew file mode 100644index 00000000..c37567b2--- /dev/null+++ b/graft/graph-serialization.md@@ -0,0 +1,34 @@+---+name: Graph Serialization+slug: graph-serialization+type: system+sources:+ - path: test/graph-write.test.ts+ hash: cbbf9c3591519993ec89298444d34732f08eb16f90ba1c1cd33bd39d5512f9ff+sources_digest: 34c4a4eb40884a5f3072352f37d7efb647f89cb7fe8b9ba43d91eacbbad0c0c0+links:+ - to: graph-traversal-and-impact-analysis+ relation: uses+ description: >-+ The serialization process must accurately reflect the relationships+ defined by the graph traversal utilities.+generator:+ version: 1+covers:+ - symbol: makeNode+ kind: function+ at: 'test/graph-write.test.ts:L19-L35'+---+<!-- context:generated:start -->+## Summary++This component manages the serialization and deserialization of graph data, ensuring that the in-memory representation remains intact while providing efficient storage and retrieval mechanisms.++## Related++- uses [[graph-traversal-and-impact-analysis]] — The serialization process must accurately reflect the relationships defined by the graph traversal utilities.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-synchronization.md b/graft/graph-synchronization.mdnew file mode 100644index 00000000..ac3bdc10--- /dev/null+++ b/graft/graph-synchronization.md@@ -0,0 +1,58 @@+---+name: Graph Synchronization+slug: graph-synchronization+type: concept+sources:+ - path: src/context/check.ts+ hash: 2444e1f4dfd78208a9b54942364ee1811d064459857c6d6cee178426e278d481+ - path: src/graph/check.ts+ hash: 5358023fe498fb2878e3aa9b6756272c39926dda865c6495d8f33d13c5ceb376+sources_digest: 9a6d9714cc8b93725ff7e5702bd59dca1a96a6a3ebb7cec5c2f2e7e72eb9f093+links:+ - to: benchmarking-system+ relation: validates+ description: Synchronization checks are part of the overall benchmarking process.+generator:+ version: 1+covers:+ - symbol: CheckResult+ kind: interface+ at: 'src/context/check.ts:L22-L30'+ - symbol: CheckOptions+ kind: interface+ at: 'src/context/check.ts:L32-L35'+ - symbol: checkContext+ kind: function+ at: 'src/context/check.ts:L37-L107'+ - symbol: formatCheckReport+ kind: function+ at: 'src/context/check.ts:L110-L135'+ - symbol: short+ kind: function+ at: 'src/context/check.ts:L137-L139'+ - symbol: GraphCheckResult+ kind: interface+ at: 'src/graph/check.ts:L27-L37'+ - symbol: GraphCheckOptions+ kind: interface+ at: 'src/graph/check.ts:L39-L41'+ - symbol: checkGraph+ kind: function+ at: 'src/graph/check.ts:L43-L101'+ - symbol: formatGraphCheckReport+ kind: function+ at: 'src/graph/check.ts:L104-L135'+---+<!-- context:generated:start -->+## Summary++This concept addresses the verification of synchronization between the context graph and the source code, ensuring that the graph accurately reflects the current state of the codebase.++## Related++- validates [[benchmarking-system]] — Synchronization checks are part of the overall benchmarking process.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-traversal-and-analysis.md b/graft/graph-traversal-and-analysis.mdnew file mode 100644index 00000000..839eb869--- /dev/null+++ b/graft/graph-traversal-and-analysis.md@@ -0,0 +1,171 @@+---+name: Graph Traversal and Analysis+slug: graph-traversal-and-analysis+type: system+sources:+ - path: src/graph/traverse-cli.ts+ hash: 080714fc91e5caefe4548e87c071b2010fdc593a670366db941d9fd2907b08e2+ - path: src/graph/traverse.ts+ hash: dd38bef08a175c1db6751823f7f6f1eaae3952227737b063373987f69c52d7fa+ - path: src/search/grep-cli.ts+ hash: 70bcb32d3ae5e4e9e39eb8b07151da7145a08756015e91f215edcadce5bddef8+ - path: src/search/grep.ts+ hash: e0ba3aaa565892e2772e4de0492931a568fc3f3724f8fca44b2a188a24e5eeb4+sources_digest: 0d510fdb8ad732a39d2c989024794702526f50a3a8555dce95314cb5b80d3a0a+links:+ - to: graph-extraction-and-loading+ relation: uses+ description: It utilizes the extracted graph data for traversal and analysis.+ - to: graph-representation+ relation: depends_on+ description: It depends on the graph representation defined in the previous component.+generator:+ version: 1+covers:+ - symbol: TraverseKind+ kind: type+ at: 'src/graph/traverse-cli.ts:L17-L17'+ - symbol: TraverseCliOptions+ kind: interface+ at: 'src/graph/traverse-cli.ts:L19-L26'+ - symbol: edgesFor+ kind: function+ at: 'src/graph/traverse-cli.ts:L31-L35'+ - symbol: headerOf+ kind: function+ at: 'src/graph/traverse-cli.ts:L41-L43'+ - symbol: hitLine+ kind: function+ at: 'src/graph/traverse-cli.ts:L45-L50'+ - symbol: looseNoteFor+ kind: function+ at: 'src/graph/traverse-cli.ts:L54-L58'+ - symbol: SymbolJson+ kind: interface+ at: 'src/graph/traverse-cli.ts:L60-L66'+ - symbol: MatchJson+ kind: interface+ at: 'src/graph/traverse-cli.ts:L68-L72'+ - symbol: HitJson+ kind: interface+ at: 'src/graph/traverse-cli.ts:L74-L82'+ - symbol: symbolJson+ kind: function+ at: 'src/graph/traverse-cli.ts:L84-L86'+ - symbol: hitJson+ kind: function+ at: 'src/graph/traverse-cli.ts:L88-L97'+ - symbol: runTraverseCommand+ kind: function+ at: 'src/graph/traverse-cli.ts:L105-L155'+ - symbol: SymbolMatch+ kind: interface+ at: 'src/graph/traverse.ts:L19-L21'+ - symbol: ResolveSymbolOptions+ kind: interface+ at: 'src/graph/traverse.ts:L23-L26'+ - symbol: resolveSymbol+ kind: function+ at: 'src/graph/traverse.ts:L47-L72'+ - symbol: symbolMatches+ kind: function+ at: 'src/graph/traverse.ts:L74-L83'+ - symbol: EdgeHit+ kind: interface+ at: 'src/graph/traverse.ts:L88-L93'+ - symbol: callersOf+ kind: function+ at: 'src/graph/traverse.ts:L96-L104'+ - symbol: calleesOf+ kind: function+ at: 'src/graph/traverse.ts:L107-L115'+ - symbol: impactOf+ kind: function+ at: 'src/graph/traverse.ts:L123-L125'+ - symbol: impactOfMany+ kind: function+ at: 'src/graph/traverse.ts:L141-L172'+ - symbol: symbolsInFile+ kind: function+ at: 'src/graph/traverse.ts:L176-L178'+ - symbol: impactOfFile+ kind: function+ at: 'src/graph/traverse.ts:L189-L191'+ - symbol: GrepCliOptions+ kind: interface+ at: 'src/search/grep-cli.ts:L15-L22'+ - symbol: groupHeader+ kind: function+ at: 'src/search/grep-cli.ts:L24-L27'+ - symbol: formatGroup+ kind: function+ at: 'src/search/grep-cli.ts:L29-L33'+ - symbol: formatGrepHeader+ kind: function+ at: 'src/search/grep-cli.ts:L36-L39'+ - symbol: truncationNote+ kind: function+ at: 'src/search/grep-cli.ts:L42-L49'+ - symbol: formatGrepResult+ kind: function+ at: 'src/search/grep-cli.ts:L53-L59'+ - symbol: zeroHitNote+ kind: function+ at: 'src/search/grep-cli.ts:L69-L74'+ - symbol: runGrepCommand+ kind: function+ at: 'src/search/grep-cli.ts:L83-L112'+ - symbol: GrepHit+ kind: interface+ at: 'src/search/grep.ts:L17-L21'+ - symbol: GrepSymbolRef+ kind: interface+ at: 'src/search/grep.ts:L23-L31'+ - symbol: GrepGroup+ kind: interface+ at: 'src/search/grep.ts:L33-L42'+ - symbol: GrepResult+ kind: interface+ at: 'src/search/grep.ts:L44-L58'+ - symbol: GrepOptions+ kind: interface+ at: 'src/search/grep.ts:L60-L69'+ - symbol: escapeRegExp+ kind: function+ at: 'src/search/grep.ts:L75-L77'+ - symbol: spanBounds+ kind: function+ at: 'src/search/grep.ts:L79-L83'+ - symbol: SymbolSpan+ kind: interface+ at: 'src/search/grep.ts:L85-L89'+ - symbol: symbolsOf+ kind: function+ at: 'src/search/grep.ts:L93-L102'+ - symbol: enclosingSymbol+ kind: function+ at: 'src/search/grep.ts:L108-L115'+ - symbol: computeInDegree+ kind: function+ at: 'src/search/grep.ts:L119-L126'+ - symbol: toSymbolRef+ kind: function+ at: 'src/search/grep.ts:L128-L131'+ - symbol: grepGraph+ kind: function+ at: 'src/search/grep.ts:L133-L195'+---+<!-- context:generated:start -->+## Summary++This component provides core functionalities for traversing the graph structure, enabling symbol resolution, impact analysis, and dependency tracking within the codebase. It includes CLI tools for user interaction and ensures that graph traversal is efficient and testable.++## Related++- uses [[graph-extraction-and-loading]] — It utilizes the extracted graph data for traversal and analysis.+- depends on [[graph-representation]] — It depends on the graph representation defined in the previous component.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/graph-traversal-and-impact-analysis.md b/graft/graph-traversal-and-impact-analysis.mdnew file mode 100644index 00000000..95e57b19--- /dev/null+++ b/graft/graph-traversal-and-impact-analysis.md@@ -0,0 +1,55 @@+---+name: Graph Traversal and Impact Analysis+slug: graph-traversal-and-impact-analysis+type: system+sources:+ - path: test/graph-traverse.test.ts+ hash: 9683b55f739af4afbb3840cee333eed0b1869494b66fe9cddfae1153df246947+sources_digest: 488464ccc2ad9ea80719012d014ea2836db6f60a1b0335e18545affa4a04a7b2+links:+ - to: graph-ranking+ relation: depends_on+ description: >-+ Impact analysis relies on the graph structure, which is influenced by the+ ranking of nodes.+ - to: graph-serialization+ relation: depends_on+ description: >-+ The graph traversal utilities are essential for validating the serialized+ output of the graph.+generator:+ version: 1+covers:+ - symbol: nodeStub+ kind: function+ at: 'test/graph-traverse.test.ts:L15-L30'+ - symbol: edge+ kind: function+ at: 'test/graph-traverse.test.ts:L32-L34'+ - symbol: graphOf+ kind: function+ at: 'test/graph-traverse.test.ts:L36-L42'+ - symbol: baseGraph+ kind: function+ at: 'test/graph-traverse.test.ts:L57-L66'+ - symbol: diamondGraph+ kind: function+ at: 'test/graph-traverse.test.ts:L167-L179'+ - symbol: fileAndSymbolGraph+ kind: function+ at: 'test/graph-traverse.test.ts:L221-L231'+---+<!-- context:generated:start -->+## Summary++This component encompasses the core functionality for graph traversal, symbol resolution, and impact analysis, providing essential utilities for understanding node relationships and their implications within the graph structure.++## Related++- depends on [[graph-ranking]] — Impact analysis relies on the graph structure, which is influenced by the ranking of nodes.+- depends on [[graph-serialization]] — The graph traversal utilities are essential for validating the serialized output of the graph.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/visualization-layer.md b/graft/graph-visualization.mdsimilarity index 89%rename from graft/visualization-layer.mdrename to graft/graph-visualization.mdindex 573614e6..27c41c15 100644--- a/graft/visualization-layer.md+++ b/graft/graph-visualization.md@@ -1,6 +1,6 @@----name: Visualization Layer-slug: visualization-layer+name: Graph Visualization+slug: graph-visualizationtype: systemsources:- path: viewer/data.ts@@ -15,9 +15,11 @@ sources:hash: d66e0157f4c2a1525c16505306eb3aabce82565c3d0e56199ea5b7a860290b01sources_digest: fd0623540e7f7eed9942e3db2bc219f9a08b3814ac219dfb2b9a74f8c1aea966links:- - to: graph-management- relation: depends_on- description: Utilizes the graph data for rendering visualizations.+ - to: graph-traversal-and-impact-analysis+ relation: uses+ description: >-+ The visualization relies on the traversal utilities to accurately+ represent node relationships.generator:version: 1covers:@@ -199,11 +201,11 @@ covers:<!-- context:generated:start -->## Summary-This component provides the visualization tools for the context graph, enabling users to interact with and explore the graph structure through a web interface.+This component is responsible for rendering and displaying the graph data, providing interactive visualizations that allow users to explore node relationships and details effectively.## Related-- depends on [[graph-management]] — Utilizes the graph data for rendering visualizations.+- uses [[graph-traversal-and-impact-analysis]] — The visualization relies on the traversal utilities to accurately represent node relationships.<!-- context:generated:end -->## Notesdiff --git a/graft/host-configuration-management.md b/graft/host-configuration-management.mdnew file mode 100644index 00000000..e09a3d49--- /dev/null+++ b/graft/host-configuration-management.md@@ -0,0 +1,57 @@+---+name: Host Configuration Management+slug: host-configuration-management+type: system+sources:+ - path: test/hosts-codex-hooks.test.ts+ hash: ed49a8a106eeb458ad2dd071071cefae17dd4d0eabd1b74006047feadef9a89a+ - path: test/hosts-init.test.ts+ hash: 56f8988468cb716296b40c939bf58d079015d135fcb3f2c1481e64bce7f67324+ - path: test/hosts-mcp-config.test.ts+ hash: 5b3ec5afd61079f051d8063f06701ddac608f48b706e72f9ee607e8da673fb06+ - path: test/hosts-registry.test.ts+ hash: 6490cbdc54b870d670adf28b5b469e07360a474073b08d692601ef1c4b7ea47e+ - path: test/hosts-sections.test.ts+ hash: a780abe63074737d40bcd556df06b7b541d2694df75c307daabd280f64f9dba4+sources_digest: bc0c33ccee8f4a029f0fb4af261138907cc7b85f4f063f18ef3cb49d03076555+links:+ - to: graph-serialization+ relation: produces+ description: >-+ Host configurations may influence the structure and serialization of the+ graph.+generator:+ version: 1+covers:+ - symbol: fresh+ kind: function+ at: 'test/hosts-codex-hooks.test.ts:L8-L8'+ - symbol: fresh+ kind: function+ at: 'test/hosts-init.test.ts:L9-L9'+ - symbol: fresh+ kind: function+ at: 'test/hosts-mcp-config.test.ts:L8-L8'+ - symbol: probeFor+ kind: function+ at: 'test/hosts-registry.test.ts:L9-L14'+ - symbol: fresh+ kind: function+ at: 'test/hosts-registry.test.ts:L15-L15'+ - symbol: fresh+ kind: function+ at: 'test/hosts-sections.test.ts:L8-L8'+---+<!-- context:generated:start -->+## Summary++This component manages the initialization and configuration of hosts within the repository, ensuring that host-specific settings are correctly applied and maintained across different environments.++## Related++- produces [[graph-serialization]] — Host configurations may influence the structure and serialization of the graph.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/host-management-and-configuration.md b/graft/host-management-and-configuration.mdnew file mode 100644index 00000000..25b50283--- /dev/null+++ b/graft/host-management-and-configuration.md@@ -0,0 +1,131 @@+---+name: Host Management and Configuration+slug: host-management-and-configuration+type: system+sources:+ - path: src/hosts/codex-hooks.ts+ hash: 0b9ba9ba677876d1adf4ce8d05aa534cddfbdeb7060ed11a92111a41a76d1512+ - path: src/hosts/init.ts+ hash: cd3ef307f207a48b82fa81ea55e34fdc97b8663612ad639a3256336d5531afa0+ - path: src/hosts/instructions.ts+ hash: 1dddea660f4d5e65952faf2beee42f04153ccab893658e75bda1dce6c0245b18+ - path: src/hosts/mcp-config.ts+ hash: c3a3dea18371806ed352e7cab582265db2341b7d4ea5797578e495b512a9b0b3+ - path: src/hosts/registry.ts+ hash: 0a8a2b82f0e4e1010943eb69d2eee7d9c4549f884967d5af1b8317c38ef99c18+ - path: src/hosts/sections.ts+ hash: f172618889d5a02683032df8c69dd85b71c00c72a8b76958305ade22d6cda714+sources_digest: da51b260a6b5e65f9dc1fa578e44a81309e6379f05f575b42378a1a646d63bb7+links:+ - to: graph-extraction-and-loading+ relation: part_of+ description: >-+ This system is part of the overall architecture that supports host+ interactions.+ - to: graph-representation+ relation: configures+ description: >-+ It configures the behavior of the graph representation based on host+ settings.+generator:+ version: 1+covers:+ - symbol: HookWrite+ kind: interface+ at: 'src/hosts/codex-hooks.ts:L11-L15'+ - symbol: dirExists+ kind: function+ at: 'src/hosts/codex-hooks.ts:L17-L19'+ - symbol: writeOwned+ kind: function+ at: 'src/hosts/codex-hooks.ts:L21-L31'+ - symbol: isGraftEntry+ kind: function+ at: 'src/hosts/codex-hooks.ts:L33-L35'+ - symbol: installCodexHooks+ kind: function+ at: 'src/hosts/codex-hooks.ts:L37-L74'+ - symbol: HostsInitResult+ kind: interface+ at: 'src/hosts/init.ts:L14-L20'+ - symbol: probeFor+ kind: function+ at: 'src/hosts/init.ts:L22-L27'+ - symbol: writeOwned+ kind: function+ at: 'src/hosts/init.ts:L29-L35'+ - symbol: runHostsInit+ kind: function+ at: 'src/hosts/init.ts:L37-L72'+ - symbol: instructionBody+ kind: function+ at: 'src/hosts/instructions.ts:L6-L42'+ - symbol: cursorRule+ kind: function+ at: 'src/hosts/instructions.ts:L44-L51'+ - symbol: kiroSteering+ kind: function+ at: 'src/hosts/instructions.ts:L53-L59'+ - symbol: windsurfRule+ kind: function+ at: 'src/hosts/instructions.ts:L61-L64'+ - symbol: McpWrite+ kind: interface+ at: 'src/hosts/mcp-config.ts:L10-L14'+ - symbol: dirExists+ kind: function+ at: 'src/hosts/mcp-config.ts:L19-L21'+ - symbol: mergeJsonKey+ kind: function+ at: 'src/hosts/mcp-config.ts:L23-L43'+ - symbol: upsertCodexToml+ kind: function+ at: 'src/hosts/mcp-config.ts:L45-L54'+ - symbol: registerMcpConfigs+ kind: function+ at: 'src/hosts/mcp-config.ts:L56-L87'+ - symbol: DetectProbe+ kind: interface+ at: 'src/hosts/registry.ts:L12-L16'+ - symbol: HostTarget+ kind: interface+ at: 'src/hosts/registry.ts:L18-L26'+ - symbol: hostIds+ kind: function+ at: 'src/hosts/registry.ts:L82-L84'+ - symbol: detectHosts+ kind: function+ at: 'src/hosts/registry.ts:L86-L88'+ - symbol: UpsertAction+ kind: type+ at: 'src/hosts/sections.ts:L11-L11'+ - symbol: LineEnding+ kind: type+ at: 'src/hosts/sections.ts:L13-L13'+ - symbol: fencedBlock+ kind: function+ at: 'src/hosts/sections.ts:L15-L21'+ - symbol: detectEol+ kind: function+ at: 'src/hosts/sections.ts:L24-L26'+ - symbol: markerLineIndex+ kind: function+ at: 'src/hosts/sections.ts:L29-L34'+ - symbol: upsertSection+ kind: function+ at: 'src/hosts/sections.ts:L36-L67'+---+<!-- context:generated:start -->+## Summary++This component manages the configuration and initialization of various coding hosts, allowing the Graft system to interact with different environments. It includes functionality for setting up hooks, managing instruction files, and ensuring that the environment is correctly configured for user interactions.++## Related++- part of [[graph-extraction-and-loading]] — This system is part of the overall architecture that supports host interactions.+- configures [[graph-representation]] — It configures the behavior of the graph representation based on host settings.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/idempotent-host-initialization.md b/graft/idempotent-host-initialization.mdnew file mode 100644index 00000000..5acc73f0--- /dev/null+++ b/graft/idempotent-host-initialization.md@@ -0,0 +1,34 @@+---+name: Idempotent Host Initialization+slug: idempotent-host-initialization+type: concept+sources:+ - path: test/hosts-init.test.ts+ hash: 56f8988468cb716296b40c939bf58d079015d135fcb3f2c1481e64bce7f67324+sources_digest: f7070057632565b4c1a7232ff4218cdefd56e5b26dacbe4e874e1c73a6ffb332+links:+ - to: host-configuration-management+ relation: implements+ description: >-+ The host initialization process must adhere to idempotency to maintain+ configuration integrity.+generator:+ version: 1+covers:+ - symbol: fresh+ kind: function+ at: 'test/hosts-init.test.ts:L9-L9'+---+<!-- context:generated:start -->+## Summary++This design principle ensures that host initialization functions do not alter already configured repositories, allowing for safe repeated executions without unintended side effects.++## Related++- implements [[host-configuration-management]] — The host initialization process must adhere to idempotency to maintain configuration integrity.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/judge.md b/graft/judge.mdnew file mode 100644index 00000000..2c0d02c6--- /dev/null+++ b/graft/judge.md@@ -0,0 +1,41 @@+---+name: Judge+slug: judge+type: system+sources:+ - path: bench/judge.ts+ hash: bb48a8012b929bc0237f4d900d0ab7aa9a98f96777d72a89ce5305c6c57e6c47+sources_digest: b7c143d704da46109b37f03f603d29dcdd327ce19900ddfdf1b58ac4ead126ba+links:+ - to: llm-integration+ relation: uses+ description: The judge uses language models to evaluate answers.+generator:+ version: 1+covers:+ - symbol: Verdict+ kind: interface+ at: 'bench/judge.ts:L18-L24'+ - symbol: JudgeInput+ kind: interface+ at: 'bench/judge.ts:L26-L32'+ - symbol: extractJson+ kind: function+ at: 'bench/judge.ts:L35-L49'+ - symbol: judge+ kind: function+ at: 'bench/judge.ts:L51-L86'+---+<!-- context:generated:start -->+## Summary++The judge component evaluates the correctness of the agent's responses against reference answers, utilizing a two-layer scoring system that includes keyword checks and model evaluations. It ensures robust and consistent assessment of AI-generated answers.++## Related++- uses [[llm-integration]] — The judge uses language models to evaluate answers.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/llm-integration.md b/graft/llm-integration.mdnew file mode 100644index 00000000..51169ffc--- /dev/null+++ b/graft/llm-integration.md@@ -0,0 +1,36 @@+---+name: LLM Integration+slug: llm-integration+type: system+sources:+ - path: bench/llm.ts+ hash: 6fc86553ce48879cb28b411747fe3ffaa2ad5c269e5de50d83e4ed8b629cae2b+sources_digest: 4f4e246df7420566c35c5613d87662927000d8a548af5960275c64cc0a6e125e+links:+ - to: agent+ relation: produces+ description: The LLM integration provides models that the agent uses for processing.+ - to: judge+ relation: produces+ description: The LLM integration provides models that the judge uses for evaluation.+generator:+ version: 1+covers:+ - symbol: makeChatModel+ kind: function+ at: 'bench/llm.ts:L16-L28'+---+<!-- context:generated:start -->+## Summary++This component serves as the integration layer for various language models used in the benchmarking process, allowing for flexible configuration and interaction with different AI providers. It ensures that models are correctly instantiated and utilized across the system.++## Related++- produces [[agent]] — The LLM integration provides models that the agent uses for processing.+- produces [[judge]] — The LLM integration provides models that the judge uses for evaluation.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/manifest.json b/graft/manifest.jsonindex 124d7a4f..d537a2dc 100644--- a/graft/manifest.json+++ b/graft/manifest.json@@ -1,35 +1,39 @@{"version": 1,- "model": "openrouter:openai/gpt-4o-mini",- "repoDigest": "f7db46e361715e61d60229d1747926ce09ebe17ebf62a16ab251ebe72f7bc843",+ "model": "openai:openai/gpt-4o-mini",+ "repoDigest": "35887975b3454c31ed185360b52aa4b8e96a0a27c5422961a28cde187f125978","files": [{"path": "bench/agent.ts",- "hash": "e10d64f913c9517cef84cce58ea042d71bed3e94182c791245170eca54060e31"+ "hash": "34a496d38f2dfc14688cb4f0981262d79dacef165bd1a4f9874b94c31e1819e9"},{"path": "bench/judge.ts",- "hash": "94c222341b066e4f3134b3d9d3f30f31b9ffe7b92967086b07c58f297d349936"+ "hash": "bb48a8012b929bc0237f4d900d0ab7aa9a98f96777d72a89ce5305c6c57e6c47"},{"path": "bench/llm.ts",- "hash": "6c0d2a02ac6aa86de94f779355020700a4d9016e2f4b431bf75560e1d3c51229"+ "hash": "6fc86553ce48879cb28b411747fe3ffaa2ad5c269e5de50d83e4ed8b629cae2b"},{"path": "bench/report.ts",- "hash": "775be8c40a8e4172521bba8f6a1f026fa23c4d24b9b5225da3ed5b745077a5b0"+ "hash": "17c0be550f9712165177d070f58cbe7a0f60fcb2c1dc5830eb1a4dde97ec12f3"},{"path": "bench/run.ts",- "hash": "a0d2859628588f45ae31862f5f801d6219802449c23bbbdba9aa51b7b9febf47"+ "hash": "fd4445eb0d6d3c1a8b994c7e4be42522c3214612a8499e4f76bfc10d0030f9da"},{"path": "bench/selfcheck.ts",- "hash": "0eaf577938e20fa27d9cd0157bc8843fdc37165d85696789334b8605138f4bb4"+ "hash": "858ec7cce92c9105c4e111ae58f1d1a1b1b57372b96768804308009760c9b2f6"},{"path": "bench/tasks.ts",- "hash": "d21168797f40d193a914aca0c438409d29d300441bc0a6a518c93869240b3b69"+ "hash": "efb90e69f52adcb08bfe45fb5a983fc676df68befdc455513e2581a24f46807e"+ },+ {+ "path": "bench/token-ab.ts",+ "hash": "b033a023d063cccc329103fbd11d4e1a6ab16c5eb027e1dd85c47a63a7df4ff1"},{"path": "install.sh",@@ -39,29 +43,109 @@"path": "scripts/build-viewer.mjs","hash": "fb4ba16d7815dbdbaf2fd818362f914671903132be5573fbdd9a7734549b833d"},+ {+ "path": "scripts/postinstall.mjs",+ "hash": "2836cb69bc03453bc22abcae91d58de0a06881ee7f975fe86967aedf5d2d6188"+ },{"path": "src/ai/crux.ts",- "hash": "e81750029e4c8641cdaf2b4894f595297839e07a73076e4cdac1522515f923a8"+ "hash": "81323b622400aadae1fd584ea09c2016ccf1bf4f14654b648ee50b1b13bd4c68"+ },+ {+ "path": "src/ai/llm/anthropic.ts",+ "hash": "db2b6db5102af2045a3f85933faeac8ef9b0c17bc2fcbfd3b41629622bb9551b"+ },+ {+ "path": "src/ai/llm/factory.ts",+ "hash": "d7d22f3b6af8380ff1073ddd6934eda35b3c6b95a1976223751136c0cd26122a"+ },+ {+ "path": "src/ai/llm/openai.ts",+ "hash": "6cb2677125f9a2c8c617fb1aef072fad13b87413d5ec40bebf3e21e0acc784df"+ },+ {+ "path": "src/ai/llm/types.ts",+ "hash": "8cb0f2a715498ae396ca2f5d6f14711be026346b218e07da0b30909d3cd93c93"},{"path": "src/ai/providers.ts",- "hash": "c0d1294d6fa49f6d06ff9bb137b34ea897f94a67810a839cd5705a1fa5995483"+ "hash": "ba27e2c6d98b088685946371971e9f82c7a54bba9eaa432d44881880274eb1d6"},{"path": "src/ai/summarize.ts",- "hash": "6e67f3866c75d88a8b1d265e510578f3e3014d9cfd8b2469e6e4afbd67977f93"+ "hash": "8dbec8d421f079ec67c81701d28ed1eb648b64e074b338538d03b9063941cffd"},{"path": "src/ai/synthesize.ts",- "hash": "982ab91da10ae51fdba64466cbb614db14a51f2e100bb12a72178961d8dd97d7"+ "hash": "7c6124323d5112abb15f0adea21962e083ea38234a8771832a71a59350fdc362"},{"path": "src/ask/ask.ts",- "hash": "5dad6519214e9b58feb86b46e2f498338819643ec44dc69a8f70614aad2eb986"+ "hash": "62d693c39f77019e50437b5285fafe5802b8b077e7aa6545589a3b084f93e552"+ },+ {+ "path": "src/ask/graphrank.ts",+ "hash": "a8dfba7907ce7fea84669ddf9ca20f14392b7d1edb5b76db0acf522465078cd5"+ },+ {+ "path": "src/ask/index-file.ts",+ "hash": "8250b5189d515c4e4bf1573c4c44c96563e121c944951c5f16029c62da62d854"+ },+ {+ "path": "src/claude/format.ts",+ "hash": "de278daec7071243ac381603d43817c6589406a1c8d03cef4d0bcf58b4b1d902"+ },+ {+ "path": "src/claude/hooks.ts",+ "hash": "efe4393aec6f4ab0854042b1300e8e1af899d820e6819fd0ad2d2374d321ffee"+ },+ {+ "path": "src/claude/init.ts",+ "hash": "7a686f132722453ee18c4715e4ab563f1577ac41811b01cced574de075a452ee"+ },+ {+ "path": "src/claude/paths.ts",+ "hash": "d4bde8a45859c88921abd6fd06c700199bf1feaf2e5487e8e0e217cf9dab5026"+ },+ {+ "path": "src/claude/settings-merge.ts",+ "hash": "eda59409ff8c470e7d3726a6740ba19e36e511ab40c67234aa794fabd9eacb8d"+ },+ {+ "path": "src/claude/shim-template.ts",+ "hash": "53c468c5de89b06fb76439c756932592409eba5fc19ba07ff6a37403912033a9"+ },+ {+ "path": "src/claude/skill-template.ts",+ "hash": "4e951868562ef41f827b4828dc1931cf1e645d2e57999308b1919f62de5af7fb"+ },+ {+ "path": "src/claude/state.ts",+ "hash": "f8b8d93b534be15a3d71565e63a63caa302f036348d20dcd645fb49f25db3f61"+ },+ {+ "path": "src/claude/stats.ts",+ "hash": "fc205923682e656d3e68bf301ba25702b827262f12057910615b4b648de3338b"+ },+ {+ "path": "src/claude/statusline.ts",+ "hash": "0708f2f773f65b931d488688d898c56344cd930fae1af6614a579e6fb47fae16"+ },+ {+ "path": "src/claude/sync-run.ts",+ "hash": "7ee672e67d3167a38e9577a673656f7958c69b48e62ec715850a9b14599a1d2a"+ },+ {+ "path": "src/cli-epilogue.ts",+ "hash": "a4534c83c0a600020421be92882a83db7fda3e1626a38702fc372bb3c523a232"+ },+ {+ "path": "src/cli-meta.ts",+ "hash": "95ee44a152ed1936f0461b2452d9902fbf422555da9f01e8f5ff57fbb84a2f00"},{"path": "src/cli.ts",- "hash": "ba1d90ee4c0f7b5000fa4239461c19d54fdedcad12b8592589312f163e1357dc"+ "hash": "2c7acb076bd022635defd0b67c5358edd3b662328050be6c2d976e6baa17fc9c"},{"path": "src/context/build.ts",@@ -77,11 +161,15 @@},{"path": "src/engine.ts",- "hash": "e237ef6555d8bd2001eccfc32e314ef3881cef1c79d537ee701515a357f87d16"+ "hash": "55e2191dd67d1e4369c2a872f1b908937bd6034ce6f8f4b03e6c86a059e271c7"+ },+ {+ "path": "src/graph/bindings.ts",+ "hash": "5cfcbb66a1aa754f3b56d68c09d5bcf52f5002a67abd70cc8f1a8d0c1dddce6a"},{"path": "src/graph/build.ts",- "hash": "b18f5fc18dffd77771f39722eb19963c1188fd298cbb5cfd5d71ef8dc45658c6"+ "hash": "10ae2a085b299a56cb90d41289a956065dd8eef358ae2abbc39db59b82a12dc9"},{"path": "src/graph/cards.ts",@@ -97,28 +185,88 @@},{"path": "src/graph/extract.ts",- "hash": "58cd002d5ee7dfb750cb85293a795148ffbec31e68e2a9b693e0794543a7f727"+ "hash": "8449958d4b5fd74c8eafeb488ae16cb60dcaf3e5fcaf1e3069cebf4cf9ef48d9"+ },+ {+ "path": "src/graph/load.ts",+ "hash": "115b75e947618be7755ac59310f898943cb4c1d8266bdf5a4a30fdca4956914a"+ },+ {+ "path": "src/graph/map.ts",+ "hash": "aa982e0a06ce4e8d3af76cec5847846d495f36ace8835fe6bf70805429346ffd"+ },+ {+ "path": "src/graph/relations.ts",+ "hash": "e62bc9934057bf232f86edcf942e71b0a2f4c44b57ffd78ddb935b85ab75aca8"},{"path": "src/graph/resolve.ts",- "hash": "dad41f73d773c45f5237b85e10a36ae45331cd5959df578816ee8ab47622cffe"+ "hash": "23e2e29f6e907f079f0d214ac6ce24b6105c403a51da30c2f4d39494f4b6b110"+ },+ {+ "path": "src/graph/traverse-cli.ts",+ "hash": "080714fc91e5caefe4548e87c071b2010fdc593a670366db941d9fd2907b08e2"+ },+ {+ "path": "src/graph/traverse.ts",+ "hash": "dd38bef08a175c1db6751823f7f6f1eaae3952227737b063373987f69c52d7fa"},{"path": "src/graph/types.ts",- "hash": "757b84c059d13cda49e0f29518b31a5473f0d6e243b2ab1f374a7f7ff02492e4"+ "hash": "27a9bdbef7783e5da94c860bc83525ef788e38a2176bc1184c8adbee539b1b51"},{"path": "src/graph/write.ts",- "hash": "55dd6ea840135ade4db7f49042234bee0db07a9c8c959ab57767deb8bebc6345"+ "hash": "a8f0d1b3efed9ca1ac3c22175c46c7a737b91bf632930ebb4437ebf52326ed69"+ },+ {+ "path": "src/hosts/codex-hooks.ts",+ "hash": "0b9ba9ba677876d1adf4ce8d05aa534cddfbdeb7060ed11a92111a41a76d1512"+ },+ {+ "path": "src/hosts/init.ts",+ "hash": "cd3ef307f207a48b82fa81ea55e34fdc97b8663612ad639a3256336d5531afa0"+ },+ {+ "path": "src/hosts/instructions.ts",+ "hash": "1dddea660f4d5e65952faf2beee42f04153ccab893658e75bda1dce6c0245b18"+ },+ {+ "path": "src/hosts/mcp-config.ts",+ "hash": "c3a3dea18371806ed352e7cab582265db2341b7d4ea5797578e495b512a9b0b3"+ },+ {+ "path": "src/hosts/registry.ts",+ "hash": "0a8a2b82f0e4e1010943eb69d2eee7d9c4549f884967d5af1b8317c38ef99c18"+ },+ {+ "path": "src/hosts/sections.ts",+ "hash": "f172618889d5a02683032df8c69dd85b71c00c72a8b76958305ade22d6cda714"},{"path": "src/index.ts",- "hash": "e56e74612514fd45665b27e3c47b4a685b503a533b38e1674d256344511107fc"+ "hash": "f66577d7952e061dd28f782e39f572fe9421a52758e9151f2620739894dd006d"},{"path": "src/ingest/fs.ts","hash": "a8339532da34b44d35eb9ad16e7106adb1262d73d9895b1bd94574337fb2019f"},+ {+ "path": "src/mcp/server.ts",+ "hash": "0bdeba850ab62132a01b683cd2db7ee36a7509a67ebd58e73887a22a611ce100"+ },+ {+ "path": "src/mcp/tools.ts",+ "hash": "26d386319a711ec0eb758a2561513dc05e164f2c4d5828b6089b41db2b0a715b"+ },+ {+ "path": "src/search/grep-cli.ts",+ "hash": "70bcb32d3ae5e4e9e39eb8b07151da7145a08756015e91f215edcadce5bddef8"+ },+ {+ "path": "src/search/grep.ts",+ "hash": "e0ba3aaa565892e2772e4de0492931a568fc3f3724f8fca44b2a188a24e5eeb4"+ },{"path": "src/util/id.ts","hash": "5fabc8ddcc3abc907ce69f04ad2ebe51933262cf44aa2dfd40589f71f1926e8a"@@ -131,22 +279,150 @@"path": "src/viz/serve.ts","hash": "14283762f454c01fc95cfbe9c2b41ef063fc17c4c3e5d120b5dc7f66f541fc1c"},+ {+ "path": "test/ask-index.test.ts",+ "hash": "c9cd7c011ebd661f35488c59dcd34801079f2786d56e96833f4da7c45dfa37d7"+ },{"path": "test/ask.test.ts",- "hash": "b2d9beeea01fd6faab6225ea3b3a735d5dd808e8358ffe37bb82a2a5f5da3dce"+ "hash": "3445f8b156ba6b2f0e9123e9fc45781da352ec6d5baeb985ee144fe5aecaafb3"+ },+ {+ "path": "test/claude-format.test.ts",+ "hash": "cfaa9f489dd95956e3c9917ebe29a46992dfdbab943b5971eecbd98f18b3268c"+ },+ {+ "path": "test/claude-hooks.test.ts",+ "hash": "875c10776da455499b58ebe861b3cb0ae797f751e4e838812cd0b4f3c13587c2"+ },+ {+ "path": "test/claude-init.test.ts",+ "hash": "b582cd79b2a1e4952ff83ac1b2e85f742756443c2896e08d96a75dc76e2971a5"+ },+ {+ "path": "test/claude-paths.test.ts",+ "hash": "205740f8110e72e4cb24652c09f763fad5e056dc77776bcfa95a1953731ed2c8"+ },+ {+ "path": "test/claude-settings-merge.test.ts",+ "hash": "4c8b800f02d1b72050082bdbcdcda0878e5d9760563d2e1ca4a31cb06ffaaabb"+ },+ {+ "path": "test/claude-shim-template.test.ts",+ "hash": "f787f99fef2dc6a5ed366419fc470e8e4f825e0bc590cf3550d39e01995e7619"+ },+ {+ "path": "test/claude-skill-template.test.ts",+ "hash": "49f60183a51f9c307a33b5d4da3a7ded2f55509407e6a85778f3512b27db7cde"+ },+ {+ "path": "test/claude-state.test.ts",+ "hash": "78e6a81af7642ea788072457ea181bc626c7a8a898cfebb882ab42fed7e9dd2e"+ },+ {+ "path": "test/claude-stats.test.ts",+ "hash": "f625d026d152a65017699e37e27534043dc0af0f43ba2d3ea778bac8ddab82c3"+ },+ {+ "path": "test/claude-statusline.test.ts",+ "hash": "07128b5b195af3a37c1e170a35c18378e36160d1a6f8e17be362bac315811cac"+ },+ {+ "path": "test/cli-meta.test.ts",+ "hash": "e7a05bf838e876a317276f94a26d92b0b1526e1ea7eabda4e68b804bdb0334e5"},{"path": "test/context.test.ts",- "hash": "7c1242872b127117c7cc50404895d7ffcf286a51b611cd23c4ffabd5db8d43f3"+ "hash": "126861c136d48ed6a148e50226c96ec2935c52cf83ef56fbd43392e0d271db1f"},{"path": "test/covers.test.ts","hash": "f5a75f405be1a01ad43fc806588858df3a8988fee62ad4ec024440d3f5e0fc0c"},+ {+ "path": "test/graph-bindings.test.ts",+ "hash": "b6892b1b6982547fc67d5b0e7812a536e47018ab3e38e4eda35a0f12f24ab8db"+ },+ {+ "path": "test/graph-go.test.ts",+ "hash": "bf11085a7edb03c00d52dca090af9c1ca4eb3cb34bb88904bbdd478171d3483d"+ },+ {+ "path": "test/graph-load.test.ts",+ "hash": "8df11988d049b5243d8c7a0d55045163b714965897448797b40c8ef458b0896b"+ },+ {+ "path": "test/graph-map.test.ts",+ "hash": "97c06030735d5dbb15270b73a594e1de8fb3ffba5c6551b6303a5357b8da31be"+ },+ {+ "path": "test/graph-resolve-typed.test.ts",+ "hash": "0c3760525cc61ee97de448fa26b4a5b9a3bb07c03b4acfbdf3608541b189cf81"+ },+ {+ "path": "test/graph-traverse-cli.test.ts",+ "hash": "d79347b0640178631235552105c0518029305ead4990726470d3adf5a1b52f09"+ },+ {+ "path": "test/graph-traverse.test.ts",+ "hash": "9683b55f739af4afbb3840cee333eed0b1869494b66fe9cddfae1153df246947"+ },+ {+ "path": "test/graph-write.test.ts",+ "hash": "cbbf9c3591519993ec89298444d34732f08eb16f90ba1c1cd33bd39d5512f9ff"+ },+ {+ "path": "test/graphrank.test.ts",+ "hash": "9b6450a705fd5bbe7ddead7ae29f87fcb839599d34b6bd0c8ebcb0091ee70c47"+ },{"path": "test/helpers.ts","hash": "e45af1d38d7c6d4abc804fc74e9ae4c3373cf78769c17b16b185c3ee0e2c3228"},+ {+ "path": "test/hosts-codex-hooks.test.ts",+ "hash": "ed49a8a106eeb458ad2dd071071cefae17dd4d0eabd1b74006047feadef9a89a"+ },+ {+ "path": "test/hosts-init.test.ts",+ "hash": "56f8988468cb716296b40c939bf58d079015d135fcb3f2c1481e64bce7f67324"+ },+ {+ "path": "test/hosts-instructions.test.ts",+ "hash": "37ae3aae1157c1e1eb39ef5670b363d517aaf3028ca8fb56581193b81a83cad7"+ },+ {+ "path": "test/hosts-mcp-config.test.ts",+ "hash": "5b3ec5afd61079f051d8063f06701ddac608f48b706e72f9ee607e8da673fb06"+ },+ {+ "path": "test/hosts-registry.test.ts",+ "hash": "6490cbdc54b870d670adf28b5b469e07360a474073b08d692601ef1c4b7ea47e"+ },+ {+ "path": "test/hosts-sections.test.ts",+ "hash": "a780abe63074737d40bcd556df06b7b541d2694df75c307daabd280f64f9dba4"+ },+ {+ "path": "test/llm-adapters.test.ts",+ "hash": "53081583f9a2ef8a7f925fcce6554201fb8a10184ac835f3879cb3f04700f346"+ },+ {+ "path": "test/llm-ops.test.ts",+ "hash": "ef3ba575506602feeb3048a6bded8bd2a92e9a59054c569352e82d1a847b80af"+ },+ {+ "path": "test/mcp-server.test.ts",+ "hash": "4d828181f0a8c645f00097ab43c2bdcf5bc65da276e83b7503bc2888ae09f254"+ },+ {+ "path": "test/mcp-tools.test.ts",+ "hash": "22d3a32a85a0ba1542969786e8bda07d3df02ee068554d4070f705d30d7239dc"+ },+ {+ "path": "test/search-grep.test.ts",+ "hash": "a23b17c1a455374c4b4172834c51bb6c5e5ed5abbc891df16ee7cb4aeae9b5c0"+ },{"path": "test/viz-assemble.test.ts","hash": "89a2a9f11f459a8110f9d89b2de780dfd164504f3b4c7dc61953a6c83c5911cb"@@ -178,17 +454,17 @@],"nodes": [{- "slug": "ai-model-integration",- "name": "AI Model Integration",+ "slug": "agent",+ "name": "Agent","type": "system","sources": [- "bench/llm.ts"+ "bench/agent.ts"],- "sourcesDigest": "1bdc59307386b5187ea92242900b2c3b286de3f9f45a08a7dfcf1c2d11801b27"+ "sourcesDigest": "989950aca29644904bb9a7040d36a735534f3b0d1b3854912a2303e5b0831423"},{- "slug": "benchmarking-framework",- "name": "Benchmarking Framework",+ "slug": "benchmarking-system",+ "name": "Benchmarking System","type": "system","sources": ["bench/agent.ts",@@ -197,49 +473,40 @@"bench/report.ts","bench/run.ts","bench/selfcheck.ts",- "bench/tasks.ts"+ "bench/tasks.ts",+ "bench/token-ab.ts"],- "sourcesDigest": "afaac16d744b84811efe1b826c2bab23737665e1e62fe39b1267f20f5451b4d0"+ "sourcesDigest": "918b737414aae73bb0f84df38880140028a61e8bf27b89b544943394d05bb10f"},{- "slug": "benchmarking-results-reporting",- "name": "Benchmarking Results Reporting",- "type": "system",- "sources": [- "bench/report.ts"- ],- "sourcesDigest": "f7b46f3036503f43413cb48d25fa6ce54585514fb19e9b4e923c0c5628ce8aed"- },- {- "slug": "caching-mechanism",- "name": "Caching Mechanism",+ "slug": "code-summarization",+ "name": "Code Summarization","type": "concept",- "sources": [- "bench/agent.ts",- "bench/report.ts",- "src/context/build.ts"- ],- "sourcesDigest": "0393dee6bf242715500eeac001ca94cd9c7ff05d644d8e36d58e9c7fd2e0eab9"- },- {- "slug": "code-summarization-and-synthesis",- "name": "Code Summarization and Synthesis",- "type": "system","sources": ["src/ai/crux.ts","src/ai/summarize.ts","src/ai/synthesize.ts"],- "sourcesDigest": "1916d34902c4bd664703e6c5da273beb26c2be5f55e971b3cc3f590f65cde3c7"+ "sourcesDigest": "2df073fd00fbefc26907027a923c10609cf005d9cbb727ff2917374d03b251dc"},{"slug": "configuration-management","name": "Configuration Management","type": "concept","sources": [- "src/ai/providers.ts"+ "src/ai/providers.ts",+ "src/claude/settings-merge.ts"+ ],+ "sourcesDigest": "cbca57735b2ad73fb6d62dde432844f8879809265ad6f5274082ab955c08b5b8"+ },+ {+ "slug": "deterministic-testing",+ "name": "Deterministic Testing",+ "type": "concept",+ "sources": [+ "test/helpers.ts"],- "sourcesDigest": "a131fc0c197424e0b9a6a1da0c7e97f8aaa37eb06f6720480e7959923c918071"+ "sourcesDigest": "ddc97a2b9b5b7ea60c6a55b3c250ddc0dffa3b335c4b43ddc9152dc900f56744"},{"slug": "error-handling-and-reporting",@@ -247,31 +514,177 @@"type": "concept","sources": ["bench/run.ts",- "src/graph/build.ts",- "src/graph/check.ts"+ "src/engine.ts",+ "src/graph/build.ts"+ ],+ "sourcesDigest": "616914a6531c73b635ea2da8eba71b3f12bdae64d0e10c2618cdd7c1ebfc658b"+ },+ {+ "slug": "graph-data-integrity",+ "name": "Graph Data Integrity",+ "type": "concept",+ "sources": [+ "test/graph-write.test.ts"],- "sourcesDigest": "1386bf6efb7992fa69cd12a578fcd62b16f5332693ce2d7020e4050ba354f2f7"+ "sourcesDigest": "34c4a4eb40884a5f3072352f37d7efb647f89cb7fe8b9ba43d91eacbbad0c0c0"},{- "slug": "graph-construction",- "name": "Graph Construction",+ "slug": "graph-extraction-and-loading",+ "name": "Graph Extraction and Loading","type": "system","sources": [- "src/context/build.ts",+ "src/graph/extract.ts",+ "src/graph/load.ts",+ "src/graph/relations.ts",+ "src/graph/resolve.ts",+ "src/graph/types.ts"+ ],+ "sourcesDigest": "acfd590d81e375dfc632bbf862a013b910daf352d7ff1739e70ef80fd841fcfa"+ },+ {+ "slug": "graph-ranking",+ "name": "Graph Ranking",+ "type": "system",+ "sources": [+ "test/graphrank.test.ts"+ ],+ "sourcesDigest": "891283b4808759d18bf39767763a60e2529b6e7559323f4115f409ab61912eaa"+ },+ {+ "slug": "graph-representation",+ "name": "Graph Representation",+ "type": "system",+ "sources": [+ "src/graph/relations.ts",+ "src/graph/types.ts"+ ],+ "sourcesDigest": "45b44b0500854924c7bf69043e5f45af360c55776bcf957442700620d7a3b1f4"+ },+ {+ "slug": "graph-serialization",+ "name": "Graph Serialization",+ "type": "system",+ "sources": [+ "test/graph-write.test.ts"+ ],+ "sourcesDigest": "34c4a4eb40884a5f3072352f37d7efb647f89cb7fe8b9ba43d91eacbbad0c0c0"+ },+ {+ "slug": "graph-synchronization",+ "name": "Graph Synchronization",+ "type": "concept",+ "sources": ["src/context/check.ts",- "src/graph/build.ts","src/graph/check.ts"],- "sourcesDigest": "542278c320dfc3ba4690fe870e4222ebb3eb9fa87d9c1cd94780003d54e72141"+ "sourcesDigest": "9a6d9714cc8b93725ff7e5702bd59dca1a96a6a3ebb7cec5c2f2e7e72eb9f093"+ },+ {+ "slug": "graph-traversal-and-analysis",+ "name": "Graph Traversal and Analysis",+ "type": "system",+ "sources": [+ "src/graph/traverse-cli.ts",+ "src/graph/traverse.ts",+ "src/search/grep-cli.ts",+ "src/search/grep.ts"+ ],+ "sourcesDigest": "0d510fdb8ad732a39d2c989024794702526f50a3a8555dce95314cb5b80d3a0a"+ },+ {+ "slug": "graph-traversal-and-impact-analysis",+ "name": "Graph Traversal and Impact Analysis",+ "type": "system",+ "sources": [+ "test/graph-traverse.test.ts"+ ],+ "sourcesDigest": "488464ccc2ad9ea80719012d014ea2836db6f60a1b0335e18545affa4a04a7b2"+ },+ {+ "slug": "graph-visualization",+ "name": "Graph Visualization",+ "type": "system",+ "sources": [+ "viewer/data.ts",+ "viewer/detail.ts",+ "viewer/graph.ts",+ "viewer/main.ts",+ "viewer/tree.ts"+ ],+ "sourcesDigest": "fd0623540e7f7eed9942e3db2bc219f9a08b3814ac219dfb2b9a74f8c1aea966"},{- "slug": "graph-management",- "name": "Graph Management",+ "slug": "host-configuration-management",+ "name": "Host Configuration Management","type": "system","sources": [- "src/graph/write.ts"+ "test/hosts-codex-hooks.test.ts",+ "test/hosts-init.test.ts",+ "test/hosts-mcp-config.test.ts",+ "test/hosts-registry.test.ts",+ "test/hosts-sections.test.ts"],- "sourcesDigest": "fa6cd161fd547a03ecad2649fbb2b6094b5a6a64b10dcc1bdd6244e5157d4d48"+ "sourcesDigest": "bc0c33ccee8f4a029f0fb4af261138907cc7b85f4f063f18ef3cb49d03076555"+ },+ {+ "slug": "host-management-and-configuration",+ "name": "Host Management and Configuration",+ "type": "system",+ "sources": [+ "src/hosts/codex-hooks.ts",+ "src/hosts/init.ts",+ "src/hosts/instructions.ts",+ "src/hosts/mcp-config.ts",+ "src/hosts/registry.ts",+ "src/hosts/sections.ts"+ ],+ "sourcesDigest": "da51b260a6b5e65f9dc1fa578e44a81309e6379f05f575b42378a1a646d63bb7"+ },+ {+ "slug": "idempotent-host-initialization",+ "name": "Idempotent Host Initialization",+ "type": "concept",+ "sources": [+ "test/hosts-init.test.ts"+ ],+ "sourcesDigest": "f7070057632565b4c1a7232ff4218cdefd56e5b26dacbe4e874e1c73a6ffb332"+ },+ {+ "slug": "judge",+ "name": "Judge",+ "type": "system",+ "sources": [+ "bench/judge.ts"+ ],+ "sourcesDigest": "b7c143d704da46109b37f03f603d29dcdd327ce19900ddfdf1b58ac4ead126ba"+ },+ {+ "slug": "llm-integration",+ "name": "LLM Integration",+ "type": "system",+ "sources": [+ "bench/llm.ts"+ ],+ "sourcesDigest": "4f4e246df7420566c35c5613d87662927000d8a548af5960275c64cc0a6e125e"+ },+ {+ "slug": "mcp-server-and-tools",+ "name": "MCP Server and Tools",+ "type": "system",+ "sources": [+ "test/mcp-server.test.ts",+ "test/mcp-tools.test.ts"+ ],+ "sourcesDigest": "57fc202e973b1af8d9bf326a11a5008fb7c95c9ea5738c7dfecd511a8df4d9d0"+ },+ {+ "slug": "report",+ "name": "Report",+ "type": "system",+ "sources": [+ "bench/report.ts"+ ],+ "sourcesDigest": "38642e3446c662002dd4ca9bd1c6438520ecfe224cb0b2481b1c21d74dc32228"},{"slug": "self-check-mechanism",@@ -280,29 +693,84 @@"sources": ["bench/selfcheck.ts"],- "sourcesDigest": "bfb889927e966de42eecbab5b0186d21e7c5fc8fbde68f2a8a68c657bb120a9a"+ "sourcesDigest": "9e4f820e588b39901b8509f53d03b4a0d5451ee79d098d970f3a88d7c6765c7c"},{- "slug": "task-management",- "name": "Task Management",+ "slug": "tasks",+ "name": "Tasks","type": "system","sources": ["bench/tasks.ts"],- "sourcesDigest": "2940a72050e0bee89a860d904a1ebf289505f797cd93c71d86c2e776227e3fb4"+ "sourcesDigest": "bf5418660cc917f7af4f93b7ed71cfc4c37f06a27af5b61047b54ba572a3a2b0"},{- "slug": "visualization-layer",- "name": "Visualization Layer",+ "slug": "test-helpers",+ "name": "Test Helpers","type": "system","sources": [- "viewer/data.ts",+ "test/helpers.ts"+ ],+ "sourcesDigest": "ddc97a2b9b5b7ea60c6a55b3c250ddc0dffa3b335c4b43ddc9152dc900f56744"+ },+ {+ "slug": "testing-and-validation",+ "name": "Testing and Validation",+ "type": "system",+ "sources": [+ "test/ask-index.test.ts",+ "test/ask.test.ts",+ "test/claude-format.test.ts",+ "test/claude-hooks.test.ts",+ "test/claude-init.test.ts",+ "test/claude-paths.test.ts",+ "test/claude-settings-merge.test.ts",+ "test/claude-shim-template.test.ts",+ "test/claude-skill-template.test.ts",+ "test/claude-state.test.ts",+ "test/claude-stats.test.ts",+ "test/claude-statusline.test.ts",+ "test/cli-meta.test.ts",+ "test/context.test.ts",+ "test/covers.test.ts",+ "test/graph-bindings.test.ts",+ "test/graph-go.test.ts",+ "test/graph-load.test.ts",+ "test/graph-map.test.ts",+ "test/graph-resolve-typed.test.ts",+ "test/graph-traverse-cli.test.ts"+ ],+ "sourcesDigest": "ec26f442eeea6bac55ed94939624004883ed25f71e6271fccd772f42743774f0"+ },+ {+ "slug": "token-a-b-testing",+ "name": "Token A/B Testing",+ "type": "system",+ "sources": [+ "bench/token-ab.ts"+ ],+ "sourcesDigest": "12c7bde30c776e231fe85e67e20d88c3b691c854a45b9bc463502f489874cdf7"+ },+ {+ "slug": "user-interaction-in-visualization",+ "name": "User Interaction in Visualization",+ "type": "concept",+ "sources": ["viewer/detail.ts","viewer/graph.ts",- "viewer/main.ts",- "viewer/tree.ts"+ "viewer/main.ts"],- "sourcesDigest": "fd0623540e7f7eed9942e3db2bc219f9a08b3814ac219dfb2b9a74f8c1aea966"+ "sourcesDigest": "949fbcf087492dc70392ec9143ab9070d6c27e57720cbb7fa1b4324d473e7423"+ },+ {+ "slug": "visualization-and-serving",+ "name": "Visualization and Serving",+ "type": "system",+ "sources": [+ "src/viz/assemble.ts",+ "src/viz/serve.ts"+ ],+ "sourcesDigest": "88ca5c49a63bfa8625974ff180102457ba16dd9538fa82d23bbe252becd035d8"}]}diff --git a/graft/mcp-server-and-tools.md b/graft/mcp-server-and-tools.mdnew file mode 100644index 00000000..78647684--- /dev/null+++ b/graft/mcp-server-and-tools.md@@ -0,0 +1,49 @@+---+name: MCP Server and Tools+slug: mcp-server-and-tools+type: system+sources:+ - path: test/mcp-server.test.ts+ hash: 4d828181f0a8c645f00097ab43c2bdcf5bc65da276e83b7503bc2888ae09f254+ - path: test/mcp-tools.test.ts+ hash: 22d3a32a85a0ba1542969786e8bda07d3df02ee068554d4070f705d30d7239dc+sources_digest: 57fc202e973b1af8d9bf326a11a5008fb7c95c9ea5738c7dfecd511a8df4d9d0+links:+ - to: graph-serialization+ relation: validates+ description: The MCP tools may validate the integrity of the serialized graph data.+generator:+ version: 1+covers:+ - symbol: rpc+ kind: function+ at: 'test/mcp-server.test.ts:L9-L28'+ - symbol: builtRepo+ kind: function+ at: 'test/mcp-tools.test.ts:L9-L16'+ - symbol: chainRepo+ kind: function+ at: 'test/mcp-tools.test.ts:L22-L33'+ - symbol: customDirRepo+ kind: function+ at: 'test/mcp-tools.test.ts:L37-L45'+ - symbol: fileScopeRepo+ kind: function+ at: 'test/mcp-tools.test.ts:L50-L60'+ - symbol: multiDirRepo+ kind: function+ at: 'test/mcp-tools.test.ts:L65-L73'+---+<!-- context:generated:start -->+## Summary++This component encompasses the Multi-Channel Protocol server and associated tools, facilitating RPC interactions and providing various utilities for analyzing and manipulating code repositories.++## Related++- validates [[graph-serialization]] — The MCP tools may validate the integrity of the serialized graph data.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/benchmarking-results-reporting.md b/graft/report.mdsimilarity index 64%rename from graft/benchmarking-results-reporting.mdrename to graft/report.mdindex b8f159a8..8e649d77 100644--- a/graft/benchmarking-results-reporting.md+++ b/graft/report.md@@ -1,15 +1,15 @@----name: Benchmarking Results Reporting-slug: benchmarking-results-reporting+name: Report+slug: reporttype: systemsources:- path: bench/report.ts- hash: 775be8c40a8e4172521bba8f6a1f026fa23c4d24b9b5225da3ed5b745077a5b0-sources_digest: f7b46f3036503f43413cb48d25fa6ce54585514fb19e9b4e923c0c5628ce8aed+ hash: 17c0be550f9712165177d070f58cbe7a0f60fcb2c1dc5830eb1a4dde97ec12f3+sources_digest: 38642e3446c662002dd4ca9bd1c6438520ecfe224cb0b2481b1c21d74dc32228links:- - to: benchmarking-framework+ - to: benchmarking-systemrelation: part_of- description: Integrates with the benchmarking framework to report results.+ description: The report is a key output of the benchmarking system.generator:version: 1covers:@@ -53,11 +53,11 @@ covers:<!-- context:generated:start -->## Summary-This component aggregates and formats the results of benchmarking trials, providing insights into performance metrics and cost evaluations. It emphasizes clarity in reporting and economic implications.+The report component aggregates benchmarking results from various trials, transforming raw data into a structured markdown report that highlights performance metrics and provides insights into the benchmarking context.## Related-- part of [[benchmarking-framework]] — Integrates with the benchmarking framework to report results.+- part of [[benchmarking-system]] — The report is a key output of the benchmarking system.<!-- context:generated:end -->## Notesdiff --git a/graft/scripts/postinstall.md b/graft/scripts/postinstall.mdindex 0e44a530..9ae3f64d 100644--- a/graft/scripts/postinstall.md+++ b/graft/scripts/postinstall.md@@ -1,3 +1,5 @@# scripts/postinstall.mjs+This script provides a non-intrusive notification after installation, ensuring the install process is not interrupted by errors.+_No extracted symbols in this file._diff --git a/graft/self-check-mechanism.md b/graft/self-check-mechanism.mdindex 119250e9..2d343d67 100644--- a/graft/self-check-mechanism.md+++ b/graft/self-check-mechanism.md@@ -4,30 +4,33 @@ slug: self-check-mechanismtype: systemsources:- path: bench/selfcheck.ts- hash: 0eaf577938e20fa27d9cd0157bc8843fdc37165d85696789334b8605138f4bb4-sources_digest: bfb889927e966de42eecbab5b0186d21e7c5fc8fbde68f2a8a68c657bb120a9a+ hash: 858ec7cce92c9105c4e111ae58f1d1a1b1b57372b96768804308009760c9b2f6+sources_digest: 9e4f820e588b39901b8509f53d03b4a0d5451ee79d098d970f3a88d7c6765c7clinks:- - to: benchmarking-framework- relation: part_of- description: Supports the benchmarking framework by providing a testing environment.+ - to: agent+ relation: uses+ description: The self-check mechanism simulates the agent's behavior.generator:version: 1covers:- - symbol: makeStubClient+ - symbol: makeStubModelkind: function- at: 'bench/selfcheck.ts:L19-L48'+ at: 'bench/selfcheck.ts:L20-L39'+ - symbol: create+ kind: method+ at: 'bench/selfcheck.ts:L24-L37'- symbol: mainkind: function- at: 'bench/selfcheck.ts:L50-L114'+ at: 'bench/selfcheck.ts:L41-L105'---<!-- context:generated:start -->## Summary-This component allows for offline verification of the benchmarking harness, enabling developers to test control flow without needing external API keys. It simulates responses for comprehensive testing.+This component allows for offline verification of the agent's control flow and tool execution without requiring an API key, using a stubbed model to simulate responses and evaluate correctness.## Related-- part of [[benchmarking-framework]] — Supports the benchmarking framework by providing a testing environment.+- uses [[agent]] — The self-check mechanism simulates the agent's behavior.<!-- context:generated:end -->## Notesdiff --git a/graft/src/ai/crux.md b/graft/src/ai/crux.mdindex 5df63102..c7464a16 100644--- a/graft/src/ai/crux.md+++ b/graft/src/ai/crux.md@@ -1,15 +1,15 @@-# src/ai/crux.ts · [[code-summarization-and-synthesis]]+# src/ai/crux.ts · [[code-summarization]]-This file provides a mechanism to summarize code definitions for better navigation and understanding of a codebase.+This file defines a system for summarizing code definitions to aid engineers in navigating a codebase.- NodeRef · interface · L21-L27 — Defines the structure for referencing a node in the code graph.- FileCruxInput · interface · L29-L33 — Encapsulates the input data required for summarizing a file's code definitions.- NodeCrux · interface · L35-L40 — Represents the summarized information for a code definition in the file.- CruxSummarizer · interface · L42-L44 — Interface for summarizing code definitions from a file.-- numberLines · function · L63-L70 — Formats the source code into a numbered string for better readability.-- userContent · function · L72-L81 — Constructs a user content string that includes file details and target nodes.-- parseResults · function · L84-L98 — Parses the JSON response from the summarization model into a usable format.-- num · function · L88-L88 — This function converts a potentially non-finite number to a finite integer or zero, ensuring valid numerical output.-- OpenRouterCruxSummarizer · class · L101-L127 — Implements the CruxSummarizer interface using OpenAI's chat API for summarization.-- constructor · method · L105-L112 — Initializes the OpenRouterCruxSummarizer with API key and model.-- describeFile · method · L114-L126 — Generates summaries for the code definitions in a given file.+- numberLines · function · L81-L88 — Formats the source code into a numbered string for better readability.+- userContent · function · L90-L99 — Constructs a user content string that includes file details and target nodes.+- parseResults · function · L102-L114 — Transforms the tool's parsed argument object into a structured list of NodeCrux objects for further processing.+- num · function · L104-L104 — This function converts a potentially non-finite number to a finite integer or zero, ensuring valid numerical output.+- ChatCruxSummarizer · class · L117-L140 — Implements a summarizer that utilizes a ChatModel to describe code definitions and their purposes in a file.+- constructor · method · L118-L118 — Initializes the ChatCruxSummarizer with a specific ChatModel instance for generating summaries.+- describeFile · method · L120-L139 — Processes a file input to generate summaries of its target definitions using the ChatModel.diff --git a/graft/src/ai/llm/anthropic.md b/graft/src/ai/llm/anthropic.mdnew file mode 100644index 00000000..466322aa--- /dev/null+++ b/graft/src/ai/llm/anthropic.md@@ -0,0 +1,14 @@+# src/ai/llm/anthropic.ts++This module provides an adapter for the Anthropic Messages API, enabling seamless integration of Claude as a first-class AI provider while handling specific API differences.++- AnthropicChatModelOptions · interface · L24-L31 — Defines the configuration options required to instantiate an Anthropic chat model, ensuring necessary parameters are provided.+- CacheControl · type · L33-L33 — Specifies the cache control settings for ephemeral data management in the chat model.+- cc · function · L34-L34 — Creates a cache control object based on a boolean flag to manage ephemeral caching behavior.+- AnthropicChatModel · class · L36-L141 — Implements the chat model interface for interacting with the Anthropic API, encapsulating the logic for message handling and API communication.+- constructor · method · L41-L45 — Initializes an instance of the AnthropicChatModel with the provided options, setting up the necessary API client and model details.+- create · method · L47-L100 — Handles the creation of chat messages by processing input requests and formatting them for the Anthropic API, ensuring compliance with API requirements.+- assistantParam · method · L103-L111 — Reconstructs the assistant's response from the original message blocks, preserving the context and structure of the conversation.+- fromResponse · method · L113-L140 — Transforms the API response into a structured ChatResponse object, extracting relevant information and maintaining the original message format.+- toAnthropicTool · function · L143-L145 — Converts a ToolSpec into the format required by the Anthropic API, facilitating the integration of tools into chat requests.+- normalizeUsage · function · L148-L155 — Normalizes the usage statistics from the Anthropic API response, providing a consistent structure for input and output token counts.diff --git a/graft/src/ai/llm/factory.md b/graft/src/ai/llm/factory.mdnew file mode 100644index 00000000..bad36e75--- /dev/null+++ b/graft/src/ai/llm/factory.md@@ -0,0 +1,7 @@+# src/ai/llm/factory.ts++Creates instances of ChatModel based on the specified provider configuration, enabling flexible integration with different chat model APIs.++- ProviderKind · type · L12-L12 — Defines the types of providers for chat models, ensuring compatibility with specific APIs.+- ChatModelConfig · interface · L14-L21 — Specifies the configuration required to create a chat model, enforcing necessary parameters for initialization.+- createChatModel · function · L23-L39 — Creates an instance of a chat model based on the specified provider, handling different implementations accordingly.diff --git a/graft/src/ai/llm/openai.md b/graft/src/ai/llm/openai.mdnew file mode 100644index 00000000..d0bcd8d9--- /dev/null+++ b/graft/src/ai/llm/openai.md@@ -0,0 +1,16 @@+# src/ai/llm/openai.ts++This module provides an adapter for interacting with various OpenAI-compatible endpoints, allowing users to send chat requests and receive responses while managing caching and formatting options.++- OpenAIChatModelOptions · interface · L19-L29 — Defines the configuration options for the OpenAI chat model, including API key and model type.+- ChatParams · type · L31-L31 — Defines the parameters required for creating a chat completion request, ensuring the correct structure is used for API calls.+- ChatMessage · type · L32-L32 — Represents a message in the chat, encapsulating the role and content to facilitate communication between users and the AI.+- textPart · function · L35-L39 — Constructs a text message part with optional cache control for OpenRouter passthrough.+- toChatMessage · function · L41-L67 — Transforms a message object into a format suitable for OpenAI's chat API, handling different roles appropriately.+- toChatTool · function · L69-L71 — Converts a tool specification into a format compatible with OpenAI's chat completion API, enabling the use of external tools in chat interactions.+- OpenAIChatModel · class · L73-L162 — Implements the chat model interface for interacting with OpenAI's chat completions API.+- constructor · method · L78-L88 — Initializes an OpenAIChatModel instance with the specified options, setting up the necessary API client and model parameters for chat interactions.+- create · method · L90-L115 — Creates a chat completion request to the OpenAI API using the provided messages and parameters.+- fromResponse · method · L117-L161 — Processes the response from the OpenAI API to extract relevant chat information and tool calls.+- parse · function · L127-L133 — Safely parses a JSON string into an object, handling errors to ensure robust processing of responses from the chat API.+- normalizeUsage · function · L165-L174 — Normalizes usage statistics by calculating uncached input tokens from the OpenAI API response.diff --git a/graft/src/ai/llm/types.md b/graft/src/ai/llm/types.mdnew file mode 100644index 00000000..54c96977--- /dev/null+++ b/graft/src/ai/llm/types.md@@ -0,0 +1,12 @@+# src/ai/llm/types.ts++Defines interfaces and types for a provider-neutral chat transport system that facilitates communication with various language model providers.++- ToolCall · interface · L23-L28 — Represents a single invocation of a tool requested by the model, encapsulating its ID, name, and parsed arguments.+- Message · interface · L31-L52 — Defines a turn in a conversation, allowing for structured communication between users and the assistant, including tool calls and raw provider data.+- ToolSpec · interface · L55-L59 — Describes a tool that the model can call, including its name, description, and parameters, facilitating interaction with various tools.+- ResponseFormat · type · L68-L71 — Specifies the format in which the model must respond, ensuring compatibility across different output types like text, JSON, or tool calls.+- Usage · interface · L78-L83 — Tracks token usage across providers, normalizing input and output counts to facilitate consistent accounting in multi-provider environments.+- ChatRequest · interface · L85-L94 — Encapsulates a request to the chat model, including messages, tools, and response format, to standardize interactions with the model.+- ChatResponse · interface · L96-L104 — Represents the response from the chat model, including the assistant's text, tool calls made, and usage statistics, to provide a complete interaction result.+- ChatModel · interface · L110-L113 — Defines a connection to a specific model, providing a method to create chat requests and ensuring consistent interaction with the model.diff --git a/graft/src/ai/providers.md b/graft/src/ai/providers.mdindex 1dff7589..93aa24b5 100644--- a/graft/src/ai/providers.md+++ b/graft/src/ai/providers.md@@ -1,7 +1,7 @@# src/ai/providers.ts · [[configuration-management]]-This file defines configurations for an AI engine, allowing customization and default settings for its operation.+This module provides configuration management for AI model providers, allowing users to specify settings and defaults for various AI services.-- EngineConfig · interface · L9-L25 — EngineConfig provides a structure for user-defined settings, enabling flexibility in configuring the AI engine's behavior.-- ResolvedConfig · interface · L28-L35 — ResolvedConfig represents the final configuration after merging user inputs with defaults and environment variables, ensuring all necessary settings are available.-- resolveConfig · function · L43-L55 — resolveConfig combines user configuration with environment variables and defaults to produce a complete configuration for the AI engine.+- EngineConfig · interface · L17-L39 — Defines the configuration structure for the engine, allowing customization of various parameters for LLM operations.+- ResolvedConfig · interface · L42-L55 — Represents the fully resolved configuration after merging user settings with defaults and environment variables.+- resolveConfig · function · L71-L106 — Merges user-provided configuration with environment variables and defaults to produce a complete configuration object.diff --git a/graft/src/ai/summarize.md b/graft/src/ai/summarize.mdindex bff34287..68e0f0e3 100644--- a/graft/src/ai/summarize.md+++ b/graft/src/ai/summarize.md@@ -1,9 +1,9 @@-# src/ai/summarize.ts · [[code-summarization-and-synthesis]]+# src/ai/summarize.ts · [[code-summarization]]-This file provides functionality to summarize source code files into plain English for a knowledge graph.+This file provides functionality to summarize source code files into concise prose for a knowledge graph, enhancing documentation and understanding of codebases.- Summarizer · interface · L13-L15 — The Summarizer interface defines a contract for summarizing source code files.- userContent · function · L28-L34 — The userContent function formats the source code and its path into a structured string for summarization.-- OpenRouterSummarizer · class · L37-L61 — The OpenRouterSummarizer class implements the Summarizer interface using OpenAI's chat API to generate summaries.-- constructor · method · L41-L48 — The constructor initializes the OpenRouterSummarizer with an API key and model for making API calls.-- summarize · method · L50-L60 — The summarize method generates a summary of the provided code by interacting with the OpenAI API.+- ChatSummarizer · class · L37-L51 — Provides a mechanism to summarize source code files into plain English for knowledge management.+- constructor · method · L38-L38 — Initializes the ChatSummarizer with a specific ChatModel for generating summaries.+- summarize · method · L40-L50 — Generates a summary of the provided source code using the specified ChatModel.diff --git a/graft/src/ai/synthesize.md b/graft/src/ai/synthesize.mdindex 3e98d8aa..57b3c3d4 100644--- a/graft/src/ai/synthesize.md+++ b/graft/src/ai/synthesize.md@@ -1,6 +1,6 @@-# src/ai/synthesize.ts · [[code-summarization-and-synthesis]]+# src/ai/synthesize.ts · [[code-summarization]]-This file defines the architecture for synthesizing a graph of nodes from file summaries, enabling a structured representation of a codebase.+This file defines the architecture for synthesizing a graph of nodes from file summaries, enabling better understanding and navigation of a codebase.- SynthLink · interface · L12-L16 — Defines the structure of a directed edge between nodes, specifying relationships in the synthesized graph.- SynthNode · interface · L19-L27 — Represents a node in the synthesized graph, encapsulating its name, type, summary, sources, and links to other nodes.@@ -8,6 +8,6 @@ This file defines the architecture for synthesizing a graph of nodes from file s- Synthesizer · interface · L35-L37 — Defines the interface for synthesizers that convert file summaries into structured nodes.- userContent · function · L93-L98 — Constructs a formatted string from an array of file summaries, ensuring it does not exceed a specified character limit.- clean · function · L101-L123 — Normalizes and cleans a raw model response into a structured array of SynthNode objects.-- OpenRouterSynthesizer · class · L135-L164 — Implements the Synthesizer interface using OpenRouter's API to generate nodes from file summaries.-- constructor · method · L139-L142 — Initializes the OpenRouterSynthesizer with API key, model, and optional base URL for the OpenAI client.-- synthesize · method · L144-L163 — Processes an array of file summaries to produce a structured array of SynthNode objects by interacting with the OpenAI API.+- ChatSynthesizer · class · L128-L154 — The ChatSynthesizer class implements the Synthesizer interface to create a structured architecture graph using a chat model.+- constructor · method · L129-L129 — The constructor initializes the ChatSynthesizer with a specific chat model for generating architecture graphs.+- synthesize · method · L131-L153 — The synthesize method processes file summaries to produce a curated set of SynthNode objects representing the architecture of the codebase.diff --git a/graft/src/ask/ask.md b/graft/src/ask/ask.mdindex bc0547a5..eebcd84b 100644--- a/graft/src/ask/ask.md+++ b/graft/src/ask/ask.md@@ -1,38 +1,38 @@# src/ask/ask.ts-This file implements a query tool that routes natural language queries to relevant code symbols and returns structured context information.+This module provides a mechanism to process natural language queries and return structured results from a codebase, enhancing the ability to find relevant code snippets and their relationships.- AskHit · interface · L26-L39 — Represents a hit in the query results, encapsulating details about a code symbol and its context.-- AskResult · interface · L45-L62 — Encapsulates the result of a query, including the query string, mode of operation, and the hits found.+- AskResult · interface · L45-L62 — Represents the result of an 'ask' query, encapsulating the query details and the hits found.- firstProse · function · L65-L72 — Extracts the first meaningful prose line from a body of text, ignoring headings and blank lines.-- Corpus · interface · L74-L81 — Defines the structure for a corpus containing concepts and a graph, used for processing queries.-- loadCorpus · function · L83-L108 — Loads a corpus from a specified directory, extracting concepts and building a graph for query processing.-- score · function · L117-L128 — Calculates a score for a document's token counts against a query, facilitating relevance ranking.-- idfFromDf · function · L134-L138 — function idfFromDf(df: Map<string, number>, n: number): Map<string, number>-- computeIdf · function · L140-L145 — function computeIdf(docBags: Array<Set<string>>): Map<string, number>-- computeIdfFromIndex · function · L154-L159 — function computeIdfFromIndex(index: AskIndex, conceptBags: Array<Set<string>>): Map<string, number>-- bm25 · function · L166-L182 — function bm25( query: Map<string, number>, doc: Map<string, number>, idf: Map<string, number>, dl: number, avgdl: number, ): number-- subjectWords · function · L194-L196 — function subjectWords(query: string): string[]-- findSubjectNodes · function · L206-L213 — function findSubjectNodes(query: string, graph: GraphV1): { nodes: NodeV1[]; tried: string }-- StructuralOutcome · type · L221-L221 — type StructuralOutcome = { result: AskResult } | { fallthroughNote: string } | null;-- fallthroughNoteFor · function · L223-L228 — function fallthroughNoteFor(subject: string): string-- structural · function · L230-L279 — Processes a structural query to find and return relevant callers or callees from the graph based on the query.-- hasTerm · function · L298-L300 — function hasTerm(f: Map<string, number>, t: string): boolean-- matchedIdfShare · function · L309-L323 — function matchedIdfShare( q: Map<string, number>, fields: Array<Map<string, number>>, idf: Map<string, number>, dfltIdf: number, ): number-- lexical · function · L325-L487 — Ranks concepts and symbols based on lexical matching with the query, returning the most relevant results.-- bodyLen · function · L416-L420 — bodyLen = (m: Map<string, number>)-- AskOptions · interface · L489-L505 — Defines options for customizing the behavior of the ask function, such as context directory and result limits.+- Corpus · interface · L74-L81 — Defines the structure for holding concepts and graph data used in processing queries.+- loadCorpus · function · L83-L108 — Loads a corpus of concepts and graph data from a specified directory, enabling query processing.+- score · function · L117-L128 — Calculates a score for a document based on its token counts relative to a query, enhancing relevance ranking.+- idfFromDf · function · L134-L138 — Computes the inverse document frequency (IDF) from document frequency (DF) data, aiding in scoring relevance.+- computeIdf · function · L140-L145 — Generates IDF values from document bags, which are used to weight query matches based on term rarity.+- computeIdfFromIndex · function · L154-L159 — Calculates IDF values using precomputed index data, optimizing the scoring process for queries.+- bm25 · function · L166-L182 — Implements the BM25 scoring algorithm to rank documents based on term frequency and document length.+- subjectWords · function · L194-L196 — Tokenizes a query into words while preserving qualified names, facilitating accurate subject resolution.+- findSubjectNodes · function · L206-L213 — Finds nodes in the graph that match the structural subject of a query, enhancing query resolution.+- StructuralOutcome · type · L221-L221 — Defines the possible outcomes of a structural query, indicating whether a result was found, a fallthrough note is needed, or if there was no structural intent.+- fallthroughNoteFor · function · L223-L228 — Generates a note for cases where a structural query falls back to lexical processing, providing user guidance.+- structural · function · L230-L279 — Processes a structural query to find relationships in the graph, returning relevant results or fallthrough notes.+- hasTerm · function · L298-L300 — Checks for the presence of a term in a document's token map, aiding in relevance scoring.+- matchedIdfShare · function · L309-L323 — Calculates the share of query terms matched by a document, weighted by term rarity for relevance assessment.+- lexical · function · L325-L487 — Handles lexical queries by scoring documents based on term matches and relevance, returning structured results.+- bodyLen · function · L416-L420 — Calculates the length of the body of a lexical document to ensure it meets certain criteria for processing.+- AskOptions · interface · L489-L505 — Defines the options available for configuring the ask function, allowing customization of its behavior.- parseSpan · function · L509-L513 — Parses a string pointer into its file path and line range components, facilitating source code navigation.- sliceSpan · function · L517-L532 — Reads a specified range of lines from a source file, allowing for inlined code snippets in query results.-- inlineSource · function · L539-L556 — Attaches inlined source code to query hits, enhancing the context provided to the user.-- hitFiles · function · L560-L569 — function hitFiles(hits: AskHit[]): Set<string>-- baselineFor · function · L574-L589 — function baselineFor(hits: AskHit[], graph: GraphV1 | null): AskResult["saved"] | undefined-- ask · function · L592-L622 — Processes a query against a code graph, returning structured results based on the query type and context.-- SkeletonEntry · interface · L626-L633 — interface SkeletonEntry-- SkeletonResult · interface · L635-L639 — interface SkeletonResult-- skeleton · function · L644-L673 — function skeleton(dir: string, file: string, opts: { contextDir?: string } = {}): SkeletonResult-- startLine · function · L661-L661 — startLine = (span: string)-- formatSkeleton · function · L676-L685 — function formatSkeleton(r: SkeletonResult): string-- toTokens · function · L688-L690 — function toTokens(chars: number): number-- formatAsk · function · L693-L731 — Formats the results of a query into a markdown context pack for easy readability and presentation.-- savingsFooter · function · L736-L748 — function savingsFooter(r: AskResult, body: string): string+- inlineSource · function · L539-L556 — Inlines the source code for the hits found, providing context directly in the results without needing to open files.+- hitFiles · function · L560-L569 — Extracts a set of unique file paths from the hits, indicating which files are relevant to the query results.+- baselineFor · function · L574-L589 — Calculates the baseline file size and character count for the hits, providing a measure of the cost of reading the full files.+- ask · function · L592-L622 — Handles the main logic for processing a query against a directory, returning structured results based on the query type.+- SkeletonEntry · interface · L626-L633 — Defines the structure of a skeleton entry, which represents a piece of information extracted from a file.+- SkeletonResult · interface · L635-L639 — Defines the structure of the result returned from the skeleton function, encapsulating the extracted information.+- skeleton · function · L644-L673 — Extracts a skeleton representation of a file, providing a summary and context for its contents.+- startLine · function · L661-L661 — Calculates the starting line number from a given span, aiding in the extraction of relevant code sections.+- formatSkeleton · function · L676-L685 — Formats the skeleton result into a string representation for display or output purposes.+- toTokens · function · L688-L690 — Converts a character count into a token count, facilitating the processing of text for queries.+- formatAsk · function · L693-L731 — Formats the results of an ask query into a string for presentation, ensuring clarity and usability.+- savingsFooter · function · L736-L748 — Generates a footer for the ask results that summarizes the savings in terms of file reading costs.diff --git a/graft/src/ask/graphrank.md b/graft/src/ask/graphrank.mdindex 675d7af3..a24d4dbe 100644--- a/graft/src/ask/graphrank.md+++ b/graft/src/ask/graphrank.md@@ -1,5 +1,7 @@# src/ask/graphrank.ts-- PageRankOptions · interface · L20-L26 — interface PageRankOptions-- personalizedPageRank · function · L39-L101 — function personalizedPageRank( graph: GraphV1, seeds: Map<string, number>, opts: PageRankOptions = {}, ): Map<string, number>-- link · function · L51-L53 — link = (a: string, b: string)+This module implements a personalized PageRank algorithm to improve the ranking of code nodes based on their structural relevance rather than just lexical similarity.++- PageRankOptions · interface · L20-L26 — Defines options for configuring the personalized PageRank algorithm, including restart probability and iteration count.+- personalizedPageRank · function · L39-L101 — Calculates personalized PageRank scores for nodes in a wiring graph based on provided seeds, enhancing the relevance of code suggestions.+- link · function · L51-L53 — Creates undirected links between nodes in the graph for the PageRank calculation, ensuring that both directions are considered.diff --git a/graft/src/ask/index-file.md b/graft/src/ask/index-file.mdindex 42f59842..03db258f 100644--- a/graft/src/ask/index-file.md+++ b/graft/src/ask/index-file.md@@ -1,11 +1,13 @@# src/ask/index-file.ts-- tokenize · function · L38-L44 — function tokenize(text: string): string[]-- counts · function · L47-L51 — function counts(tokens: string[]): Map<string, number>-- AskIndexDoc · interface · L54-L59 — interface AskIndexDoc-- AskIndex · interface · L63-L69 — interface AskIndex-- askIndexPath · function · L76-L78 — function askIndexPath(outDir: string): string-- pairs · function · L80-L82 — function pairs(m: Map<string, number>): [string, number][]-- bagLen · function · L85-L89 — function bagLen(p: [string, number][]): number-- writeAskIndex · function · L98-L131 — function writeAskIndex(outDir: string, graph: GraphV1): string-- readAskIndex · function · L138-L159 — function readAskIndex(outDir: string): AskIndex | null+This file provides functionality for building and reading a cache of tokenized graph data to optimize query performance.++- tokenize · function · L38-L44 — Tokenizes input text into lowercased subword tokens, ensuring consistent tokenization for both build-time and query-time processes.+- counts · function · L47-L51 — Counts the frequency of each token in a given array, facilitating the creation of term-frequency maps for documents.+- AskIndexDoc · interface · L54-L59 — Defines the structure for storing token bags associated with a single document in the index.+- AskIndex · interface · L63-L69 — Represents the overall structure of the ask index, including document frequencies and average body length for efficient querying.+- askIndexPath · function · L76-L78 — Generates the absolute file path for the ask index sidecar based on the output directory.+- pairs · function · L80-L82 — Converts a Map of token counts into a sorted array format suitable for JSON serialization.+- bagLen · function · L85-L89 — Calculates the total count of tokens in a document's field, representing its length.+- writeAskIndex · function · L98-L131 — Writes the tokenized representation of graph nodes and their frequencies to a JSON file, creating a cache for future queries.+- readAskIndex · function · L138-L159 — Reads and validates the ask index from a file, ensuring data integrity before use in queries.diff --git a/graft/src/claude/format.md b/graft/src/claude/format.mdindex c6b34c13..f65abe06 100644--- a/graft/src/claude/format.md+++ b/graft/src/claude/format.md@@ -1,16 +1,18 @@# src/claude/format.ts-- enrichedSegment · function · L13-L17 — function enrichedSegment(s: Stats): string | null-- freshnessSegment · function · L19-L24 — function freshnessSegment(s: Stats): string-- renderStatusline · function · L26-L48 — function renderStatusline( stats: Stats | null, session: SessionState | null, ctx: { ctxPct: number | null }, ): string[]-- nodeIdsInFile · function · L50-L56 — function nodeIdsInFile(w: GraphV1, filePath: string): Set<string>-- incomingEdges · function · L58-L62 — function incomingEdges(w: GraphV1, filePath: string): EdgeV1[]-- formatBlastRadius · function · L64-L75 — function formatBlastRadius(w: GraphV1, filePath: string, cap = 8): string | null-- AskJson · interface · L77-L84 — interface AskJson-- tokensOf · function · L86-L86 — function tokensOf(chars: number): number-- retrievalBody · function · L91-L108 — function retrievalBody(hits: AskJson['hits']): string-- retrievalTokensSaved · function · L111-L117 — function retrievalTokensSaved(ask: AskJson, cap = 5): number-- formatRetrieval · function · L119-L132 — function formatRetrieval(ask: AskJson, cap = 5): string | null-- relevantRetrieval · function · L152-L163 — function relevantRetrieval(ask: AskJson, s: SessionState, cap = 3): string | null-- formatOrientation · function · L165-L167 — function formatOrientation(indexMd: string, budgetBytes = 1500): string-- renderSubagent · function · L169-L173 — function renderSubagent(agentName: string, session: SessionState | null): string+This file contains functions and types for formatting and rendering status information related to a graph-based system.++- enrichedSegment · function · L13-L17 — Calculates the percentage of enriched items based on the ready count and total count, returning a formatted string if there are any enriched items.+- freshnessSegment · function · L19-L24 — Generates a status message indicating the freshness of the data, highlighting if the data is syncing or stale.+- renderStatusline · function · L26-L48 — Constructs a status line for displaying the current state of the system, including node and edge counts, enrichment status, and session information.+- nodeIdsInFile · function · L50-L56 — Retrieves a set of node IDs from a graph that correspond to a specified file path, filtering based on path matches.+- incomingEdges · function · L58-L62 — Finds all incoming edges for nodes in a graph that correspond to a specified file path, returning those edges that target the nodes.+- formatBlastRadius · function · L64-L75 — Formats a string that describes the blast radius for a given file, listing dependencies and their relationships, up to a specified cap.+- AskJson · interface · L77-L84 — Defines the structure for a JSON object used in retrieval queries, encapsulating query details and hit information.+- tokensOf · function · L86-L86 — Calculates the number of tokens based on character count, facilitating token management in retrieval processes.+- retrievalBody · function · L91-L108 — Constructs a formatted string representation of retrieval hits, including pointers and snippets, for display purposes.+- retrievalTokensSaved · function · L111-L117 — Calculates the number of tokens saved by using a retrieval pack instead of reading files in full, based on the hits and baseline size.+- formatRetrieval · function · L119-L132 — Formats the retrieval results into a string, including details about tokens saved and the estimated size of the retrieval pack.+- relevantRetrieval · function · L152-L163 — Determines if a retrieval pack should be injected based on relevance and novelty, returning the formatted text or null if not applicable.+- formatOrientation · function · L165-L167 — Creates a formatted string representing the orientation of the repository map, limited to a specified byte budget.+- renderSubagent · function · L169-L173 — Generates a string representation of a subagent's status, including its query if available, for display purposes.diff --git a/graft/src/claude/hooks.md b/graft/src/claude/hooks.mdindex 5c638eec..bacbdfd8 100644--- a/graft/src/claude/hooks.md+++ b/graft/src/claude/hooks.md@@ -1,12 +1,14 @@# src/claude/hooks.ts-- readStdin · function · L14-L18 — function readStdin(): any-- safeReadFd0 · function · L19-L19 — function safeReadFd0(): string-- projectDir · function · L21-L23 — function projectDir(input: any): string-- underGraft · function · L24-L27 — function underGraft(dir: string, file: string): boolean-- graftJson · function · L28-L41 — function graftJson(dir: string, args: string[]): any | null-- checkStaleCount · function · L42-L46 — function checkStaleCount(dir: string): number-- emit · function · L47-L49 — function emit(eventName: string, additionalContext: string): void-- handlePostEdit · function · L51-L57 — async function handlePostEdit(input: any, dir: string): Promise<void>-- handleStop · function · L59-L73 — function handleStop(dir: string): void-- main · function · L75-L113 — async function main(event: string): Promise<void>+Handles various events related to the Graft system, including session management and user prompts.++- readStdin · function · L14-L18 — Reads input from standard input, handling test seams and parsing JSON.+- safeReadFd0 · function · L19-L19 — Safely reads from the standard input file descriptor, returning an empty string on failure.+- projectDir · function · L21-L23 — Determines the project directory based on environment variables or input parameters.+- underGraft · function · L24-L27 — Checks if a given file is part of the graft project structure.+- graftJson · function · L28-L41 — Executes a command to retrieve JSON output from the graft CLI, handling errors gracefully.+- checkStaleCount · function · L42-L46 — Counts the number of changes in the graft graph to determine if it is stale.+- emit · function · L47-L49 — Outputs a JSON object to standard output for event tracking.+- handlePostEdit · function · L51-L57 — Handles post-edit events by updating stats and emitting relevant information.+- handleStop · function · L59-L73 — Handles the stop event by syncing state if necessary.+- main · function · L75-L113 — Main entry point for handling various events and orchestrating the application logic.diff --git a/graft/src/claude/init.md b/graft/src/claude/init.mdindex 5a598067..02da9616 100644--- a/graft/src/claude/init.md+++ b/graft/src/claude/init.md@@ -1,4 +1,6 @@# src/claude/init.ts-- InitResult · interface · L9-L15 — interface InitResult-- runInit · function · L17-L49 — function runInit(dir: string, opts: { build?: boolean; cliPath?: string } = {}): InitResult+Initializes the Claude environment by setting up necessary directories, configuration files, and shims for the application.++- InitResult · interface · L9-L15 — Defines the structure of the result returned by the runInit function, encapsulating settings, shims, skill, warnings, and build status.+- runInit · function · L17-L49 — Initializes the Claude environment by setting up necessary directories, merging settings, creating shims, and optionally building the project.diff --git a/graft/src/claude/paths.md b/graft/src/claude/paths.mdindex 2cb74329..56e267c0 100644--- a/graft/src/claude/paths.md+++ b/graft/src/claude/paths.md@@ -1,5 +1,7 @@# src/claude/paths.ts-- graftCliPath · function · L11-L13 — function graftCliPath(): string-- claudeDistDir · function · L18-L20 — function claudeDistDir(): string-- claudeScriptPath · function · L23-L25 — function claudeScriptPath(name: string): string+This module provides utility functions to resolve paths for the graft CLI and related scripts, ensuring correct path resolution regardless of the installation context.++- graftCliPath · function · L11-L13 — Provides the absolute path to the graft CLI, ensuring it can be located regardless of the installation context.+- claudeDistDir · function · L18-L20 — Returns the absolute path to the package's distribution directory, facilitating consistent access to resources without guesswork.+- claudeScriptPath · function · L23-L25 — Constructs the absolute path to a sibling script in the claude directory, enabling dynamic script resolution.diff --git a/graft/src/claude/settings-merge.md b/graft/src/claude/settings-merge.mdindex bc63fd01..85a5da61 100644--- a/graft/src/claude/settings-merge.md+++ b/graft/src/claude/settings-merge.md@@ -1,7 +1,9 @@-# src/claude/settings-merge.ts+# src/claude/settings-merge.ts · [[configuration-management]]-- Json · type · L1-L1 — type Json = Record<string, any>;-- hookCmd · function · L7-L9 — function hookCmd(arg: string): string-- graftBlocks · function · L10-L17 — function graftBlocks(): Record<string, Json>-- isGraftHookEntry · function · L18-L20 — function isGraftHookEntry(entry: Json): boolean-- mergeGraftSettings · function · L22-L55 — function mergeGraftSettings(existing: Json): { merged: Json; warnings: string[] }+Merges existing settings with new graft configurations, ensuring proper command hooks and permissions are set while avoiding conflicts.++- Json · type · L1-L1 — Defines a flexible JSON type for various settings configurations.+- hookCmd · function · L7-L9 — Generates a command string to execute a specified hook in the Graft environment.+- graftBlocks · function · L10-L17 — Creates a mapping of events to their corresponding Graft command hooks for processing user actions.+- isGraftHookEntry · function · L18-L20 — Checks if a given entry is a Graft hook by inspecting its command reference.+- mergeGraftSettings · function · L22-L55 — Merges existing settings with Graft-specific configurations, ensuring idempotency and compliance with Graft rules.diff --git a/graft/src/claude/shim-template.md b/graft/src/claude/shim-template.mdindex 54b2a047..8433066f 100644--- a/graft/src/claude/shim-template.md+++ b/graft/src/claude/shim-template.md@@ -1,5 +1,7 @@# src/claude/shim-template.ts-- shim · function · L16-L60 — function shim(entryFile: string, call: string, bakedDir: string): string-- statuslineShim · function · L62-L62 — function statuslineShim(bakedDir: string): string-- hooksShim · function · L63-L63 — function hooksShim(bakedDir: string): string+Generates shims to dynamically locate and execute the correct version of the @nanonets/graft package's entry points, ensuring compatibility across different installation methods.++- shim · function · L16-L60 — Generates a script that dynamically locates and executes a specified entry file from the installed graft package, ensuring compatibility across various installation methods.+- statuslineShim · function · L62-L62 — Creates a shim for the statusline entry of the graft package, facilitating its execution in a consistent manner.+- hooksShim · function · L63-L63 — Creates a shim for the hooks entry of the graft package, enabling its execution with command-line arguments.diff --git a/graft/src/claude/skill-template.md b/graft/src/claude/skill-template.mdindex 4b6deeb8..aad781a4 100644--- a/graft/src/claude/skill-template.md+++ b/graft/src/claude/skill-template.md@@ -1,3 +1,5 @@# src/claude/skill-template.ts-- skillTemplate · function · L6-L76 — function skillTemplate(): string+Provides a structured template for the graft Claude Code skill, enabling efficient onboarding and understanding of the codebase.++- skillTemplate · function · L6-L76 — Generates a markdown string that serves as a comprehensive guide for using the graft tool effectively within a code repository.diff --git a/graft/src/claude/state.md b/graft/src/claude/state.mdindex 18219c72..ebc12b22 100644--- a/graft/src/claude/state.md+++ b/graft/src/claude/state.md@@ -1,19 +1,21 @@# src/claude/state.ts-- Stats · interface · L4-L9 — interface Stats-- SessionState · interface · L10-L20 — interface SessionState-- emptyStats · function · L24-L27 — function emptyStats(): Stats-- emptySession · function · L28-L30 — function emptySession(): SessionState-- cacheDir · function · L32-L32 — function cacheDir(projectDir: string): string-- statsPath · function · L33-L33 — function statsPath(d: string): string-- sessionPath · function · L34-L34 — function sessionPath(d: string, id: string): string-- lockPath · function · L35-L35 — function lockPath(d: string): string-- readJson · function · L37-L39 — function readJson<T>(p: string): T | null-- writeJsonAtomic · function · L40-L45 — function writeJsonAtomic(p: string, value: unknown): void-- readStats · function · L47-L47 — function readStats(d: string): Stats | null-- writeStats · function · L48-L48 — function writeStats(d: string, s: Stats): void-- patchStats · function · L51-L55 — function patchStats(d: string, patch: Partial<Stats>): Stats-- readSession · function · L56-L58 — function readSession(d: string, id: string): SessionState-- writeSession · function · L59-L61 — function writeSession(d: string, id: string, s: SessionState): void-- acquireLock · function · L63-L79 — function acquireLock(d: string): boolean-- releaseLock · function · L80-L80 — function releaseLock(d: string): void+Manages application state and session data, including statistics and file locking mechanisms.++- Stats · interface · L4-L9 — Defines the structure for tracking various statistics related to nodes and edges in the system.+- SessionState · interface · L10-L20 — Defines the structure for maintaining the state of a session, including queries and token savings.+- emptyStats · function · L24-L27 — Creates and returns an initial empty Stats object to reset statistics tracking.+- emptySession · function · L28-L30 — Creates and returns an initial empty SessionState object to reset session tracking.+- cacheDir · function · L32-L32 — Constructs the path to the cache directory for a given project.+- statsPath · function · L33-L33 — Generates the file path for storing statistics in JSON format.+- sessionPath · function · L34-L34 — Generates the file path for storing session data in JSON format.+- lockPath · function · L35-L35 — Generates the file path for the synchronization lock used in the caching mechanism.+- readJson · function · L37-L39 — Reads and parses a JSON file, returning the content or null if an error occurs.+- writeJsonAtomic · function · L40-L45 — Writes a JSON object to a file atomically, ensuring no data corruption during the write process.+- readStats · function · L47-L47 — Reads the statistics from the specified path, returning null if not found.+- writeStats · function · L48-L48 — Writes the provided statistics to the specified path in JSON format.+- patchStats · function · L51-L55 — Updates the existing statistics with a patch and writes the updated stats back to storage.+- readSession · function · L56-L58 — Reads the session data from the specified path, returning an empty session if not found.+- writeSession · function · L59-L61 — Writes the session data to the specified path in JSON format.+- acquireLock · function · L63-L79 — Attempts to acquire a lock for the specified directory to prevent concurrent access issues.+- releaseLock · function · L80-L80 — Releases the lock for the specified directory, allowing other processes to access it.diff --git a/graft/src/claude/stats.md b/graft/src/claude/stats.mdindex 4fb546f6..9f3cd7b0 100644--- a/graft/src/claude/stats.md+++ b/graft/src/claude/stats.md@@ -1,4 +1,6 @@# src/claude/stats.ts-- readWiring · function · L6-L10 — function readWiring(projectDir: string): GraphV1 | null-- computeStats · function · L12-L25 — function computeStats( w: GraphV1, ): Pick<Stats, 'nodeCount' | 'edgeCount' | 'languages' | 'totalCount' | 'readyCount'>+This module provides functions to read wiring data from a JSON file and compute statistics about graph nodes and edges, facilitating analysis of project structure.++- readWiring · function · L6-L10 — Loads and parses the wiring configuration from a JSON file, returning the graph structure or null if an error occurs.+- computeStats · function · L12-L25 — Calculates and returns statistics about the nodes and edges in a graph, including counts and languages used.diff --git a/graft/src/claude/statusline.md b/graft/src/claude/statusline.mdindex 8163bac4..9043f7c5 100644--- a/graft/src/claude/statusline.md+++ b/graft/src/claude/statusline.md@@ -1,4 +1,4 @@# src/claude/statusline.ts-- resolveStats · function · L14-L20 — function resolveStats(dir: string): Stats | null-- main · function · L22-L33 — function main(): void+- resolveStats · function · L14-L20 — Determines the current statistics of the project, either from a cache or by reading the wiring graph directly.+- main · function · L22-L33 — Handles input and orchestrates the rendering of the status line or subagent output based on the provided context.diff --git a/graft/src/claude/sync-run.md b/graft/src/claude/sync-run.mdindex 5f04883d..f4369517 100644--- a/graft/src/claude/sync-run.md+++ b/graft/src/claude/sync-run.md@@ -1,5 +1,7 @@# src/claude/sync-run.ts-- realBuild · function · L8-L11 — function realBuild(dir: string): void-- runSync · function · L13-L27 — function runSync(dir: string, build: (d: string) => void = realBuild): void-- main · function · L29-L32 — function main(): void+Coordinates the synchronous build process and updates the system state based on the build results.++- realBuild · function · L8-L11 — Executes a build process for a specified directory, ensuring it adheres to specific constraints.+- runSync · function · L13-L27 — Coordinates the build process and updates the system state based on the build outcome.+- main · function · L29-L32 — Initiates the synchronization process when the script is executed directly with a specified directory.diff --git a/graft/src/cli-epilogue.md b/graft/src/cli-epilogue.mdindex 6e9e7e91..44b38986 100644--- a/graft/src/cli-epilogue.md+++ b/graft/src/cli-epilogue.md@@ -1,7 +1,9 @@# src/cli-epilogue.ts-- indigo · function · L23-L23 — indigo = (s: string)-- muted · function · L24-L24 — muted = (s: string)-- Step · interface · L26-L31 — interface Step-- InitEpilogueOptions · interface · L33-L40 — interface InitEpilogueOptions-- formatInitEpilogue · function · L44-L85 — function formatInitEpilogue(opts: InitEpilogueOptions): string+Generates a closing message for the `graft init` command, including next steps and a visual wordmark.++- indigo · function · L23-L23 — Applies a specific color formatting to a string for terminal output.+- muted · function · L24-L24 — Applies a muted color formatting to a string for terminal output.+- Step · interface · L26-L31 — Defines the structure for a step in the epilogue, including a label and command.+- InitEpilogueOptions · interface · L33-L40 — Specifies options for rendering the init epilogue, including graph status and node/edge counts.+- formatInitEpilogue · function · L44-L85 — Formats and returns the next-steps epilogue for the `graft init` command based on provided options.diff --git a/graft/src/cli-meta.md b/graft/src/cli-meta.mdindex fe56c3fb..9b607285 100644--- a/graft/src/cli-meta.md+++ b/graft/src/cli-meta.md@@ -1,13 +1,15 @@# src/cli-meta.ts-- resolvePackageJsonPath · function · L17-L24 — function resolvePackageJsonPath(moduleUrl: string): string-- readCurrentVersion · function · L27-L31 — function readCurrentVersion(moduleUrl: string): string-- isRunningViaNpx · function · L35-L37 — function isRunningViaNpx(moduleUrl: string): boolean-- NpmViewResult · interface · L39-L42 — interface NpmViewResult-- getNpmViewVersion · function · L46-L60 — function getNpmViewVersion(pkgName: string = PKG_NAME, timeoutMs = 2000): NpmViewResult-- formatVersionReport · function · L63-L73 — function formatVersionReport(current: string, latest: NpmViewResult): string-- globalRoot · function · L76-L87 — function globalRoot(): string | null-- readGlobalInstalledVersion · function · L92-L103 — function readGlobalInstalledVersion(pkgName: string = PKG_NAME): string | null-- UpgradeResult · interface · L105-L113 — interface UpgradeResult-- formatUpgradeReport · function · L116-L127 — function formatUpgradeReport(result: UpgradeResult): string-- runUpgrade · function · L132-L143 — function runUpgrade(moduleUrl: string): UpgradeResult+This file provides support for version management and upgrade functionality for the graft package, including version resolution and reporting.++- resolvePackageJsonPath · function · L17-L24 — Determines the path to the package.json file for a given module URL, enabling access to package metadata.+- readCurrentVersion · function · L27-L31 — Retrieves the current version of the graft package from its package.json file, ensuring the application uses the correct version.+- isRunningViaNpx · function · L35-L37 — Checks if the current module is executed from an npx cache directory, affecting how upgrades are handled.+- NpmViewResult · interface · L39-L42 — Defines the structure for the result of an npm view command, indicating success and the version of a package.+- getNpmViewVersion · function · L46-L60 — Fetches the version of a specified package from npm, handling errors gracefully to ensure reliability.+- formatVersionReport · function · L63-L73 — Formats a report on the current and latest package versions for user-friendly output.+- globalRoot · function · L76-L87 — Determines the global npm node_modules directory, accommodating various installation layouts.+- readGlobalInstalledVersion · function · L92-L103 — Reads the installed version of a package directly from the global node_modules directory, providing accurate local versioning.+- UpgradeResult · interface · L105-L113 — Defines the structure for the result of an upgrade operation, indicating whether it was executed and its success status.+- formatUpgradeReport · function · L116-L127 — Generates a user-friendly report after an upgrade attempt, indicating success or failure.+- runUpgrade · function · L132-L143 — Executes the upgrade process for the graft package, ensuring the latest version is installed unless running via npx.diff --git a/graft/src/cli.md b/graft/src/cli.mdindex 36f27da2..47f8b479 100644--- a/graft/src/cli.md+++ b/graft/src/cli.md@@ -1,7 +1,9 @@# src/cli.ts-This file implements the `graft` CLI tool for building and maintaining a context graph from code, ensuring it stays in sync with the repository.+Defines the command-line interface for the graft tool, enabling various operations on the codebase's context graph.-- engineFrom · function · L43-L46 — Creates an instance of the Graft engine configured with the specified context directory.-- fmt · function · L82-L86 — Formats a record of counts into a human-readable string for console output.-- traverseAction · function · L257-L263 — function traverseAction(kind: import("./graph/traverse-cli.js").TraverseKind)+- GlobalOpts · interface · L48-L54 — Holds the global options for the CLI, allowing configuration of the context graph generation and LLM provider settings.+- cliConfig · function · L57-L66 — Constructs the configuration object for the engine based on CLI options, ensuring the correct parameters are used for graph generation.+- engineFrom · function · L68-L70 — Creates an instance of the Graft engine using the current CLI configuration, enabling graph operations.+- fmt · function · L106-L110 — Formats a record of counts into a human-readable string for console output.+- traverseAction · function · L287-L293 — Handles traversal commands for graph analysis, allowing users to query relationships between symbols in the codebase.diff --git a/graft/src/context/build.md b/graft/src/context/build.mdindex a7408c6a..d8f001a5 100644--- a/graft/src/context/build.md+++ b/graft/src/context/build.md@@ -1,4 +1,4 @@-# src/context/build.ts · [[caching-mechanism]] [[graph-construction]]+# src/context/build.tsThis file builds a context graph from a code repository by summarizing source files and synthesizing nodes.diff --git a/graft/src/context/check.md b/graft/src/context/check.mdindex 16080632..7909085b 100644--- a/graft/src/context/check.md+++ b/graft/src/context/check.md@@ -1,4 +1,4 @@-# src/context/check.ts · [[graph-construction]]+# src/context/check.ts · [[graph-synchronization]]This file provides functionality to verify if the committed context graph is synchronized with the current codebase, ensuring consistency in CI environments.diff --git a/graft/src/engine.md b/graft/src/engine.mdindex dfb74203..ce78085c 100644--- a/graft/src/engine.md+++ b/graft/src/engine.md@@ -1,19 +1,19 @@-# src/engine.ts+# src/engine.ts · [[error-handling-and-reporting]]-The Context Graph Engine builds and checks a code context graph from a repository without a database.+The Graft class manages the construction and validation of a context graph from a code repository, ensuring it remains in sync with the codebase.-- InitOptions · interface · L26-L31 — Defines options for initializing the context graph build, including code extensions and a progress callback.-- CheckRunOptions · interface · L33-L35 — Specifies options for checking the context graph, allowing for code extensions to be included.-- GraphRunOptions · interface · L37-L43 — Defines options for running the graph building process, including LLM usage and concurrency settings.-- Graft · class · L45-L128 — Encapsulates methods for building and checking a context graph from a code repository.-- constructor · method · L48-L50 — Initializes the Graft class with a configuration, resolving the necessary settings for the context graph.-- init · method · L53-L62 — Builds the context graph from the specified directory, utilizing various options and configurations.-- check · method · L65-L67 — Checks if the committed context graph is in sync with the code in the specified directory.-- checkGraph · method · L70-L72 — Verifies if the committed graph.json file is in sync with the code, focusing on the Tier-1 differences.-- graph · method · L79-L86 — Builds a per-symbol code graph from the repository, optionally using a meaning layer with LLM.-- ask · method · L93-L95 — Processes a query against the committed graph to return relevant information based on structural and lexical ranking.-- requireKey · method · L98-L106 — Ensures that a valid OpenRouter API key is available, throwing an error if it is not set.-- synthesizer · method · L108-L111 — Retrieves the synthesizer instance, creating one if it is not already configured.-- cruxSummarizer · method · L114-L116 — Creates a crux summarizer for the code graph's Tier-2 pass, ensuring it is properly configured.-- summarizer · method · L118-L121 — Obtains the summarizer instance, initializing it if no custom summarizer is provided.-- modelLabel · method · L124-L127 — Determines the human-readable label for the active model used in the context graph.+- InitOptions · interface · L28-L33 — Defines options for initializing the context graph build, including code extensions and a progress callback.+- CheckRunOptions · interface · L35-L37 — Specifies options for checking the context graph, allowing for code extensions to be included.+- GraphRunOptions · interface · L39-L45 — Defines options for running the graph building process, including LLM usage and concurrency settings.+- Graft · class · L47-L140 — Manages the context graph operations, including building and checking synchronization with the codebase.+- constructor · method · L50-L52 — Initializes the Graft class with a configuration, resolving the necessary settings for the context graph.+- init · method · L55-L64 — Builds the context graph from the specified directory, utilizing various options and configurations.+- check · method · L67-L69 — Checks if the committed context graph is in sync with the code in the specified directory.+- checkGraph · method · L72-L74 — Verifies if the committed graph.json file is in sync with the code, focusing on the Tier-1 differences.+- graph · method · L81-L88 — Builds a per-symbol code graph from the repository, optionally using a meaning layer with LLM.+- ask · method · L95-L97 — Processes a query against the context graph, returning results based on structural and lexical analysis.+- chatModel · method · L102-L119 — Retrieves the configured chat model or throws an error if the API key is missing, ensuring proper setup for LLM operations.+- synthesizer · method · L121-L123 — Provides the synthesizer for generating responses, defaulting to a chat synthesizer if none is configured.+- cruxSummarizer · method · L126-L128 — Returns a crux summarizer for the Tier-2 pass of the code graph, ensuring detailed summarization of nodes.+- summarizer · method · L130-L132 — Fetches the summarizer for generating summaries, defaulting to a chat summarizer if not explicitly set.+- modelLabel · method · L135-L139 — Determines the human-readable label for the active model, which is recorded in the manifest for reference.diff --git a/graft/src/graph/bindings.md b/graft/src/graph/bindings.mdindex a3e2b888..1455d429 100644--- a/graft/src/graph/bindings.md+++ b/graft/src/graph/bindings.md@@ -1,21 +1,23 @@# src/graph/bindings.ts-- FileBindings · class · L18-L33 — class FileBindings-- set · method · L21-L23 — set(scopePath: string, name: string, type: string): void-- lookup · method · L26-L32 — lookup(scope: string[], name: string): string | null-- defName · function · L45-L77 — function defName(node: Parser.SyntaxNode, lang: Language): string | null-- goReceiverVarOf · function · L81-L85 — function goReceiverVarOf(node: Parser.SyntaxNode): string | null-- goReceiverTypeOf · function · L91-L97 — function goReceiverTypeOf(node: Parser.SyntaxNode): string | null-- resolveRecvType · function · L103-L121 — function resolveRecvType( receiver: string | undefined, ctx: Pick<WalkCtx, "scope" | "enclosingClass" | "goReceiverVar" | "lang" | "bindings">, ): string | undefined-- isClassNode · function · L123-L129 — function isClassNode(node: Parser.SyntaxNode, lang: Language): boolean-- collectBindings · function · L132-L138 — function collectBindings(root: Parser.SyntaxNode, lang: Language): FileBindings-- collectAliases · function · L142-L156 — function collectAliases(node: Parser.SyntaxNode, lang: Language, aliases: Map<string, string>): void-- visit · function · L162-L182 — function visit( node: Parser.SyntaxNode, lang: Language, scope: string[], classScope: string | null, bindings: FileBindings, aliases: Map<string, string>, ): void-- resolveAlias · function · L188-L190 — function resolveAlias(name: string, aliases: Map<string, string>): string-- pyTypeName · function · L192-L200 — function pyTypeName(node: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null-- callTypeName · function · L202-L207 — function callTypeName(node: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null-- handlePy · function · L209-L239 — function handlePy( node: Parser.SyntaxNode, scope: string[], classScope: string | null, bindings: FileBindings, aliases: Map<string, string>, ): void-- tsAnnotationTypeName · function · L241-L248 — function tsAnnotationTypeName( typeAnn: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>, ): string | null-- tsNewTypeName · function · L250-L255 — function tsNewTypeName(value: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null-- handleTs · function · L257-L285 — function handleTs( node: Parser.SyntaxNode, scope: string[], classScope: string | null, bindings: FileBindings, aliases: Map<string, string>, ): void-- handleGo · function · L287-L322 — function handleGo(node: Parser.SyntaxNode, scope: string[], bindings: FileBindings): void+This file implements a binding pass that resolves variable types in a parsed file, enabling accurate type lookups for local variables, parameters, and class fields during code analysis.++- FileBindings · class · L18-L33 — Manages the mapping of variable/field names to their types within different scopes, enabling type resolution during code analysis.+- set · method · L21-L23 — Records the type of a variable or field in the specified scope, allowing for later retrieval during type resolution.+- lookup · method · L26-L32 — Retrieves the type associated with a variable or field name from the closest matching scope, facilitating type resolution in nested contexts.+- defName · function · L45-L77 — Determines the name of a definition node (like a function or class) based on its syntax, aiding in the identification of types during analysis.+- goReceiverVarOf · function · L81-L85 — Extracts the variable name of the receiver parameter from a Go method node, which is essential for understanding method context.+- goReceiverTypeOf · function · L91-L97 — Determines the base type of a receiver in a Go method, which is crucial for type resolution in method calls.+- resolveRecvType · function · L103-L121 — Resolves the type of a receiver in a method call based on the current context, ensuring accurate type information is used during analysis.+- isClassNode · function · L123-L129 — Checks if a given node represents a class definition, which is important for understanding the structure of the code being analyzed.+- collectBindings · function · L132-L138 — Traverses a parsed syntax tree to gather variable-to-type bindings, which are essential for type resolution in the codebase.+- collectAliases · function · L142-L156 — Scans the syntax tree to collect import aliases, ensuring that type resolution accounts for aliased names in the code.+- visit · function · L162-L182 — Recursively processes nodes in the syntax tree to build up type bindings and scopes, facilitating comprehensive type analysis.+- resolveAlias · function · L188-L190 — Resolves a name through the collected aliases, ensuring that type lookups are accurate even when using aliased names.+- pyTypeName · function · L192-L200 — Extracts and resolves the type name from a Python node, which is necessary for accurate type binding in Python code.+- callTypeName · function · L202-L207 — Determines the type name from a call expression, which is important for understanding the types of function calls in the code.+- handlePy · function · L209-L239 — Handles the processing of Python nodes to extract type information, contributing to the overall type resolution process.+- tsAnnotationTypeName · function · L241-L248 — Extracts the type name from TypeScript annotation nodes, which is crucial for type resolution in TypeScript code.+- tsNewTypeName · function · L250-L255 — Determines the type name from a TypeScript new expression, aiding in the resolution of types during analysis.+- handleTs · function · L257-L285 — Processes TypeScript nodes to gather type information, which is essential for accurate type resolution in TypeScript code.+- handleGo · function · L287-L322 — Handles the processing of Go nodes to extract type information, ensuring that type resolution is accurate for Go code.diff --git a/graft/src/graph/build.md b/graft/src/graph/build.mdindex 15198999..c6c27cfd 100644--- a/graft/src/graph/build.md+++ b/graft/src/graph/build.md@@ -1,9 +1,9 @@-# src/graph/build.ts · [[error-handling-and-reporting]] [[graph-construction]]+# src/graph/build.ts · [[error-handling-and-reporting]]-This file defines the logic to build a graph representation from source code files in a repository.+This file defines the logic for building a graph representation of a code repository, including parsing source files and resolving dependencies.- GraphBuildOptions · interface · L23-L36 — This interface specifies options for customizing the graph build process, including output directory and summarization settings.- GraphBuildResult · interface · L38-L51 — This interface outlines the structure of the result returned from the graph build process, detailing the generated graph's metadata and statistics.- listSourceFiles · function · L54-L56 — This function retrieves a list of source files from a given directory, excluding the output directory and unsupported languages.-- readGoModules · function · L62-L76 — function readGoModules(root: string): GoModule[]-- buildGraph · function · L78-L183 — This function orchestrates the process of reading source files, extracting nodes and edges, and writing the resulting graph to a file.+- readGoModules · function · L62-L76 — This function identifies and reads Go modules from the repository to facilitate edge resolution for Go import paths.+- buildGraph · function · L78-L183 — This function orchestrates the entire graph building process, from parsing source files to writing the final graph output.diff --git a/graft/src/graph/check.md b/graft/src/graph/check.mdindex b131b5e3..41808af1 100644--- a/graft/src/graph/check.md+++ b/graft/src/graph/check.md@@ -1,4 +1,4 @@-# src/graph/check.ts · [[error-handling-and-reporting]] [[graph-construction]]+# src/graph/check.ts · [[graph-synchronization]]Ensures that the committed graph.json accurately reflects the current state of the codebase, identifying any discrepancies.diff --git a/graft/src/graph/extract.md b/graft/src/graph/extract.mdindex 2df7e249..1bafd03a 100644--- a/graft/src/graph/extract.md+++ b/graft/src/graph/extract.md@@ -1,27 +1,27 @@-# src/graph/extract.ts+# src/graph/extract.ts · [[graph-extraction-and-loading]]-This module extracts structured data from source files into a normalized format for further processing.+This file provides functionality to extract and represent code structure from source files into a standardized format for further processing.-- Language · type · L18-L18 — Defines the supported programming languages for extraction.-- languageOf · function · L21-L28 — Determines the programming language of a given file path.-- RawEdge · interface · L34-L45 — Represents an unresolved edge in the extraction process, linking nodes in the graph.+- Language · type · L18-L18 — Defines a type representing the supported programming languages for extraction.+- languageOf · function · L21-L28 — Determines the programming language of a given file path based on its extension.+- RawEdge · interface · L34-L45 — Represents an unresolved edge in the code structure that will be resolved later during processing.- ExtractResult · interface · L47-L50 — Holds the result of the extraction process, containing nodes and raw edges.-- searchBody · function · L67-L70 — function searchBody(text: string, max = MAX_BODY_CHARS): string-- fileResidual · function · L78-L89 — function fileResidual(source: string, symbols: NodeV1[]): string-- WalkCtx · interface · L136-L147 — Context for walking through the syntax tree during extraction, maintaining state and scope.-- DefDescriptor · interface · L150-L156 — Describes a definition in the syntax tree, including its name and type.-- parseSource · function · L164-L166 — function parseSource(source: string): Parser.SyntaxNode-- extractFile · function · L168-L209 — Extracts nodes and edges from a source file based on its syntax tree.+- searchBody · function · L67-L70 — Normalizes and truncates the body of a code definition for efficient searching.+- fileResidual · function · L78-L89 — Extracts the module-level residual content from a source file that is not covered by any symbol definitions.+- WalkCtx · interface · L136-L147 — Contextual information used during the traversal of the syntax tree for code extraction.+- DefDescriptor · interface · L150-L156 — Describes a code definition with its relevant metadata for extraction purposes.+- parseSource · function · L164-L166 — Parses the source code into a syntax tree while handling large files in manageable chunks.+- extractFile · function · L168-L209 — Extracts nodes and edges from a source file, representing its structure in a standardized format.- walk · function · L211-L278 — Recursively traverses the syntax tree to collect definitions and their relationships.-- describe · function · L282-L313 — Identifies and describes definitions in the syntax tree based on their node types.-- describeGo · function · L318-L356 — function describeGo(node: Parser.SyntaxNode, _ctx: WalkCtx): DefDescriptor | null-- goReceiverType · function · L360-L366 — function goReceiverType(node: Parser.SyntaxNode): string | null-- goExported · function · L370-L374 — function goExported(name: string): boolean+- describe · function · L282-L313 — Identifies and describes the shape of code definitions based on their syntax tree representation.+- describeGo · function · L318-L356 — Describes Go-specific code definitions, including functions and methods, from the syntax tree.+- goReceiverType · function · L360-L366 — Extracts the base type name of a receiver for Go methods, if applicable.+- goExported · function · L370-L374 — Determines if a Go symbol is exported based on its naming convention.- heritageEdges · function · L376-L403 — Generates edges representing class inheritance and implementation relationships.-- calleeName · function · L405-L428 — Extracts the name of a function or method being called in the syntax tree.-- pyReceiver · function · L432-L441 — function pyReceiver(fn: Parser.SyntaxNode): string | undefined-- tsReceiver · function · L444-L454 — function tsReceiver(fn: Parser.SyntaxNode): string | undefined-- isImport · function · L456-L461 — Determines if a node represents an import statement in the syntax tree.-- importSpecifier · function · L463-L479 — Extracts the module name from an import statement in the syntax tree.+- calleeName · function · L405-L428 — Extracts the name and context of a function call from the syntax tree, including receiver information.+- pyReceiver · function · L432-L441 — Identifies the receiver of a Python method call from its syntax tree representation.+- tsReceiver · function · L444-L454 — Identifies the receiver of a TypeScript method call from its syntax tree representation.+- isImport · function · L456-L461 — Determines if a syntax node represents an import statement in the code.+- importSpecifier · function · L463-L479 — Extracts the module path from an import statement in the syntax tree.- clean · function · L482-L489 — Cleans and normalizes a function signature by removing unnecessary whitespace and punctuation.- tsExported · function · L492-L499 — Checks if a node is exported based on its ancestor nodes in the syntax tree.diff --git a/graft/src/graph/load.md b/graft/src/graph/load.mdindex bf4e4f85..14ce329c 100644--- a/graft/src/graph/load.md+++ b/graft/src/graph/load.md@@ -1,8 +1,10 @@-# src/graph/load.ts+# src/graph/load.ts · [[graph-extraction-and-loading]]-- CacheEntry · interface · L31-L35 — interface CacheEntry<T>-- __resetParseCounts · function · L45-L48 — function __resetParseCounts(): void-- statOf · function · L50-L57 — function statOf(path: string): { mtimeMs: number; size: number } | null-- loadCached · function · L59-L81 — function loadCached<T>( cache: Map<string, CacheEntry<T>>, path: string, parse: () => T | null, onParse: () => void, ): T | null-- loadGraphCached · function · L86-L91 — function loadGraphCached(outDir: string): GraphV1 | null-- loadAskIndexCached · function · L95-L100 — function loadAskIndexCached(outDir: string): AskIndex | null+This module implements a caching mechanism to optimize the loading of graph and ask index data by avoiding unnecessary re-parsing of files when their metadata has not changed.++- CacheEntry · interface · L31-L35 — Defines the structure for cache entries, encapsulating the metadata and value of cached items to facilitate efficient cache management.+- __resetParseCounts · function · L45-L48 — Resets the counters that track the number of cache misses for graph and ask index parsing, ensuring a clean state for tests.+- statOf · function · L50-L57 — Retrieves the metadata (mtime and size) of a file, returning null if the file does not exist, which is essential for cache validation.+- loadCached · function · L59-L81 — Loads a cached value from a specified cache, re-parsing the value if the file's metadata has changed, thus ensuring up-to-date data retrieval.+- loadGraphCached · function · L86-L91 — Caches the result of reading a graph from a file, ensuring that it is only re-read when the file's metadata indicates a change.+- loadAskIndexCached · function · L95-L100 — Caches the result of reading an ask index from a file, ensuring that it is only re-read when the file's metadata indicates a change.diff --git a/graft/src/graph/map.md b/graft/src/graph/map.mdindex 327107fc..82bf378c 100644--- a/graft/src/graph/map.md+++ b/graft/src/graph/map.md@@ -1,17 +1,19 @@# src/graph/map.ts-- Hub · interface · L25-L31 — interface Hub-- DirEntry · interface · L33-L39 — interface DirEntry-- RepoMap · interface · L41-L49 — interface RepoMap-- BuildRepoMapOptions · interface · L51-L58 — interface BuildRepoMapOptions-- dirKey · function · L70-L73 — function dirKey(path: string, depth: number): string-- computeInDegree · function · L78-L85 — function computeInDegree(graph: GraphV1): Map<string, number>-- topHubs · function · L90-L96 — function topHubs(nodes: NodeV1[], inDegree: Map<string, number>, cap: number): Hub[]-- sortedLanguages · function · L98-L105 — function sortedLanguages(paths: string[]): string[]-- buildRepoMap · function · L112-L180 — function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RepoMap-- depthFor · function · L137-L137 — depthFor = (path: string): number-- basenameOf · function · L184-L187 — function basenameOf(path: string): string-- formatDirHub · function · L189-L191 — function formatDirHub(h: Hub): string-- formatDirLine · function · L193-L198 — function formatDirLine(d: DirEntry): string-- formatHotspot · function · L200-L202 — function formatHotspot(h: Hub): string-- formatRepoMap · function · L210-L223 — function formatRepoMap(map: RepoMap): string+Builds a structured representation of a repository's file and symbol organization based on their relationships, facilitating easier navigation and understanding of the codebase.++- Hub · interface · L25-L31 — Defines the structure of a hub in the repository map, capturing its essential attributes for identification and ranking.+- DirEntry · interface · L33-L39 — Represents a directory entry in the repository map, summarizing its contents and associated hubs for better navigation.+- RepoMap · interface · L41-L49 — Encapsulates the entire repository map structure, providing a comprehensive overview of files, symbols, and their relationships.+- BuildRepoMapOptions · interface · L51-L58 — Specifies options for building the repository map, allowing customization of directory and hub limits.+- dirKey · function · L70-L73 — Generates a directory key based on the specified depth, facilitating the grouping of files in the repository map.+- computeInDegree · function · L78-L85 — Calculates the in-degree of nodes in the graph, determining the number of incoming edges for each target, which is crucial for identifying hubs.+- topHubs · function · L90-L96 — Identifies the top hubs based on in-degree, ensuring that only significant nodes are included in the repository map.+- sortedLanguages · function · L98-L105 — Sorts and deduplicates the programming languages used in the repository, enhancing the metadata of the repository map.+- buildRepoMap · function · L112-L180 — Constructs the repository map from a given graph, organizing files and symbols into a structured format for easy access.+- depthFor · function · L137-L137 — Determines the depth for a given path, influencing how files are grouped in the repository map based on the split segment.+- basenameOf · function · L184-L187 — Extracts the base name from a file path, simplifying the representation of file names in the output.+- formatDirHub · function · L189-L191 — Formats a hub's information for display, providing a user-friendly representation of its attributes.+- formatDirLine · function · L193-L198 — Formats a directory entry for display, summarizing its contents and associated hubs in a readable format.+- formatHotspot · function · L200-L202 — Formats a hotspot's information for display, detailing its attributes in a clear manner.+- formatRepoMap · function · L210-L223 — Renders the repository map as a human-readable string, summarizing its contents and structure for easy understanding.diff --git a/graft/src/graph/relations.md b/graft/src/graph/relations.mdindex 34b7442f..4f77066c 100644--- a/graft/src/graph/relations.md+++ b/graft/src/graph/relations.md@@ -1,3 +1,5 @@-# src/graph/relations.ts+# src/graph/relations.ts · [[graph-extraction-and-loading]] [[graph-representation]]++Defines a set of dependency relations for graph traversal, ensuring accurate representation of connections between symbols._No extracted symbols in this file._diff --git a/graft/src/graph/resolve.md b/graft/src/graph/resolve.mdindex 876406c8..f5ed1e0f 100644--- a/graft/src/graph/resolve.md+++ b/graft/src/graph/resolve.md@@ -1,13 +1,13 @@-# src/graph/resolve.ts+# src/graph/resolve.ts · [[graph-extraction-and-loading]]-This file resolves raw edge intents into concrete edges by matching names against a node index, ensuring accurate relationships between nodes.+This module resolves various types of edges between nodes in a codebase, ensuring accurate connections based on defined relationships and confidence levels.-- GoModule · interface · L39-L42 — interface GoModule-- ResolveOptions · interface · L44-L49 — interface ResolveOptions-- resolveEdges · function · L51-L140 — This function processes raw edges and establishes relationships between nodes based on their types and specified relations.-- add · function · L97-L102 — This function adds a new edge to the output if it hasn't been seen before, preventing duplicate edges in the result.+- GoModule · interface · L39-L42 — Defines the structure for a Go module, enabling the mapping of Go import paths to their corresponding directories in the repository.+- ResolveOptions · interface · L44-L49 — Specifies options for resolving edges, including the Go modules present in the repository for accurate import path mapping.+- resolveEdges · function · L51-L140 — Processes nodes and raw edges to create a list of resolved edges, ensuring accurate relationships based on various resolution strategies.+- add · function · L97-L102 — Adds a new edge to the output if it hasn't been seen before, preventing duplicates in the resolved edges list.- push · function · L142-L146 — This function adds a value to an array in a map, creating the array if it doesn't exist, facilitating grouped storage of nodes.- resolveName · function · L152-L164 — This function resolves a symbol name to its corresponding node ID, prioritizing local matches and handling ambiguities appropriately.-- resolveTypedMember · function · L180-L213 — function resolveTypedMember( recvType: string, name: string, file: string, ownerMethod: Map<string, NodeV1[]>, classParents: Map<string, string[]>, ): { id: string; confidence: EdgeV1["confidence"] } | "ambiguous" | null+- resolveTypedMember · function · L180-L213 — Resolves a typed member call against a method index, traversing the inheritance chain to find the appropriate method or returning ambiguity if necessary.- resolveImport · function · L219-L231 — This function resolves a module specifier to a file node ID if it points within the repository, ensuring correct imports.-- resolveGoImport · function · L243-L258 — function resolveGoImport(spec: string, modules: GoModule[], filesByDir: Map<string, string[]>): string+- resolveGoImport · function · L243-L258 — Maps a Go import package path to an in-repo file node, handling module paths and ensuring correct resolution within the repository structure.diff --git a/graft/src/graph/traverse-cli.md b/graft/src/graph/traverse-cli.mdindex ba10b935..4cff1d70 100644--- a/graft/src/graph/traverse-cli.md+++ b/graft/src/graph/traverse-cli.md@@ -1,14 +1,16 @@-# src/graph/traverse-cli.ts+# src/graph/traverse-cli.ts · [[graph-traversal-and-analysis]]-- TraverseKind · type · L17-L17 — type TraverseKind = "callers" | "callees" | "impact";-- TraverseCliOptions · interface · L19-L26 — interface TraverseCliOptions-- edgesFor · function · L31-L35 — function edgesFor(kind: TraverseKind, graph: GraphV1, node: NodeV1, depth: number): EdgeHit[]-- headerOf · function · L41-L43 — function headerOf(n: NodeV1): string-- hitLine · function · L45-L50 — function hitLine(kind: TraverseKind, hit: EdgeHit): string-- looseNoteFor · function · L54-L58 — function looseNoteFor(kind: TraverseKind, name: string): string-- SymbolJson · interface · L60-L66 — interface SymbolJson-- MatchJson · interface · L68-L72 — interface MatchJson-- HitJson · interface · L74-L82 — interface HitJson-- symbolJson · function · L84-L86 — function symbolJson(n: NodeV1): SymbolJson-- hitJson · function · L88-L97 — function hitJson(hit: EdgeHit): HitJson-- runTraverseCommand · function · L105-L155 — function runTraverseCommand(kind: TraverseKind, query: string, dir: string, opts: TraverseCliOptions): void+This file implements CLI commands for traversing a graph to find callers, callees, and impact of symbols, ensuring a consistent user experience across different commands.++- TraverseKind · type · L17-L17 — Defines the types of traversal operations available for graph navigation, ensuring type safety in CLI commands.+- TraverseCliOptions · interface · L19-L26 — Specifies options for the CLI traversal commands, allowing customization of input, output format, and traversal depth.+- edgesFor · function · L31-L35 — Determines the edges to traverse in the graph based on the specified kind, facilitating the retrieval of relevant connections for a node.+- headerOf · function · L41-L43 — Generates a formatted header string for a node, providing essential information for display in CLI output.+- hitLine · function · L45-L50 — Formats a single hit line for display, showing the relationship and details of a node in the context of the traversal.+- looseNoteFor · function · L54-L58 — Creates a user-friendly message when no edges are found for a symbol, guiding users on next steps.+- SymbolJson · interface · L60-L66 — Defines the structure for symbol metadata in JSON format, ensuring consistent representation of symbols in output.+- MatchJson · interface · L68-L72 — Defines the structure for matching results in JSON format, encapsulating symbol information and associated hits.+- HitJson · interface · L74-L82 — Defines the structure for hit details in JSON format, providing information about the relationship and depth of hits.+- symbolJson · function · L84-L86 — Converts a node into a standardized JSON format, facilitating consistent output for symbol information.+- hitJson · function · L88-L97 — Transforms an EdgeHit into a JSON format, ensuring structured output for hits in the traversal results.+- runTraverseCommand · function · L105-L155 — Executes the traversal command based on user input, handling graph resolution and output formatting, while managing errors effectively.diff --git a/graft/src/graph/traverse.md b/graft/src/graph/traverse.mdindex b54671d1..e4bab1a5 100644--- a/graft/src/graph/traverse.md+++ b/graft/src/graph/traverse.md@@ -1,13 +1,15 @@-# src/graph/traverse.ts+# src/graph/traverse.ts · [[graph-traversal-and-analysis]]-- SymbolMatch · interface · L19-L21 — interface SymbolMatch-- ResolveSymbolOptions · interface · L23-L26 — interface ResolveSymbolOptions-- resolveSymbol · function · L47-L72 — function resolveSymbol(graph: GraphV1, query: string, opts: ResolveSymbolOptions = {}): NodeV1[]-- symbolMatches · function · L74-L83 — function symbolMatches(nodes: NodeV1[], lowerQuery: string): NodeV1[]-- EdgeHit · interface · L88-L93 — interface EdgeHit-- callersOf · function · L96-L104 — function callersOf(graph: GraphV1, symbol: NodeV1): EdgeHit[]-- calleesOf · function · L107-L115 — function calleesOf(graph: GraphV1, symbol: NodeV1): EdgeHit[]-- impactOf · function · L123-L125 — function impactOf(graph: GraphV1, symbol: NodeV1, maxDepth = 2): EdgeHit[]-- impactOfMany · function · L141-L172 — function impactOfMany(graph: GraphV1, seeds: NodeV1[], maxDepth = 2): EdgeHit[]-- symbolsInFile · function · L176-L178 — function symbolsInFile(graph: GraphV1, fileNode: NodeV1): NodeV1[]-- impactOfFile · function · L189-L191 — function impactOfFile(graph: GraphV1, fileNode: NodeV1, maxDepth = 2): EdgeHit[]+Centralizes the logic for resolving symbol queries in a graph, enabling consistent identification of nodes based on various naming conventions and paths.++- SymbolMatch · interface · L19-L21 — Represents a resolved match for a symbol search in the graph, allowing for future disambiguation of metadata.+- ResolveSymbolOptions · interface · L23-L26 — Defines options for narrowing down symbol resolution candidates based on path substring filtering.+- resolveSymbol · function · L47-L72 — Resolves a query string to all matching nodes in the graph, handling various naming conventions and fallbacks.+- symbolMatches · function · L74-L83 — Filters nodes in the graph to find matches based on a case-insensitive query, considering both name and id suffixes.+- EdgeHit · interface · L88-L93 — Represents a traversed edge in the graph, capturing the relationship and depth of the connection to a node.+- callersOf · function · L96-L104 — Finds all edges leading to a specified symbol, indicating which nodes directly call it.+- calleesOf · function · L107-L115 — Identifies all edges originating from a specified symbol, showing which nodes it directly calls.+- impactOf · function · L123-L125 — Performs a breadth-first search to determine the impact of changes to a symbol, identifying affected nodes up to a specified depth.+- impactOfMany · function · L141-L172 — Generalizes the impact analysis to multiple seed nodes, aggregating the results of their incoming edges.+- symbolsInFile · function · L176-L178 — Retrieves all symbols defined in a specific file, filtering out file nodes.+- impactOfFile · function · L189-L191 — Aggregates the impact analysis for a file node and its defined symbols, ensuring all dependents are considered.diff --git a/graft/src/graph/types.md b/graft/src/graph/types.mdindex ce7db024..0a6c900a 100644--- a/graft/src/graph/types.md+++ b/graft/src/graph/types.md@@ -1,12 +1,12 @@-# src/graph/types.ts+# src/graph/types.ts · [[graph-extraction-and-loading]] [[graph-representation]]-Defines the schema for a code graph, outlining nodes and edges for code structure representation.+Defines the structure and relationships of a code graph schema, facilitating the representation of code elements and their interactions.-- Kind · type · L15-L23 — Enumerates the types of symbols that can exist in the code graph, facilitating type identification.+- Kind · type · L15-L23 — Enumerates the various types of nodes in the code graph, ensuring consistent categorization of code elements across different languages.- Confidence · type · L26-L26 — Specifies the confidence levels for the truth of edges in the graph, aiding in the assessment of relationships.- SummaryState · type · L29-L29 — Indicates whether the meaning-layer has been computed for a node, managing the state of node summaries.- Crux · interface · L33-L36 — Holds the LLM-chosen business-logic excerpt for a node, providing a source of truth for code interpretation.-- NodeV1 · interface · L38-L63 — Represents a node in the graph with its identity, location, and meaning, essential for graph construction.+- NodeV1 · interface · L38-L63 — Describes the properties of a node in the code graph, encapsulating its identity, location, and meaning for effective graph representation.- Relation · type · L65-L71 — Defines the types of relationships between nodes in the graph, clarifying how symbols interact.- EdgeV1 · interface · L73-L78 — Describes the edges connecting nodes in the graph, detailing the source, target, and relationship type.- GraphV1 · interface · L80-L89 — Encapsulates the entire graph structure, including metadata and collections of nodes and edges.diff --git a/graft/src/graph/write.md b/graft/src/graph/write.mdindex 7d2a94b9..6d7e7a85 100644--- a/graft/src/graph/write.md+++ b/graft/src/graph/write.md@@ -1,9 +1,9 @@-# src/graph/write.ts · [[graph-management]]+# src/graph/write.ts-This file contains functions for managing the serialization and deserialization of a wiring graph used in a context directory.+This file manages the serialization and deserialization of a wiring graph, ensuring efficient storage and retrieval of graph data for further processing.- wiringPath · function · L20-L22 — Generates the absolute path for the wiring graph file in a specified output directory.- readGraph · function · L28-L34 — Reads and parses an existing wiring graph from a file, returning null if the file is absent or unparseable.-- writeGraph · function · L36-L46 — Writes a sorted representation of the wiring graph to a specified output directory, ensuring the directory structure exists.-- stripBodyText · function · L57-L61 — function stripBodyText(node: NodeV1): NodeV1+- writeGraph · function · L36-L46 — Writes a serialized and sorted representation of the graph to a JSON file, optimizing for size by stripping unnecessary data.+- stripBodyText · function · L57-L61 — Removes the body_text property from a node to reduce the size of the serialized graph, avoiding duplication of data already stored elsewhere.- edgeOrder · function · L63-L69 — Defines the sorting order for edges in the wiring graph based on source, relation, and target.diff --git a/graft/src/hosts/codex-hooks.md b/graft/src/hosts/codex-hooks.mdindex ce092165..2ec4cfe4 100644--- a/graft/src/hosts/codex-hooks.md+++ b/graft/src/hosts/codex-hooks.md@@ -1,7 +1,9 @@-# src/hosts/codex-hooks.ts+# src/hosts/codex-hooks.ts · [[host-management-and-configuration]]-- HookWrite · interface · L11-L15 — interface HookWrite-- dirExists · function · L17-L19 — function dirExists(p: string): boolean-- writeOwned · function · L21-L31 — function writeOwned(id: string, path: string, content: string, mode?: number): HookWrite-- isGraftEntry · function · L33-L35 — function isGraftEntry(entry: unknown): boolean-- installCodexHooks · function · L37-L74 — function installCodexHooks(home: string): HookWrite[]+Facilitates the installation and management of user-level hooks for CLI agents, ensuring that hooks are correctly written and updated in the hooks.json configuration file after file edits.++- HookWrite · interface · L11-L15 — Defines the structure for hook write operations, encapsulating the ID, path, and action taken during the write process.+- dirExists · function · L17-L19 — Checks if a given directory path exists, returning a boolean value to indicate its existence.+- writeOwned · function · L21-L31 — Handles the creation or updating of a file with specific content and permissions, returning the action taken.+- isGraftEntry · function · L33-L35 — Determines if a given entry is a graft entry by checking for a specific string in its JSON representation.+- installCodexHooks · function · L37-L74 — Installs codex hooks by writing a shim and updating the hooks configuration based on the provided home directory.diff --git a/graft/src/hosts/init.md b/graft/src/hosts/init.mdindex b0b4cb04..648d392d 100644--- a/graft/src/hosts/init.md+++ b/graft/src/hosts/init.md@@ -1,6 +1,8 @@-# src/hosts/init.ts+# src/hosts/init.ts · [[host-management-and-configuration]]-- HostsInitResult · interface · L14-L20 — interface HostsInitResult-- probeFor · function · L22-L27 — function probeFor(home: string, repo: string): DetectProbe-- writeOwned · function · L29-L35 — function writeOwned(path: string, content: string): string-- runHostsInit · function · L37-L72 — function runHostsInit( repo: string, opts: { agents?: string[]; all?: boolean; home?: string; mcp?: boolean; hooks?: boolean } = {}, ): HostsInitResult+Initializes host configurations by writing instruction files based on selected hosts, ensuring that the correct files are created or updated as needed.++- HostsInitResult · interface · L14-L20 — Defines the structure of the result returned by the host initialization process, capturing written, skipped, and unknown hosts along with MCP and hooks data.+- probeFor · function · L22-L27 — Creates a probe object to check for the existence of directories in a specified repository, facilitating host detection.+- writeOwned · function · L29-L35 — Writes content to a specified path, creating or replacing the file as necessary, and returns the action taken.+- runHostsInit · function · L37-L72 — Initializes hosts by selecting them based on provided options and writing their instruction files, while also handling MCP configurations and hooks.diff --git a/graft/src/hosts/instructions.md b/graft/src/hosts/instructions.mdindex 1ae906f8..b0555561 100644--- a/graft/src/hosts/instructions.md+++ b/graft/src/hosts/instructions.md@@ -1,6 +1,8 @@-# src/hosts/instructions.ts+# src/hosts/instructions.ts · [[host-management-and-configuration]]-- instructionBody · function · L6-L42 — function instructionBody(): string-- cursorRule · function · L44-L51 — function cursorRule(): string-- kiroSteering · function · L53-L59 — function kiroSteering(): string-- windsurfRule · function · L61-L64 — function windsurfRule(): string+This file provides Graft instructions for navigating and utilizing the context graph effectively.++- instructionBody · function · L6-L42 — Generates the main instructional content for using the Graft context graph.+- cursorRule · function · L44-L51 — Defines a rule to always apply the Graft context graph before exploring source code.+- kiroSteering · function · L53-L59 — Specifies a rule for always including the Graft context graph in the workflow.+- windsurfRule · function · L61-L64 — Provides a rule that incorporates the Graft context graph into its logic.diff --git a/graft/src/hosts/mcp-config.md b/graft/src/hosts/mcp-config.mdindex d9d4ba88..bd0bbef5 100644--- a/graft/src/hosts/mcp-config.md+++ b/graft/src/hosts/mcp-config.md@@ -1,7 +1,9 @@-# src/hosts/mcp-config.ts+# src/hosts/mcp-config.ts · [[host-management-and-configuration]]-- McpWrite · interface · L10-L14 — interface McpWrite-- dirExists · function · L19-L21 — function dirExists(p: string): boolean-- mergeJsonKey · function · L23-L43 — function mergeJsonKey(id: string, path: string, topKey: string, entry: object): McpWrite-- upsertCodexToml · function · L45-L54 — function upsertCodexToml(id: string, path: string): McpWrite-- registerMcpConfigs · function · L56-L87 — function registerMcpConfigs( repo: string, ids: string[], opts: { home?: string } = {}, ): McpWrite[]+Facilitates the registration and configuration of multiple MCP servers in specified host configurations, ensuring proper JSON and TOML formatting.++- McpWrite · interface · L10-L14 — Defines the structure for writing MCP configuration results, indicating the operation performed on the configuration file.+- dirExists · function · L19-L21 — Checks if a given directory path exists, returning a boolean value.+- mergeJsonKey · function · L23-L43 — Merges a JSON entry into a specified key of a JSON file, creating or updating the file as necessary.+- upsertCodexToml · function · L45-L54 — Inserts or updates a section in a TOML configuration file for the codex, ensuring the section exists.+- registerMcpConfigs · function · L56-L87 — Registers MCP configurations for multiple IDs, handling different file types and structures based on the ID.diff --git a/graft/src/hosts/registry.md b/graft/src/hosts/registry.mdindex d9faef88..34a81327 100644--- a/graft/src/hosts/registry.md+++ b/graft/src/hosts/registry.md@@ -1,6 +1,6 @@-# src/hosts/registry.ts+# src/hosts/registry.ts · [[host-management-and-configuration]]-- DetectProbe · interface · L12-L16 — interface DetectProbe-- HostTarget · interface · L18-L26 — interface HostTarget-- hostIds · function · L82-L84 — function hostIds(): string[]-- detectHosts · function · L86-L88 — function detectHosts(probe: DetectProbe): HostTarget[]+- DetectProbe · interface · L12-L16 — Defines the structure for probing the existence of directories related to AI coding hosts.+- HostTarget · interface · L18-L26 — Represents a target host with its identification, type, and detection logic for AI coding environments.+- hostIds · function · L82-L84 — Retrieves a list of identifiers for all defined host targets.+- detectHosts · function · L86-L88 — Filters and returns host targets that are detected based on the provided probing information.diff --git a/graft/src/hosts/sections.md b/graft/src/hosts/sections.mdindex a2780caa..e0b64414 100644--- a/graft/src/hosts/sections.md+++ b/graft/src/hosts/sections.md@@ -1,8 +1,10 @@-# src/hosts/sections.ts+# src/hosts/sections.ts · [[host-management-and-configuration]]-- UpsertAction · type · L11-L11 — type UpsertAction = 'created' | 'appended' | 'replaced' | 'unchanged';-- LineEnding · type · L13-L13 — type LineEnding = '\n' | '\r\n';-- fencedBlock · function · L15-L21 — function fencedBlock(body: string, eol: LineEnding = '\n'): string-- detectEol · function · L24-L26 — function detectEol(text: string): LineEnding-- markerLineIndex · function · L29-L34 — function markerLineIndex(lines: string[], marker: string, from = 0): number-- upsertSection · function · L36-L67 — function upsertSection(filePath: string, body: string): { action: UpsertAction }+This file provides functionality to manage sections of text within files, specifically for inserting and updating content between defined markers.++- UpsertAction · type · L11-L11 — Defines the possible outcomes of an upsert operation on a section, indicating whether it was created, appended, replaced, or unchanged.+- LineEnding · type · L13-L13 — Specifies the types of line endings that can be used in the text, ensuring compatibility with different operating systems.+- fencedBlock · function · L15-L21 — Creates a formatted block of text enclosed by specific markers, ensuring proper line endings and normalization of input.+- detectEol · function · L24-L26 — Determines the dominant line ending used in a given text, facilitating consistent handling of line breaks.+- markerLineIndex · function · L29-L34 — Finds the index of a specified marker in an array of lines, helping to locate the start and end of sections within the text.+- upsertSection · function · L36-L67 — Handles the logic for inserting or updating a section of text in a file, managing file creation, content comparison, and writing operations.diff --git a/graft/src/index.md b/graft/src/index.mdindex 51280b70..192cccab 100644--- a/graft/src/index.md+++ b/graft/src/index.md@@ -1,5 +1,5 @@# src/index.ts-This file serves as the public API for the Graft library, facilitating the management and synchronization of linked markdown files in a repository.+This module serves as the public API for the Graft library, facilitating the building and checking of a graph of linked markdown files._No extracted symbols in this file._diff --git a/graft/src/mcp/server.md b/graft/src/mcp/server.mdindex 2015359e..df627206 100644--- a/graft/src/mcp/server.md+++ b/graft/src/mcp/server.md@@ -1,6 +1,8 @@# src/mcp/server.ts-- send · function · L8-L10 — function send(msg: object): void-- reply · function · L12-L14 — function reply(id: unknown, result: object): void-- replyError · function · L16-L18 — function replyError(id: unknown, code: number, message: string): void-- startMcpServer · function · L20-L66 — function startMcpServer(root: string, dirOverride?: string): void+Defines a minimal JSON-RPC 2.0 server for handling protocol messages and tool calls.++- send · function · L8-L10 — Sends a JSON-RPC message to the standard output stream.+- reply · function · L12-L14 — Constructs and sends a successful JSON-RPC response message.+- replyError · function · L16-L18 — Constructs and sends a JSON-RPC error response message.+- startMcpServer · function · L20-L66 — Initializes the server to listen for incoming JSON-RPC messages and handle them appropriately.diff --git a/graft/src/mcp/tools.md b/graft/src/mcp/tools.mdindex 0348feb6..00236aaf 100644--- a/graft/src/mcp/tools.md+++ b/graft/src/mcp/tools.md@@ -1,6 +1,6 @@# src/mcp/tools.ts-- ToolDef · interface · L18-L22 — interface ToolDef-- unknownSymbolText · function · L29-L31 — function unknownSymbolText(query: string): string-- renderMatches · function · L137-L147 — function renderMatches(kind: TraverseKind, matches: NodeV1[], hitsFor: (n: NodeV1) => EdgeHit[]): string-- callTool · function · L149-L242 — function callTool( root: string, name: string, args: Record<string, unknown>, dirOverride?: string, ): { text: string; isError: boolean }+- ToolDef · interface · L18-L22 — Defines the structure for tool definitions used in the MCP tools, ensuring consistent input schema and metadata for each tool.+- unknownSymbolText · function · L29-L31 — Generates an error message for an unknown symbol query, guiding users to check their input or build the graph.+- renderMatches · function · L137-L147 — Formats and renders the results of graph traversal matches, providing a structured output for users to understand symbol relationships.+- callTool · function · L149-L242 — Handles the invocation of various tools based on user input, managing errors and returning formatted results for different graph operations.diff --git a/graft/src/search/grep-cli.md b/graft/src/search/grep-cli.mdindex 3918bb2e..3f649c39 100644--- a/graft/src/search/grep-cli.md+++ b/graft/src/search/grep-cli.md@@ -1,10 +1,12 @@-# src/search/grep-cli.ts+# src/search/grep-cli.ts · [[graph-traversal-and-analysis]]-- GrepCliOptions · interface · L15-L22 — interface GrepCliOptions-- groupHeader · function · L24-L27 — function groupHeader(g: GrepGroup): string-- formatGroup · function · L29-L33 — function formatGroup(g: GrepGroup): string-- formatGrepHeader · function · L36-L39 — function formatGrepHeader(result: GrepResult): string-- truncationNote · function · L42-L49 — function truncationNote(result: GrepResult): string | null-- formatGrepResult · function · L53-L59 — function formatGrepResult(result: GrepResult): string-- zeroHitNote · function · L69-L74 — function zeroHitNote(result: GrepResult): string-- runGrepCommand · function · L83-L112 — function runGrepCommand(pattern: string, dir: string, opts: GrepCliOptions): void+This file provides the command-line interface for the grep functionality, formatting results for user-friendly output.++- GrepCliOptions · interface · L15-L22 — Defines options for the grep command-line interface, allowing customization of search behavior.+- groupHeader · function · L24-L27 — Generates a header string for a group of grep results, summarizing the group's metadata.+- formatGroup · function · L29-L33 — Formats a group of grep results into a human-readable string, including hit lines.+- formatGrepHeader · function · L36-L39 — Creates a header for the grep results, summarizing the total hits and files searched.+- truncationNote · function · L42-L49 — Generates a note about any truncation in the grep results, indicating unreadable files or additional hits beyond the cap.+- formatGrepResult · function · L53-L59 — Compiles the full human-readable report of grep results, including headers and formatted groups.+- zeroHitNote · function · L69-L74 — Provides a detailed message for zero-hit results, explaining the absence of matches and potential issues.+- runGrepCommand · function · L83-L112 — Executes the grep command, handling graph resolution, pattern searching, and output formatting.diff --git a/graft/src/search/grep.md b/graft/src/search/grep.mdindex 5ddc5d49..b750f445 100644--- a/graft/src/search/grep.md+++ b/graft/src/search/grep.md@@ -1,15 +1,17 @@-# src/search/grep.ts+# src/search/grep.ts · [[graph-traversal-and-analysis]]-- GrepHit · interface · L17-L21 — interface GrepHit-- GrepSymbolRef · interface · L23-L31 — interface GrepSymbolRef-- GrepGroup · interface · L33-L42 — interface GrepGroup-- GrepResult · interface · L44-L58 — interface GrepResult-- GrepOptions · interface · L60-L69 — interface GrepOptions-- escapeRegExp · function · L75-L77 — function escapeRegExp(s: string): string-- spanBounds · function · L79-L83 — function spanBounds(span: string): { start: number; end: number } | null-- SymbolSpan · interface · L85-L89 — interface SymbolSpan-- symbolsOf · function · L93-L102 — function symbolsOf(graph: GraphV1, path: string): SymbolSpan[]-- enclosingSymbol · function · L108-L115 — function enclosingSymbol(symbols: SymbolSpan[], line: number): NodeV1 | null-- computeInDegree · function · L119-L126 — function computeInDegree(graph: GraphV1): Map<string, number>-- toSymbolRef · function · L128-L131 — function toSymbolRef(n: NodeV1): GrepSymbolRef-- grepGraph · function · L133-L195 — function grepGraph(graph: GraphV1, repoRoot: string, pattern: string, opts: GrepOptions = {}): GrepResult+This file implements a regex search over indexed files in a graph, grouping results by their enclosing symbols and ranking them by their importance based on incoming edges.++- GrepHit · interface · L17-L21 — Represents a single hit found during the grep search, including the line number and trimmed text of the line.+- GrepSymbolRef · interface · L23-L31 — Defines a reference to a symbol in the graph, including its qualified name and span, to facilitate grouping grep hits by their enclosing symbols.+- GrepGroup · interface · L33-L42 — Groups grep hits by their enclosing symbol, providing context such as the symbol's in-degree and the path of the file.+- GrepResult · interface · L44-L58 — Encapsulates the results of a grep operation, including the pattern searched, total hits, and grouped results.+- GrepOptions · interface · L60-L69 — Holds options for configuring the grep search, such as case sensitivity and maximum hits to collect.+- escapeRegExp · function · L75-L77 — Escapes special characters in a string to create a safe regex pattern for searching.+- spanBounds · function · L79-L83 — Extracts the start and end line numbers from a span string, returning null if the format is invalid.+- SymbolSpan · interface · L85-L89 — Represents a span of a symbol in the graph, including its start and end lines, to assist in finding enclosing symbols.+- symbolsOf · function · L93-L102 — Retrieves and sorts the symbols of a given file in the graph, based on their span start lines.+- enclosingSymbol · function · L108-L115 — Finds the innermost symbol that contains a specified line number, returning the corresponding node from the graph.+- computeInDegree · function · L119-L126 — Calculates the incoming edge count for each symbol in the graph, which is used to rank grep hits by importance.+- toSymbolRef · function · L128-L131 — Converts a node in the graph to a GrepSymbolRef, providing a structured representation of the symbol.+- grepGraph · function · L133-L195 — Performs the grep search on the graph, collecting and returning results based on the specified pattern and options.diff --git a/graft/src/viz/assemble.md b/graft/src/viz/assemble.mdindex a0f286bc..0a272a8c 100644--- a/graft/src/viz/assemble.md+++ b/graft/src/viz/assemble.md@@ -1,4 +1,4 @@-# src/viz/assemble.ts+# src/viz/assemble.ts · [[visualization-and-serving]]Assembles a comprehensive graph document from markdown files in a context directory, ensuring that only valid nodes and edges are included.diff --git a/graft/src/viz/serve.md b/graft/src/viz/serve.mdindex 1ad6c676..3326bc86 100644--- a/graft/src/viz/serve.md+++ b/graft/src/viz/serve.md@@ -1,4 +1,4 @@-# src/viz/serve.ts+# src/viz/serve.ts · [[visualization-and-serving]]This file implements a local server for serving a viewer and handling API requests related to context and code graphs.diff --git a/graft/task-management.md b/graft/task-management.mddeleted file mode 100644index 65ed8e3a..00000000--- a/graft/task-management.md+++ /dev/null@@ -1,38 +0,0 @@-----name: Task Management-slug: task-management-type: system-sources:- - path: bench/tasks.ts- hash: d21168797f40d193a914aca0c438409d29d300441bc0a6a518c93869240b3b69-sources_digest: 2940a72050e0bee89a860d904a1ebf289505f797cd93c71d86c2e776227e3fb4-links:- - to: benchmarking-framework- relation: part_of- description: Provides the necessary tasks for the benchmarking framework.-generator:- version: 1-covers:- - symbol: repoPath- kind: function- at: 'bench/tasks.ts:L30-L33'- - symbol: Task- kind: interface- at: 'bench/tasks.ts:L35-L45'- - symbol: Corpus- kind: interface- at: 'bench/tasks.ts:L47-L53'-----<!-- context:generated:start -->-## Summary--This component defines and manages the benchmark tasks and corpora, ensuring that each task has verifiable answers based on actual source code. It emphasizes fair assessments of code comprehension.--## Related--- part of [[benchmarking-framework]] — Provides the necessary tasks for the benchmarking framework.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/tasks.md b/graft/tasks.mdnew file mode 100644index 00000000..5766c5e3--- /dev/null+++ b/graft/tasks.md@@ -0,0 +1,38 @@+---+name: Tasks+slug: tasks+type: system+sources:+ - path: bench/tasks.ts+ hash: efb90e69f52adcb08bfe45fb5a983fc676df68befdc455513e2581a24f46807e+sources_digest: bf5418660cc917f7af4f93b7ed71cfc4c37f06a27af5b61047b54ba572a3a2b0+links:+ - to: agent+ relation: depends_on+ description: The agent executes the tasks defined in this component.+generator:+ version: 1+covers:+ - symbol: repoPath+ kind: function+ at: 'bench/tasks.ts:L30-L33'+ - symbol: Task+ kind: interface+ at: 'bench/tasks.ts:L35-L45'+ - symbol: Corpus+ kind: interface+ at: 'bench/tasks.ts:L47-L53'+---+<!-- context:generated:start -->+## Summary++The tasks component defines a set of benchmark questions and expected answers, ensuring that each task is verifiable based on actual source code. It facilitates the evaluation of code understanding and comprehension.++## Related++- depends on [[agent]] — The agent executes the tasks defined in this component.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/test-helpers.md b/graft/test-helpers.mdnew file mode 100644index 00000000..114c5075--- /dev/null+++ b/graft/test-helpers.md@@ -0,0 +1,49 @@+---+name: Test Helpers+slug: test-helpers+type: system+sources:+ - path: test/helpers.ts+ hash: e45af1d38d7c6d4abc804fc74e9ae4c3373cf78769c17b16b185c3ee0e2c3228+sources_digest: ddc97a2b9b5b7ea60c6a55b3c250ddc0dffa3b335c4b43ddc9152dc900f56744+links:+ - to: graph-traversal-and-impact-analysis+ relation: validates+ description: >-+ The test helpers are used to validate the functionality of graph traversal+ and impact analysis.+generator:+ version: 1+covers:+ - symbol: PassthroughSummarizer+ kind: class+ at: 'test/helpers.ts:L9-L13'+ - symbol: summarize+ kind: method+ at: 'test/helpers.ts:L10-L12'+ - symbol: BracketSynthesizer+ kind: class+ at: 'test/helpers.ts:L21-L50'+ - symbol: synthesize+ kind: method+ at: 'test/helpers.ts:L22-L49'+ - symbol: ensure+ kind: function+ at: 'test/helpers.ts:L24-L31'+ - symbol: fakeProviders+ kind: function+ at: 'test/helpers.ts:L52-L54'+---+<!-- context:generated:start -->+## Summary++This component provides deterministic test doubles and utilities for creating mock data and structures, facilitating isolated testing of various graph functionalities without external dependencies.++## Related++- validates [[graph-traversal-and-impact-analysis]] — The test helpers are used to validate the functionality of graph traversal and impact analysis.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/test/ask-index.test.md b/graft/test/ask-index.test.mdindex 900b09be..90f04642 100644--- a/graft/test/ask-index.test.md+++ b/graft/test/ask-index.test.md@@ -1,5 +1,7 @@-# test/ask-index.test.ts+# test/ask-index.test.ts · [[testing-and-validation]]-- makeFixture · function · L26-L50 — function makeFixture(): string-- reinjectBodyText · function · L69-L85 — function reinjectBodyText(dir: string, outDir: string): void-- sortPairs · function · L106-L106 — sortPairs = (p: [string, number][])+This file contains tests to ensure the integrity and correctness of the `ask` sidecar functionality, verifying that it accurately reproduces live tokenization results and handles various edge cases without failure.++- makeFixture · function · L26-L50 — Creates a temporary multi-file fixture with overlapping vocabulary to facilitate meaningful tests on tokenization and scoring.+- reinjectBodyText · function · L69-L85 — Reconstructs the body text for nodes in the wiring.json to ensure accurate tokenization results during tests.+- sortPairs · function · L106-L106 — Sorts an array of pairs by the first element, ensuring consistent ordering for comparison in tests.diff --git a/graft/test/ask.test.md b/graft/test/ask.test.mdindex 652d8d1c..411ba858 100644--- a/graft/test/ask.test.md+++ b/graft/test/ask.test.md@@ -1,7 +1,7 @@-# test/ask.test.ts+# test/ask.test.ts · [[testing-and-validation]]-This file contains tests for the `graft ask` functionality, ensuring that the source option correctly inlines code from disk when requested.+Contains tests for the `ask` functionality, validating its behavior with various options and scenarios.- makeFixture · function · L16-L25 — Creates a temporary directory with a sample TypeScript file for testing purposes.-- stampCrux · function · L43-L49 — function stampCrux(dir: string, code: string): void-- qualifiedFixture · function · L189-L207 — function qualifiedFixture(): string+- stampCrux · function · L43-L49 — Updates the wiring.json file to include a crux for the specified node, allowing for inlined source retrieval.+- qualifiedFixture · function · L189-L207 — Sets up a temporary directory with a cache implementation to test structural resolution of function calls.diff --git a/graft/test/claude-format.test.md b/graft/test/claude-format.test.mdindex 22d20a7e..bcb22cfd 100644--- a/graft/test/claude-format.test.md+++ b/graft/test/claude-format.test.md@@ -1,5 +1,7 @@-# test/claude-format.test.ts+# test/claude-format.test.ts · [[testing-and-validation]]-- strip · function · L6-L6 — strip = (s: string)-- gateAsk · function · L97-L104 — gateAsk = (over: Record<string, unknown> = {})-- freshSession · function · L105-L105 — freshSession = ()+This test suite verifies the functionality of various formatting and retrieval functions related to the status line and enriched segments in a codebase, ensuring correct rendering based on different states and inputs.++- strip · function · L6-L6 — Removes ANSI escape codes from a string to ensure clean output for assertions.+- gateAsk · function · L97-L104 — Creates a structured query object for testing relevant retrieval functionality with customizable parameters.+- freshSession · function · L105-L105 — Initializes a fresh session state for testing the relevant retrieval process.diff --git a/graft/test/claude-hooks.test.md b/graft/test/claude-hooks.test.mdindex fb521e37..53f59fd2 100644--- a/graft/test/claude-hooks.test.md+++ b/graft/test/claude-hooks.test.md@@ -1,4 +1,6 @@-# test/claude-hooks.test.ts+# test/claude-hooks.test.ts · [[testing-and-validation]]-- runWithStdin · function · L38-L41 — async function runWithStdin(text: string, fn: () => Promise<void>): Promise<void>-- fakeBuild · function · L84-L87 — fakeBuild = (dir: string)+This file contains tests for the functionality of the graft hooks in the Claude project, ensuring that edits are detected and state is managed correctly.++- runWithStdin · function · L38-L41 — This function sets up the environment to run a given asynchronous function with specified input from stdin, managing the environment variable for the duration of the execution.+- fakeBuild · function · L84-L87 — This function simulates a build process by writing a mock wiring.json file to the specified directory, allowing tests to verify behavior based on the build output.diff --git a/graft/test/claude-init.test.md b/graft/test/claude-init.test.mdindex 75b25936..478fb9b6 100644--- a/graft/test/claude-init.test.md+++ b/graft/test/claude-init.test.md@@ -1,5 +1,7 @@-# test/claude-init.test.ts+# test/claude-init.test.ts · [[testing-and-validation]]-- fresh · function · L10-L10 — function fresh(): string-- runPostinstall · function · L12-L17 — function runPostinstall(env: Record<string, string>): string-- col · function · L116-L116 — col = (text: string, marker: string)+This file contains tests for the initialization logic of the graft system, ensuring that settings and skills are correctly scaffolded and managed during the initialization process.++- fresh · function · L10-L10 — Creates a fresh temporary directory for testing purposes, ensuring isolation between test runs.+- runPostinstall · function · L12-L17 — Executes the post-installation script, which sets up necessary configurations after the main initialization process.+- col · function · L116-L116 — Determines the column alignment for specific text markers in the output, ensuring consistent formatting in the display.diff --git a/graft/test/claude-paths.test.md b/graft/test/claude-paths.test.mdindex e696267e..f2ed5485 100644--- a/graft/test/claude-paths.test.md+++ b/graft/test/claude-paths.test.md@@ -1,3 +1,5 @@-# test/claude-paths.test.ts+# test/claude-paths.test.ts · [[testing-and-validation]]++This test file verifies that the paths for the graft CLI and Claude script are correctly resolved relative to the module structure, ensuring they are independent of the current working directory._No extracted symbols in this file._diff --git a/graft/test/claude-settings-merge.test.md b/graft/test/claude-settings-merge.test.mdindex 84b2869b..cf2714f3 100644--- a/graft/test/claude-settings-merge.test.md+++ b/graft/test/claude-settings-merge.test.md@@ -1,3 +1,5 @@-# test/claude-settings-merge.test.ts+# test/claude-settings-merge.test.ts · [[testing-and-validation]]++This test suite verifies the behavior of merging Graft settings, ensuring that defaults are applied correctly, existing configurations are preserved, and no duplicates are introduced during re-initialization._No extracted symbols in this file._diff --git a/graft/test/claude-shim-template.test.md b/graft/test/claude-shim-template.test.mdindex 2d4ecc1b..314aaecf 100644--- a/graft/test/claude-shim-template.test.md+++ b/graft/test/claude-shim-template.test.md@@ -1,3 +1,5 @@-# test/claude-shim-template.test.ts+# test/claude-shim-template.test.ts · [[testing-and-validation]]++This test file validates the behavior of the statusline and hooks shims to ensure they correctly parse and resolve module paths in a Node.js environment._No extracted symbols in this file._diff --git a/graft/test/claude-skill-template.test.md b/graft/test/claude-skill-template.test.mdindex 3faf4073..9139dc1f 100644--- a/graft/test/claude-skill-template.test.md+++ b/graft/test/claude-skill-template.test.md@@ -1,3 +1,5 @@-# test/claude-skill-template.test.ts+# test/claude-skill-template.test.ts · [[testing-and-validation]]++This test ensures that the generated skill template adheres to the expected format and contains the necessary components for functionality._No extracted symbols in this file._diff --git a/graft/test/claude-state.test.md b/graft/test/claude-state.test.mdindex ddce7768..4f75b8c4 100644--- a/graft/test/claude-state.test.md+++ b/graft/test/claude-state.test.md@@ -1,3 +1,5 @@-# test/claude-state.test.ts+# test/claude-state.test.ts · [[testing-and-validation]]-- fresh · function · L11-L11 — function fresh(): string+This test suite verifies the functionality of state management, including stats and session handling, as well as lock acquisition and release mechanisms.++- fresh · function · L11-L11 — Generates a unique temporary directory for testing purposes to ensure isolation between test cases.diff --git a/graft/test/claude-stats.test.md b/graft/test/claude-stats.test.mdindex d89e0a0a..40bef4f8 100644--- a/graft/test/claude-stats.test.md+++ b/graft/test/claude-stats.test.md@@ -1,3 +1,5 @@-# test/claude-stats.test.ts+# test/claude-stats.test.ts · [[testing-and-validation]]++This test file verifies the functionality of the computeStats function to ensure it accurately calculates node and edge counts, as well as the count of ready nodes from a given wiring structure._No extracted symbols in this file._diff --git a/graft/test/claude-statusline.test.md b/graft/test/claude-statusline.test.mdindex 4d39e3d6..1108701d 100644--- a/graft/test/claude-statusline.test.md+++ b/graft/test/claude-statusline.test.md@@ -1,4 +1,6 @@-# test/claude-statusline.test.ts+# test/claude-statusline.test.ts · [[testing-and-validation]]-- repo · function · L9-L9 — function repo(): string-- writeWiring · function · L10-L13 — function writeWiring(dir: string, obj: unknown): void+This file contains tests for the resolveStats function, ensuring it correctly retrieves and prioritizes cached statistics or falls back to graph data as needed.++- repo · function · L9-L9 — Creates a temporary directory for testing purposes, ensuring a clean environment for each test run.+- writeWiring · function · L10-L13 — Writes a wiring.json file to a specified directory, setting up the necessary structure for graph data in tests.diff --git a/graft/test/cli-meta.test.md b/graft/test/cli-meta.test.mdindex 4574c46d..714fc572 100644--- a/graft/test/cli-meta.test.md+++ b/graft/test/cli-meta.test.md@@ -1,3 +1,5 @@-# test/cli-meta.test.ts+# test/cli-meta.test.ts · [[testing-and-validation]]++This file contains tests for formatting version and upgrade reports, resolving package.json paths, reading the current version, and detecting if a script is running via npx, ensuring correct behavior of the CLI meta functionalities._No extracted symbols in this file._diff --git a/graft/test/context.test.md b/graft/test/context.test.mdindex 50d54362..ee9bfb9a 100644--- a/graft/test/context.test.md+++ b/graft/test/context.test.md@@ -1,7 +1,7 @@-# test/context.test.ts+# test/context.test.ts · [[testing-and-validation]]-This file contains end-to-end tests for the markdown-graph pipeline to ensure proper functionality and integrity of the context building and checking processes.+This file contains end-to-end tests for the markdown-graph pipeline, ensuring that the initialization and checking processes work correctly with various scenarios.-- runCli · function · L19-L30 — function runCli(args: string[]): { stdout: string; stderr: string; status: number }+- runCli · function · L19-L30 — This function executes a command-line interface (CLI) command and captures its output, allowing tests to verify the behavior of the CLI under different conditions.- makeFixture · function · L32-L43 — This function creates a temporary directory with mock service files for testing the context building process.- buildOpts · function · L45-L47 — This function generates options for building the context, including a fake model and providers.diff --git a/graft/test/covers.test.md b/graft/test/covers.test.mdindex d3407b99..7ec95bb4 100644--- a/graft/test/covers.test.md+++ b/graft/test/covers.test.md@@ -1,4 +1,4 @@-# test/covers.test.ts+# test/covers.test.ts · [[testing-and-validation]]This test suite verifies that the wiring build correctly populates the 'covers' field in concept nodes and maintains stability across builds.diff --git a/graft/test/graph-bindings.test.md b/graft/test/graph-bindings.test.mdindex 5a710bfb..ea7e6d9b 100644--- a/graft/test/graph-bindings.test.md+++ b/graft/test/graph-bindings.test.md@@ -1,3 +1,5 @@-# test/graph-bindings.test.ts+# test/graph-bindings.test.ts · [[testing-and-validation]]-- callEdges · function · L5-L7 — function callEdges(src: string, lang: "python" | "typescript" | "go", file = `x.${lang === "python" ? "py" : lang === "go" ? "go" : "ts"}`)+This file contains tests that validate the behavior of type bindings in different programming languages' code snippets.++- callEdges · function · L5-L7 — This function extracts call edges from source code based on the specified programming language, filtering for 'calls' relations.diff --git a/graft/test/graph-go.test.md b/graft/test/graph-go.test.mdindex e576c389..8fb8cba8 100644--- a/graft/test/graph-go.test.md+++ b/graft/test/graph-go.test.md@@ -1,4 +1,6 @@-# test/graph-go.test.ts+# test/graph-go.test.ts · [[testing-and-validation]]-- makeFixture · function · L53-L60 — function makeFixture(): string-- nodeById · function · L62-L64 — function nodeById(graph: GraphV1, id: string): NodeV1 | undefined+This file contains tests for verifying the extraction of Go code structures and their relationships in a code graph.++- makeFixture · function · L53-L60 — Creates a temporary Go module directory with necessary files for testing graph extraction.+- nodeById · function · L62-L64 — Retrieves a node from the graph by its unique identifier, facilitating graph traversal and assertions in tests.diff --git a/graft/test/graph-load.test.md b/graft/test/graph-load.test.mdindex db0617df..64fd1a27 100644--- a/graft/test/graph-load.test.md+++ b/graft/test/graph-load.test.md@@ -1,5 +1,7 @@-# test/graph-load.test.ts+# test/graph-load.test.ts · [[testing-and-validation]]-- node · function · L23-L38 — function node(id: string): NodeV1-- fixtureDir · function · L40-L42 — function fixtureDir(): string-- bump · function · L46-L50 — function bump(path: string): void+This file contains tests for caching mechanisms in the graph loading functionality to improve performance by avoiding unnecessary re-parsing of files.++- node · function · L23-L38 — Creates a node representation for the graph with specified properties, facilitating the construction of graph structures in tests.+- fixtureDir · function · L40-L42 — Generates a temporary directory for use in tests, ensuring isolation and preventing interference between test cases.+- bump · function · L46-L50 — Updates the modification time of a file to ensure that caching mechanisms recognize changes, preventing stale data usage.diff --git a/graft/test/graph-map.test.md b/graft/test/graph-map.test.mdindex a97c074f..1953513e 100644--- a/graft/test/graph-map.test.md+++ b/graft/test/graph-map.test.md@@ -1,7 +1,9 @@-# test/graph-map.test.ts+# test/graph-map.test.ts · [[testing-and-validation]]-- fileNode · function · L16-L31 — function fileNode(path: string): NodeV1-- symNode · function · L33-L49 — function symNode(path: string, name: string, opts: { kind?: Kind; span?: string } = {}): NodeV1-- edge · function · L51-L53 — function edge(source: string, target: string, relation: Relation = "calls"): EdgeV1-- graphOf · function · L55-L61 — function graphOf(nodes: NodeV1[], edges: EdgeV1[]): GraphV1-- bigFixture · function · L240-L259 — function bigFixture(): GraphV1+This file contains tests for the `buildRepoMap` and `formatRepoMap` functions, ensuring they correctly process and format repository data.++- fileNode · function · L16-L31 — Creates a file node representation for the graph, encapsulating file metadata for processing.+- symNode · function · L33-L49 — Generates a symbol node representation for the graph, allowing for the inclusion of function or variable symbols with associated metadata.+- edge · function · L51-L53 — Defines a connection between two nodes in the graph, representing relationships such as function calls.+- graphOf · function · L55-L61 — Constructs a graph structure from nodes and edges, serving as the foundational data for repository mapping.+- bigFixture · function · L240-L259 — Creates a large fixture graph for testing, simulating a repository with multiple directories and symbols.diff --git a/graft/test/graph-resolve-typed.test.md b/graft/test/graph-resolve-typed.test.mdindex 0b6c7a37..bfb0f460 100644--- a/graft/test/graph-resolve-typed.test.md+++ b/graft/test/graph-resolve-typed.test.md@@ -1,3 +1,5 @@-# test/graph-resolve-typed.test.ts+# test/graph-resolve-typed.test.ts · [[testing-and-validation]]-- n · function · L6-L10 — function n(id: string, kind: NodeV1["kind"]): NodeV1+This test file verifies the resolution of method calls and inheritance in a graph of nodes representing code elements, ensuring correct behavior in various scenarios.++- n · function · L6-L10 — Creates a NodeV1 object representing a code element with its associated metadata, facilitating the construction of a node graph for resolution tests.diff --git a/graft/test/graph-traverse-cli.test.md b/graft/test/graph-traverse-cli.test.mdindex 944e74ed..3bce7e79 100644--- a/graft/test/graph-traverse-cli.test.md+++ b/graft/test/graph-traverse-cli.test.md@@ -1,4 +1,6 @@-# test/graph-traverse-cli.test.ts+# test/graph-traverse-cli.test.ts · [[testing-and-validation]]-- builtRepo · function · L16-L27 — function builtRepo(): string-- runCli · function · L29-L40 — function runCli(args: string[]): { stdout: string; stderr: string; status: number }+This file contains tests for the CLI commands related to graph traversal, ensuring correct functionality and output for various scenarios.++- builtRepo · function · L16-L27 — Sets up a temporary repository with a sample math module for testing CLI commands.+- runCli · function · L29-L40 — Executes the CLI command with given arguments and captures the output and status code.diff --git a/graft/test/graph-traverse.test.md b/graft/test/graph-traverse.test.mdindex 65cd9ee1..076dc66c 100644--- a/graft/test/graph-traverse.test.md+++ b/graft/test/graph-traverse.test.md@@ -1,8 +1,10 @@-# test/graph-traverse.test.ts+# test/graph-traverse.test.ts · [[graph-traversal-and-impact-analysis]]-- nodeStub · function · L15-L30 — function nodeStub(partial: Partial<NodeV1> & { id: string }): NodeV1-- edge · function · L32-L34 — function edge(source: string, target: string, relation: Relation = "calls"): EdgeV1-- graphOf · function · L36-L42 — function graphOf(nodes: NodeV1[], edges: EdgeV1[]): GraphV1-- baseGraph · function · L57-L66 — function baseGraph(): GraphV1-- diamondGraph · function · L167-L179 — function diamondGraph(): GraphV1-- fileAndSymbolGraph · function · L221-L231 — function fileAndSymbolGraph()+Contains tests for graph traversal functionalities, ensuring correct symbol resolution and edge walking behavior.++- nodeStub · function · L15-L30 — Creates a stub node for testing purposes, encapsulating essential properties of a NodeV1 object.+- edge · function · L32-L34 — Constructs an edge between two nodes in the graph, defining their relationship type.+- graphOf · function · L36-L42 — Generates a graph structure from an array of nodes and edges, encapsulating metadata about the graph.+- baseGraph · function · L57-L66 — Creates a base graph fixture used for testing symbol resolution and edge walking.+- diamondGraph · function · L167-L179 — Constructs a diamond-shaped graph for testing the impact of nodes based on incoming edges.+- fileAndSymbolGraph · function · L221-L231 — Creates a graph that includes both file and symbol nodes to test their interactions in dependency resolution.diff --git a/graft/test/graph-write.test.md b/graft/test/graph-write.test.mdindex c830669a..1f7cb960 100644--- a/graft/test/graph-write.test.md+++ b/graft/test/graph-write.test.md@@ -1,3 +1,5 @@-# test/graph-write.test.ts+# test/graph-write.test.ts · [[graph-data-integrity]] [[graph-serialization]]-- makeNode · function · L19-L35 — function makeNode(overrides: Partial<NodeV1> = {}): NodeV1+This file contains tests to ensure that the `writeGraph` function correctly handles the serialization of graph nodes, specifically that the `body_text` field is omitted when unnecessary, while preserving other fields and the integrity of the original node object.++- makeNode · function · L19-L35 — Creates a node object with default properties, allowing for optional overrides, to facilitate testing of graph serialization and deserialization.diff --git a/graft/test/graphrank.test.md b/graft/test/graphrank.test.mdindex 3d08a6ba..ed2ba0a6 100644--- a/graft/test/graphrank.test.md+++ b/graft/test/graphrank.test.md@@ -1,7 +1,9 @@-# test/graphrank.test.ts+# test/graphrank.test.ts · [[graph-ranking]]-- node · function · L23-L38 — function node(id: string): NodeV1-- edge · function · L39-L41 — function edge(source: string, target: string, relation: Relation = "calls"): EdgeV1-- graphOf · function · L42-L48 — function graphOf(nodes: string[], edges: EdgeV1[]): GraphV1-- makeCollisionFixture · function · L128-L138 — function makeCollisionFixture(): string-- rank · function · L140-L141 — rank = (dir: string, gr: boolean)+This file contains unit and integration tests for the personalizedPageRank function, ensuring it correctly ranks nodes based on their connectivity in a graph.++- node · function · L23-L38 — Creates a node representation for the graph with specified properties.+- edge · function · L39-L41 — Defines an edge between two nodes in the graph, establishing a relationship.+- graphOf · function · L42-L48 — Constructs a graph object from given nodes and edges, encapsulating their relationships.+- makeCollisionFixture · function · L128-L138 — Sets up a temporary file structure to simulate a collision scenario for testing graph ranking.+- rank · function · L140-L141 — Executes the ask function with specified parameters to retrieve ranked results based on graph connectivity.diff --git a/graft/test/helpers.md b/graft/test/helpers.mdindex fdf10ba5..a991e067 100644--- a/graft/test/helpers.md+++ b/graft/test/helpers.md@@ -1,4 +1,4 @@-# test/helpers.ts+# test/helpers.ts · [[deterministic-testing]] [[test-helpers]]This file provides test doubles for offline, deterministic testing of components without external dependencies.diff --git a/graft/test/hosts-codex-hooks.test.md b/graft/test/hosts-codex-hooks.test.mdindex 250e1429..2924f492 100644--- a/graft/test/hosts-codex-hooks.test.md+++ b/graft/test/hosts-codex-hooks.test.md@@ -1,3 +1,5 @@-# test/hosts-codex-hooks.test.ts+# test/hosts-codex-hooks.test.ts · [[host-configuration-management]]-- fresh · function · L8-L8 — function fresh(): string+This test suite verifies the behavior of the installCodexHooks function, ensuring it correctly manages hook installations and configurations in various scenarios.++- fresh · function · L8-L8 — Generates a unique temporary directory for testing purposes.diff --git a/graft/test/hosts-init.test.md b/graft/test/hosts-init.test.mdindex f4ee7d5f..c7eef444 100644--- a/graft/test/hosts-init.test.md+++ b/graft/test/hosts-init.test.md@@ -1,3 +1,5 @@-# test/hosts-init.test.ts+# test/hosts-init.test.ts · [[host-configuration-management]] [[idempotent-host-initialization]]-- fresh · function · L9-L9 — function fresh(): string+This test suite verifies the behavior of the runHostsInit function in various scenarios, ensuring it correctly handles host initialization, agent detection, and configuration management.++- fresh · function · L9-L9 — Generates a unique temporary directory for testing purposes to avoid conflicts between test runs.diff --git a/graft/test/hosts-instructions.test.md b/graft/test/hosts-instructions.test.mdindex ce524364..43219d4d 100644--- a/graft/test/hosts-instructions.test.md+++ b/graft/test/hosts-instructions.test.md@@ -1,3 +1,5 @@# test/hosts-instructions.test.ts+This test suite verifies the structure and content of various instruction bodies to ensure they meet specified formatting and inclusion criteria.+_No extracted symbols in this file._diff --git a/graft/test/hosts-mcp-config.test.md b/graft/test/hosts-mcp-config.test.mdindex 03774c69..ed8ed191 100644--- a/graft/test/hosts-mcp-config.test.md+++ b/graft/test/hosts-mcp-config.test.md@@ -1,3 +1,5 @@-# test/hosts-mcp-config.test.ts+# test/hosts-mcp-config.test.ts · [[host-configuration-management]]-- fresh · function · L8-L8 — function fresh(): string+This test suite verifies the behavior of the registerMcpConfigs function in handling various configurations and edge cases.++- fresh · function · L8-L8 — Generates a fresh temporary directory for testing purposes.diff --git a/graft/test/hosts-registry.test.md b/graft/test/hosts-registry.test.mdindex facd6ad2..6f1dadee 100644--- a/graft/test/hosts-registry.test.md+++ b/graft/test/hosts-registry.test.md@@ -1,4 +1,6 @@-# test/hosts-registry.test.ts+# test/hosts-registry.test.ts · [[host-configuration-management]]-- probeFor · function · L9-L14 — function probeFor(home: string, repo: string): DetectProbe-- fresh · function · L15-L15 — function fresh(): string+This file contains tests for the hosts registry functionality, ensuring that the correct hosts are detected based on the presence of specific directories.++- probeFor · function · L9-L14 — Creates a probe object that checks for the existence of a directory, facilitating host detection based on the file system state.+- fresh · function · L15-L15 — Generates a temporary directory for testing purposes, ensuring a clean environment for each test case.diff --git a/graft/test/hosts-sections.test.md b/graft/test/hosts-sections.test.mdindex dd13905c..a98b0386 100644--- a/graft/test/hosts-sections.test.md+++ b/graft/test/hosts-sections.test.md@@ -1,3 +1,5 @@-# test/hosts-sections.test.ts+# test/hosts-sections.test.ts · [[host-configuration-management]]-- fresh · function · L8-L8 — function fresh(): string+This file contains tests for the upsertSection function, ensuring it correctly creates, appends, replaces, and reports on sections in markdown files.++- fresh · function · L8-L8 — Generates a fresh temporary directory for testing purposes.diff --git a/graft/test/llm-adapters.test.md b/graft/test/llm-adapters.test.mdnew file mode 100644index 00000000..c33bbc62--- /dev/null+++ b/graft/test/llm-adapters.test.md@@ -0,0 +1,8 @@+# test/llm-adapters.test.ts++This file contains tests for network-free adapters that simulate interactions with OpenAI and Anthropic SDKs, ensuring correct request handling and response formatting.++- fakeOpenAI · function · L17-L23 — Creates a mock OpenAI client for testing purposes, allowing assertions on the parameters sent to it.+- openAiResp · function · L25-L31 — Generates a mock response structure for OpenAI API calls, facilitating the testing of response handling.+- fakeAnthropic · function · L119-L125 — Creates a mock Anthropic client for testing purposes, enabling verification of the parameters it receives.+- anthropicResp · function · L127-L134 — Generates a mock response structure for Anthropic API calls, aiding in the testing of response processing.diff --git a/graft/test/llm-ops.test.md b/graft/test/llm-ops.test.mdnew file mode 100644index 00000000..eb668d86--- /dev/null+++ b/graft/test/llm-ops.test.md@@ -0,0 +1,7 @@+# test/llm-ops.test.ts++Tests the behavior of three engine operations (summarize, synthesize, crux) using a fake transport to ensure they build the correct requests and handle responses appropriately.++- FakeChatModel · class · L15-L29 — Simulates a chat model to test the behavior of chat operations without network dependency.+- constructor · method · L18-L18 — Initializes the fake chat model with a predefined reply for testing purposes.+- create · method · L19-L28 — Processes a chat request and returns a simulated chat response based on predefined data.diff --git a/graft/test/mcp-server.test.md b/graft/test/mcp-server.test.mdindex 07b2e1b6..bd79793c 100644--- a/graft/test/mcp-server.test.md+++ b/graft/test/mcp-server.test.md@@ -1,3 +1,5 @@-# test/mcp-server.test.ts+# test/mcp-server.test.ts · [[mcp-server-and-tools]]-- rpc · function · L9-L28 — async function rpc(messages: object[], dir: string, expected: number): Promise<any[]>+This file contains tests for the RPC functionality of the MCP server, ensuring that various methods return expected results and handle errors correctly.++- rpc · function · L9-L28 — The rpc function facilitates communication with the MCP server by sending messages and collecting responses, handling asynchronous interactions effectively.diff --git a/graft/test/mcp-tools.test.md b/graft/test/mcp-tools.test.mdindex 03db2807..86459f31 100644--- a/graft/test/mcp-tools.test.md+++ b/graft/test/mcp-tools.test.md@@ -1,7 +1,9 @@-# test/mcp-tools.test.ts+# test/mcp-tools.test.ts · [[mcp-server-and-tools]]-- builtRepo · function · L9-L16 — function builtRepo(): string-- chainRepo · function · L22-L33 — function chainRepo(): string-- customDirRepo · function · L37-L45 — function customDirRepo(): { repo: string; graphDir: string }-- fileScopeRepo · function · L50-L60 — function fileScopeRepo(): string-- multiDirRepo · function · L65-L73 — function multiDirRepo(): string+This test suite validates the functionality of various tools in the MCP codebase, ensuring they operate correctly on built repositories and handle errors appropriately.++- builtRepo · function · L9-L16 — Creates a temporary repository structure for testing the tools with a basic math implementation.+- chainRepo · function · L22-L33 — Sets up a repository with a three-deep function call structure to test depth-related functionality in tools.+- customDirRepo · function · L37-L45 — Establishes a repository in a custom directory to validate the handling of non-default graph locations.+- fileScopeRepo · function · L50-L60 — Creates a repository to test the interaction between file imports and function calls across files.+- multiDirRepo · function · L65-L73 — Generates a repository with multiple directories to test the handling of directory limits in tool operations.diff --git a/graft/test/search-grep.test.md b/graft/test/search-grep.test.mdindex baca671a..e5296731 100644--- a/graft/test/search-grep.test.md+++ b/graft/test/search-grep.test.md@@ -1,6 +1,8 @@# test/search-grep.test.ts-- fileNode · function · L24-L39 — function fileNode(path: string, lines: number): NodeV1-- graphOf · function · L41-L43 — function graphOf(nodes: NodeV1[], edges: GraphV1['edges'] = []): GraphV1-- needleRepo · function · L50-L85 — function needleRepo(): string-- loadBuiltGraph · function · L87-L91 — function loadBuiltGraph(repo: string): GraphV1+Contains core tests for the `graft grep` functionality, ensuring accurate symbol attribution and search results in a parsed graph.++- fileNode · function · L24-L39 — Creates a file node representation for a given path and number of lines, facilitating graph construction.+- graphOf · function · L41-L43 — Constructs a graph representation from nodes and edges, encapsulating metadata about the graph structure.+- needleRepo · function · L50-L85 — Sets up a temporary repository with TypeScript files to test the grep functionality, simulating real-world usage scenarios.+- loadBuiltGraph · function · L87-L91 — Loads a built graph from a specified repository, ensuring the graph is correctly constructed for testing.diff --git a/graft/testing-and-validation.md b/graft/testing-and-validation.mdnew file mode 100644index 00000000..ef5754d0--- /dev/null+++ b/graft/testing-and-validation.md@@ -0,0 +1,182 @@+---+name: Testing and Validation+slug: testing-and-validation+type: system+sources:+ - path: test/ask-index.test.ts+ hash: c9cd7c011ebd661f35488c59dcd34801079f2786d56e96833f4da7c45dfa37d7+ - path: test/ask.test.ts+ hash: 3445f8b156ba6b2f0e9123e9fc45781da352ec6d5baeb985ee144fe5aecaafb3+ - path: test/claude-format.test.ts+ hash: cfaa9f489dd95956e3c9917ebe29a46992dfdbab943b5971eecbd98f18b3268c+ - path: test/claude-hooks.test.ts+ hash: 875c10776da455499b58ebe861b3cb0ae797f751e4e838812cd0b4f3c13587c2+ - path: test/claude-init.test.ts+ hash: b582cd79b2a1e4952ff83ac1b2e85f742756443c2896e08d96a75dc76e2971a5+ - path: test/claude-paths.test.ts+ hash: 205740f8110e72e4cb24652c09f763fad5e056dc77776bcfa95a1953731ed2c8+ - path: test/claude-settings-merge.test.ts+ hash: 4c8b800f02d1b72050082bdbcdcda0878e5d9760563d2e1ca4a31cb06ffaaabb+ - path: test/claude-shim-template.test.ts+ hash: f787f99fef2dc6a5ed366419fc470e8e4f825e0bc590cf3550d39e01995e7619+ - path: test/claude-skill-template.test.ts+ hash: 49f60183a51f9c307a33b5d4da3a7ded2f55509407e6a85778f3512b27db7cde+ - path: test/claude-state.test.ts+ hash: 78e6a81af7642ea788072457ea181bc626c7a8a898cfebb882ab42fed7e9dd2e+ - path: test/claude-stats.test.ts+ hash: f625d026d152a65017699e37e27534043dc0af0f43ba2d3ea778bac8ddab82c3+ - path: test/claude-statusline.test.ts+ hash: 07128b5b195af3a37c1e170a35c18378e36160d1a6f8e17be362bac315811cac+ - path: test/cli-meta.test.ts+ hash: e7a05bf838e876a317276f94a26d92b0b1526e1ea7eabda4e68b804bdb0334e5+ - path: test/context.test.ts+ hash: 126861c136d48ed6a148e50226c96ec2935c52cf83ef56fbd43392e0d271db1f+ - path: test/covers.test.ts+ hash: f5a75f405be1a01ad43fc806588858df3a8988fee62ad4ec024440d3f5e0fc0c+ - path: test/graph-bindings.test.ts+ hash: b6892b1b6982547fc67d5b0e7812a536e47018ab3e38e4eda35a0f12f24ab8db+ - path: test/graph-go.test.ts+ hash: bf11085a7edb03c00d52dca090af9c1ca4eb3cb34bb88904bbdd478171d3483d+ - path: test/graph-load.test.ts+ hash: 8df11988d049b5243d8c7a0d55045163b714965897448797b40c8ef458b0896b+ - path: test/graph-map.test.ts+ hash: 97c06030735d5dbb15270b73a594e1de8fb3ffba5c6551b6303a5357b8da31be+ - path: test/graph-resolve-typed.test.ts+ hash: 0c3760525cc61ee97de448fa26b4a5b9a3bb07c03b4acfbdf3608541b189cf81+ - path: test/graph-traverse-cli.test.ts+ hash: d79347b0640178631235552105c0518029305ead4990726470d3adf5a1b52f09+sources_digest: ec26f442eeea6bac55ed94939624004883ed25f71e6271fccd772f42743774f0+links:+ - to: graph-extraction-and-loading+ relation: validates+ description: It validates the extraction and loading functionalities.+ - to: graph-traversal-and-analysis+ relation: validates+ description: It ensures that traversal and analysis functions perform correctly.+ - to: host-management-and-configuration+ relation: validates+ description: It tests the configuration and initialization processes for hosts.+generator:+ version: 1+covers:+ - symbol: makeFixture+ kind: function+ at: 'test/ask-index.test.ts:L26-L50'+ - symbol: reinjectBodyText+ kind: function+ at: 'test/ask-index.test.ts:L69-L85'+ - symbol: sortPairs+ kind: function+ at: 'test/ask-index.test.ts:L106-L106'+ - symbol: makeFixture+ kind: function+ at: 'test/ask.test.ts:L16-L25'+ - symbol: stampCrux+ kind: function+ at: 'test/ask.test.ts:L43-L49'+ - symbol: qualifiedFixture+ kind: function+ at: 'test/ask.test.ts:L189-L207'+ - symbol: strip+ kind: function+ at: 'test/claude-format.test.ts:L6-L6'+ - symbol: gateAsk+ kind: function+ at: 'test/claude-format.test.ts:L97-L104'+ - symbol: freshSession+ kind: function+ at: 'test/claude-format.test.ts:L105-L105'+ - symbol: runWithStdin+ kind: function+ at: 'test/claude-hooks.test.ts:L38-L41'+ - symbol: fakeBuild+ kind: function+ at: 'test/claude-hooks.test.ts:L84-L87'+ - symbol: fresh+ kind: function+ at: 'test/claude-init.test.ts:L10-L10'+ - symbol: runPostinstall+ kind: function+ at: 'test/claude-init.test.ts:L12-L17'+ - symbol: col+ kind: function+ at: 'test/claude-init.test.ts:L116-L116'+ - symbol: fresh+ kind: function+ at: 'test/claude-state.test.ts:L11-L11'+ - symbol: repo+ kind: function+ at: 'test/claude-statusline.test.ts:L9-L9'+ - symbol: writeWiring+ kind: function+ at: 'test/claude-statusline.test.ts:L10-L13'+ - symbol: runCli+ kind: function+ at: 'test/context.test.ts:L19-L30'+ - symbol: makeFixture+ kind: function+ at: 'test/context.test.ts:L32-L43'+ - symbol: buildOpts+ kind: function+ at: 'test/context.test.ts:L45-L47'+ - symbol: makeFixture+ kind: function+ at: 'test/covers.test.ts:L16-L24'+ - symbol: callEdges+ kind: function+ at: 'test/graph-bindings.test.ts:L5-L7'+ - symbol: makeFixture+ kind: function+ at: 'test/graph-go.test.ts:L53-L60'+ - symbol: nodeById+ kind: function+ at: 'test/graph-go.test.ts:L62-L64'+ - symbol: node+ kind: function+ at: 'test/graph-load.test.ts:L23-L38'+ - symbol: fixtureDir+ kind: function+ at: 'test/graph-load.test.ts:L40-L42'+ - symbol: bump+ kind: function+ at: 'test/graph-load.test.ts:L46-L50'+ - symbol: fileNode+ kind: function+ at: 'test/graph-map.test.ts:L16-L31'+ - symbol: symNode+ kind: function+ at: 'test/graph-map.test.ts:L33-L49'+ - symbol: edge+ kind: function+ at: 'test/graph-map.test.ts:L51-L53'+ - symbol: graphOf+ kind: function+ at: 'test/graph-map.test.ts:L55-L61'+ - symbol: bigFixture+ kind: function+ at: 'test/graph-map.test.ts:L240-L259'+ - symbol: 'n'+ kind: function+ at: 'test/graph-resolve-typed.test.ts:L6-L10'+ - symbol: builtRepo+ kind: function+ at: 'test/graph-traverse-cli.test.ts:L16-L27'+ - symbol: runCli+ kind: function+ at: 'test/graph-traverse-cli.test.ts:L29-L40'+---+<!-- context:generated:start -->+## Summary++This component encompasses various test suites designed to validate the functionality and reliability of the Graft system, ensuring that all components work as intended and that changes do not introduce regressions. It includes tests for extraction, loading, traversal, and host management.++## Related++- validates [[graph-extraction-and-loading]] — It validates the extraction and loading functionalities.+- validates [[graph-traversal-and-analysis]] — It ensures that traversal and analysis functions perform correctly.+- validates [[host-management-and-configuration]] — It tests the configuration and initialization processes for hosts.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/token-a-b-testing.md b/graft/token-a-b-testing.mdnew file mode 100644index 00000000..c6569fec--- /dev/null+++ b/graft/token-a-b-testing.md@@ -0,0 +1,56 @@+---+name: Token A/B Testing+slug: token-a-b-testing+type: system+sources:+ - path: bench/token-ab.ts+ hash: b033a023d063cccc329103fbd11d4e1a6ab16c5eb027e1dd85c47a63a7df4ff1+sources_digest: 12c7bde30c776e231fe85e67e20d88c3b691c854a45b9bc463502f489874cdf7+links:+ - to: agent+ relation: uses+ description: The A/B testing harness evaluates the agent's performance.+generator:+ version: 1+covers:+ - symbol: Metrics+ kind: interface+ at: 'bench/token-ab.ts:L55-L64'+ - symbol: runSearch+ kind: function+ at: 'bench/token-ab.ts:L98-L128'+ - symbol: runRead+ kind: function+ at: 'bench/token-ab.ts:L130-L147'+ - symbol: runAgent+ kind: function+ at: 'bench/token-ab.ts:L150-L207'+ - symbol: graftPack+ kind: function+ at: 'bench/token-ab.ts:L210-L221'+ - symbol: cost+ kind: function+ at: 'bench/token-ab.ts:L223-L227'+ - symbol: row+ kind: function+ at: 'bench/token-ab.ts:L229-L231'+ - symbol: main+ kind: function+ at: 'bench/token-ab.ts:L233-L273'+ - symbol: pct+ kind: function+ at: 'bench/token-ab.ts:L253-L253'+---+<!-- context:generated:start -->+## Summary++This component implements a manual A/B testing harness to compare token usage between two evaluation arms of the agent, providing insights into the efficiency of different approaches in answering coding-related questions.++## Related++- uses [[agent]] — The A/B testing harness evaluates the agent's performance.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/user-interaction-in-visualization.md b/graft/user-interaction-in-visualization.mdnew file mode 100644index 00000000..95bcba7f--- /dev/null+++ b/graft/user-interaction-in-visualization.md@@ -0,0 +1,158 @@+---+name: User Interaction in Visualization+slug: user-interaction-in-visualization+type: concept+sources:+ - path: viewer/detail.ts+ hash: fe8df7c5561f2a8588cf4e1ecb367d19cb6b480fe4855f05e4f96137d8078884+ - path: viewer/graph.ts+ hash: 192a59b16da8327457de6723893fd9207dd9570a35cd664f96534a7b85e73e01+ - path: viewer/main.ts+ hash: ab45ce4dfe66aafbe779b71d49d6370b3fe64482307b994e857ce34d3f317325+sources_digest: 949fbcf087492dc70392ec9143ab9070d6c27e57720cbb7fa1b4324d473e7423+links:+ - to: graph-visualization+ relation: implements+ description: >-+ User interactions must be effectively managed to enhance the overall+ experience of exploring the graph.+generator:+ version: 1+covers:+ - symbol: esc+ kind: function+ at: 'viewer/detail.ts:L8-L10'+ - symbol: renderDetail+ kind: function+ at: 'viewer/detail.ts:L12-L58'+ - symbol: name+ kind: function+ at: 'viewer/detail.ts:L29-L29'+ - symbol: linkList+ kind: function+ at: 'viewer/detail.ts:L40-L50'+ - symbol: SimNode+ kind: interface+ at: 'viewer/graph.ts:L22-L30'+ - symbol: SimEdge+ kind: interface+ at: 'viewer/graph.ts:L32-L38'+ - symbol: el+ kind: function+ at: 'viewer/graph.ts:L42-L46'+ - symbol: GraphView+ kind: class+ at: 'viewer/graph.ts:L48-L334'+ - symbol: constructor+ kind: method+ at: 'viewer/graph.ts:L65-L69'+ - symbol: buildChrome+ kind: method+ at: 'viewer/graph.ts:L71-L78'+ - symbol: ensureMarkers+ kind: method+ at: 'viewer/graph.ts:L80-L91'+ - symbol: setData+ kind: method+ at: 'viewer/graph.ts:L94-L136'+ - symbol: buildElements+ kind: method+ at: 'viewer/graph.ts:L138-L164'+ - symbol: tick+ kind: method+ at: 'viewer/graph.ts:L166-L182'+ - symbol: restyle+ kind: method+ at: 'viewer/graph.ts:L185-L243'+ - symbol: nodeShown+ kind: function+ at: 'viewer/graph.ts:L195-L195'+ - symbol: select+ kind: method+ at: 'viewer/graph.ts:L245-L249'+ - symbol: focus+ kind: method+ at: 'viewer/graph.ts:L252-L261'+ - symbol: firstMatch+ kind: method+ at: 'viewer/graph.ts:L263-L266'+ - symbol: applyView+ kind: method+ at: 'viewer/graph.ts:L268-L270'+ - symbol: zoomBy+ kind: method+ at: 'viewer/graph.ts:L272-L279'+ - symbol: resetView+ kind: method+ at: 'viewer/graph.ts:L281-L284'+ - symbol: reheat+ kind: method+ at: 'viewer/graph.ts:L286-L288'+ - symbol: bindDrag+ kind: method+ at: 'viewer/graph.ts:L290-L309'+ - symbol: move+ kind: function+ at: 'viewer/graph.ts:L294-L299'+ - symbol: up+ kind: function+ at: 'viewer/graph.ts:L300-L305'+ - symbol: bindPanZoom+ kind: method+ at: 'viewer/graph.ts:L311-L333'+ - symbol: Tab+ kind: type+ at: 'viewer/main.ts:L10-L10'+ - symbol: $+ kind: function+ at: 'viewer/main.ts:L12-L12'+ - symbol: activeGraph+ kind: function+ at: 'viewer/main.ts:L23-L25'+ - symbol: graphTab+ kind: function+ at: 'viewer/main.ts:L27-L29'+ - symbol: renderChips+ kind: function+ at: 'viewer/main.ts:L32-L60'+ - symbol: rank+ kind: function+ at: 'viewer/main.ts:L43-L43'+ - symbol: glyphFor+ kind: function+ at: 'viewer/main.ts:L62-L71'+ - symbol: renderLegend+ kind: function+ at: 'viewer/main.ts:L74-L94'+ - symbol: updateShownCount+ kind: function+ at: 'viewer/main.ts:L96-L101'+ - symbol: updateCounts+ kind: function+ at: 'viewer/main.ts:L103-L112'+ - symbol: showDetail+ kind: function+ at: 'viewer/main.ts:L115-L124'+ - symbol: setTab+ kind: function+ at: 'viewer/main.ts:L129-L167'+ - symbol: showEmpty+ kind: function+ at: 'viewer/main.ts:L169-L173'+ - symbol: loadAll+ kind: function+ at: 'viewer/main.ts:L216-L223'+---+<!-- context:generated:start -->+## Summary++This concept addresses the design decisions related to user interactions within the graph visualization, including navigation, selection, and dynamic updates based on user actions.++## Related++- implements [[graph-visualization]] — User interactions must be effectively managed to enhance the overall experience of exploring the graph.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/graft/viewer/data.md b/graft/viewer/data.mdindex 44225b43..2484009f 100644--- a/graft/viewer/data.md+++ b/graft/viewer/data.md@@ -1,4 +1,4 @@-# viewer/data.ts · [[visualization-layer]]+# viewer/data.ts · [[graph-visualization]]This file defines data structures and functions for managing and visualizing graph data from a server.diff --git a/graft/viewer/detail.md b/graft/viewer/detail.mdindex 530c912f..1f5eba0b 100644--- a/graft/viewer/detail.md+++ b/graft/viewer/detail.md@@ -1,4 +1,4 @@-# viewer/detail.ts · [[visualization-layer]]+# viewer/detail.ts · [[graph-visualization]] [[user-interaction-in-visualization]]This file provides the logic to render a detailed view of a selected node in a graph, including its properties and relationships.diff --git a/graft/viewer/graph.md b/graft/viewer/graph.mdindex 7404d975..be783225 100644--- a/graft/viewer/graph.md+++ b/graft/viewer/graph.md@@ -1,4 +1,4 @@-# viewer/graph.ts · [[visualization-layer]]+# viewer/graph.ts · [[graph-visualization]] [[user-interaction-in-visualization]]This file implements a force-directed graph visualization using D3.js, allowing interactive exploration of nodes and edges.diff --git a/graft/viewer/main.md b/graft/viewer/main.mdindex f19e51c1..45c79d36 100644--- a/graft/viewer/main.md+++ b/graft/viewer/main.md@@ -1,4 +1,4 @@-# viewer/main.ts · [[visualization-layer]]+# viewer/main.ts · [[graph-visualization]] [[user-interaction-in-visualization]]This file serves as the entry point for the graft visualization viewer, managing the user interface and interactions for displaying graphs.diff --git a/graft/viewer/tree.md b/graft/viewer/tree.mdindex ea95d540..434211f4 100644--- a/graft/viewer/tree.md+++ b/graft/viewer/tree.md@@ -1,4 +1,4 @@-# viewer/tree.ts · [[visualization-layer]]+# viewer/tree.ts · [[graph-visualization]]Generates a collapsible tree view of a code graph's hierarchy, allowing users to navigate through files, classes, and methods.diff --git a/graft/visualization-and-serving.md b/graft/visualization-and-serving.mdnew file mode 100644index 00000000..2d07e8de--- /dev/null+++ b/graft/visualization-and-serving.md@@ -0,0 +1,74 @@+---+name: Visualization and Serving+slug: visualization-and-serving+type: system+sources:+ - path: src/viz/assemble.ts+ hash: 58ad5caed087bd7b929f5b625501a607e79e0476f998636bec241e0296706ece+ - path: src/viz/serve.ts+ hash: 14283762f454c01fc95cfbe9c2b41ef063fc17c4c3e5d120b5dc7f66f541fc1c+sources_digest: 88ca5c49a63bfa8625974ff180102457ba16dd9538fa82d23bbe252becd035d8+links:+ - to: graph-representation+ relation: produces+ description: It produces visual representations of the graph structure.+ - to: graph-traversal-and-analysis+ relation: uses+ description: It utilizes the graph traversal capabilities for visualization.+generator:+ version: 1+covers:+ - symbol: VizNode+ kind: interface+ at: 'src/viz/assemble.ts:L18-L24'+ - symbol: VizEdge+ kind: interface+ at: 'src/viz/assemble.ts:L26-L31'+ - symbol: VizGraph+ kind: interface+ at: 'src/viz/assemble.ts:L33-L42'+ - symbol: normalizeRelation+ kind: function+ at: 'src/viz/assemble.ts:L56-L58'+ - symbol: extractSummary+ kind: function+ at: 'src/viz/assemble.ts:L65-L76'+ - symbol: assembleContextGraph+ kind: function+ at: 'src/viz/assemble.ts:L79-L130'+ - symbol: VizServerOptions+ kind: interface+ at: 'src/viz/serve.ts:L16-L21'+ - symbol: VizServer+ kind: interface+ at: 'src/viz/serve.ts:L23-L26'+ - symbol: sendJson+ kind: function+ at: 'src/viz/serve.ts:L38-L41'+ - symbol: listen+ kind: function+ at: 'src/viz/serve.ts:L43-L55'+ - symbol: onError+ kind: function+ at: 'src/viz/serve.ts:L45-L48'+ - symbol: startVizServer+ kind: function+ at: 'src/viz/serve.ts:L57-L148'+ - symbol: close+ kind: method+ at: 'src/viz/serve.ts:L140-L146'+---+<!-- context:generated:start -->+## Summary++This component is responsible for assembling and serving the context graph for visualization purposes, providing a local server for the Graft visualization tool. It handles the generation of JSON representations of the graph and manages client notifications for changes in the context directory.++## Related++- produces [[graph-representation]] — It produces visual representations of the graph structure.+- uses [[graph-traversal-and-analysis]] — It utilizes the graph traversal capabilities for visualization.+<!-- context:generated:end -->++## Notes++_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/package-lock.json b/package-lock.jsonindex 2c370df1..49ae5a35 100644--- a/package-lock.json+++ b/package-lock.json@@ -10,6 +10,7 @@"hasInstallScript": true,"license": "MIT","dependencies": {+ "@anthropic-ai/sdk": "^0.113.0","commander": "^15.0.0","dotenv": "^17.4.2","gray-matter": "^4.0.3",@@ -34,6 +35,36 @@"node": ">=20"}},+ "node_modules/@anthropic-ai/sdk": {+ "version": "0.113.0",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.113.0.tgz",+ "integrity": "sha512-8YKIP333ypmy8QjtSP691fIqdes3HL/rSXAT4FDZX/HRnkQaNG+iOVBfEQw4vjPNpYHeoy7FSYc2o/jb8b3AnA==",+ "license": "MIT",+ "dependencies": {+ "json-schema-to-ts": "^3.1.1",+ "standardwebhooks": "^1.0.0"+ },+ "bin": {+ "anthropic-ai-sdk": "bin/cli"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/@babel/runtime": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },"node_modules/@esbuild/aix-ppc64": {"version": "0.28.1","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",@@ -476,6 +507,12 @@"node": ">=18"}},+ "node_modules/@stablelib/base64": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",+ "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",+ "license": "MIT"+ },"node_modules/@types/d3-force": {"version": "3.0.10","resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",@@ -641,6 +678,12 @@"node": ">=0.10.0"}},+ "node_modules/fast-sha256": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",+ "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",+ "license": "Unlicense"+ },"node_modules/fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -693,6 +736,19 @@"js-yaml": "bin/js-yaml.js"}},+ "node_modules/json-schema-to-ts": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",+ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "ts-algebra": "^2.0.0"+ },+ "engines": {+ "node": ">=16"+ }+ },"node_modules/kind-of": {"version": "6.0.3","resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",@@ -765,6 +821,16 @@"node": ">=4"}},+ "node_modules/standardwebhooks": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz",+ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==",+ "license": "MIT",+ "dependencies": {+ "@stablelib/base64": "^1.0.0",+ "fast-sha256": "^1.3.0"+ }+ },"node_modules/strip-bom-string": {"version": "1.0.0","resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz",@@ -868,6 +934,12 @@}}},+ "node_modules/ts-algebra": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",+ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",+ "license": "MIT"+ },"node_modules/tsx": {"version": "4.22.4","resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz",diff --git a/package.json b/package.jsonindex e4cdba95..93b559aa 100644--- a/package.json+++ b/package.json@@ -56,6 +56,7 @@"node": ">=20"},"dependencies": {+ "@anthropic-ai/sdk": "^0.113.0","commander": "^15.0.0","dotenv": "^17.4.2","gray-matter": "^4.0.3",diff --git a/src/ai/crux.ts b/src/ai/crux.tsindex 1c5a5a4d..91ba56fb 100644--- a/src/ai/crux.ts+++ b/src/ai/crux.ts@@ -14,7 +14,7 @@* sees each symbol's neighbours, which sharpens the summaries. Line numbers are* consumed once, at write time, to slice the crux text verbatim from source.*/-import OpenAI from "openai";+import type { ChatModel } from "./llm/types.js";import type { Kind } from "../graph/types.js";/** One definition we want described, located by its line span within the file. */@@ -45,17 +45,35 @@ export interface CruxSummarizer {const SYSTEM_PROMPT = `You explain code definitions for a code graph that helps engineers navigate a codebase.-You are given ONE source file with 1-based line numbers, and a list of TARGET definitions in it. For every target, return its purpose and the line range of its core logic.--Return STRICT JSON, exactly:-{ "symbols": [ { "id": string, "summary": string, "crux_start": number, "crux_end": number }, ... ] }+You are given ONE source file with 1-based line numbers, and a list of TARGET definitions in it. For every target, record its purpose and the line range of its core logic via the record_symbols tool.Rules:- Emit exactly one entry per target id given, using that id verbatim.- summary: ONE sentence — what the symbol is FOR at the business-logic level. Say what problem it solves or rule it enforces, not what its signature already says.- crux_start / crux_end: FILE line numbers (as shown), inside that symbol's own line range. Pick the SINGLE most important contiguous span — the core branch, formula, guard, or state change. Keep it TIGHT: at most ~8 lines, and NEVER the whole function. If you can't narrow it below that, the symbol has no distinct crux — use 0/0.-- Skip boilerplate, logging, and plumbing. If a symbol has no meaningful crux (trivial getter, data holder, one-line delegation, or logic spread evenly with no focal point), use "crux_start": 0 and "crux_end": 0.-- Output ONLY the JSON object. No prose, no code fences.`;+- Skip boilerplate, logging, and plumbing. If a symbol has no meaningful crux (trivial getter, data holder, one-line delegation, or logic spread evenly with no focal point), use "crux_start": 0 and "crux_end": 0.`;++const RECORD_TOOL = "record_symbols";++const SYMBOLS_SCHEMA = {+ type: "object",+ properties: {+ symbols: {+ type: "array",+ items: {+ type: "object",+ properties: {+ id: { type: "string" },+ summary: { type: "string" },+ crux_start: { type: "number" },+ crux_end: { type: "number" },+ },+ required: ["id", "summary", "crux_start", "crux_end"],+ },+ },+ },+ required: ["symbols"],+} as const;/** Cap the file text sent per request so one huge file can't blow the context. */const MAX_CODE_CHARS = 18_000;@@ -80,11 +98,9 @@ function userContent(input: FileCruxInput): string {return `FILE: ${input.path}\n\n${numberLines(input.source)}\n\nTARGETS:\n${targets}`;}-/** Best-effort parse of a model's JSON reply into a {@link NodeCrux} list. */-function parseResults(raw: string): NodeCrux[] {- const text = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");- const obj = JSON.parse(text) as { symbols?: unknown };- if (!Array.isArray(obj.symbols)) return [];+/** Normalize the tool's parsed argument object into a {@link NodeCrux} list. */+function parseResults(obj: { symbols?: unknown } | undefined): NodeCrux[] {+ if (!obj || !Array.isArray(obj.symbols)) return [];const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : 0);return obj.symbols.map((s) => s as Record<string, unknown>)@@ -97,31 +113,28 @@ function parseResults(raw: string): NodeCrux[] {}));}-/** Crux summarizer backed by OpenRouter's OpenAI-compatible chat API. */-export class OpenRouterCruxSummarizer implements CruxSummarizer {- private client: OpenAI;- private model: string;-- constructor(apiKey: string, model: string, baseUrl = "https://openrouter.ai/api/v1") {- this.client = new OpenAI({- apiKey,- baseURL: baseUrl,- defaultHeaders: { "X-Title": "Context Graph Engine" },- });- this.model = model;- }+/** Crux summarizer backed by any {@link ChatModel} via forced tool calling. */+export class ChatCruxSummarizer implements CruxSummarizer {+ constructor(private model: ChatModel) {}async describeFile(input: FileCruxInput): Promise<NodeCrux[]> {if (input.nodes.length === 0) return [];- const response = await this.client.chat.completions.create({- model: this.model,+ const res = await this.model.create({temperature: 0,- response_format: { type: "json_object" },+ maxTokens: 8192,+ tools: [+ {+ name: RECORD_TOOL,+ description: "Record each target definition's purpose and crux line range.",+ parameters: SYMBOLS_SCHEMA as unknown as Record<string, unknown>,+ },+ ],+ responseFormat: { kind: "tool", name: RECORD_TOOL },messages: [{ role: "system", content: SYSTEM_PROMPT },{ role: "user", content: userContent(input) },],});- return parseResults(response.choices[0]?.message?.content ?? "");+ return parseResults(res.toolCalls[0]?.args as { symbols?: unknown } | undefined);}}diff --git a/src/ai/llm/anthropic.ts b/src/ai/llm/anthropic.tsnew file mode 100644index 00000000..b58de7cc--- /dev/null+++ b/src/ai/llm/anthropic.ts@@ -0,0 +1,155 @@+/**+ * Native Anthropic transport. Wraps `@anthropic-ai/sdk` (the Messages API), so+ * Claude is a first-class provider rather than something tunneled through an+ * OpenAI-compatible endpoint.+ *+ * The Messages API differs from Chat Completions in ways this adapter absorbs so+ * the rest of graft never sees them:+ * - `system` is a top-level parameter, not a message.+ * - tool results ride inside a USER turn, and all results answering one+ * assistant turn must be coalesced into a single user message.+ * - `max_tokens` is required (callers get a default).+ * - `temperature` is rejected by current models, so it is never forwarded.+ * - structured output is a forced tool (there is no `response_format`).+ * - assistant turns are replayed verbatim (via `providerRaw`) so thinking-block+ * signatures survive a multi-turn loop.+ */+import Anthropic from "@anthropic-ai/sdk";+import type { ChatModel, ChatRequest, ChatResponse, Message, ToolCall, ToolSpec, Usage } from "./types.js";++const PROVIDER = "anthropic";+const JSON_TOOL = "emit_json";+const DEFAULT_MAX_TOKENS = 4096;++export interface AnthropicChatModelOptions {+ apiKey: string;+ model: string;+ baseUrl?: string;+ label?: string;+ /** Inject a pre-built client (tests pass a stub; production omits it). */+ client?: Anthropic;+}++type CacheControl = { cache_control: { type: "ephemeral" } } | Record<string, never>;+const cc = (on: boolean | undefined): CacheControl => (on ? { cache_control: { type: "ephemeral" } } : {});++export class AnthropicChatModel implements ChatModel {+ readonly label: string;+ private client: Anthropic;+ private model: string;++ constructor(opts: AnthropicChatModelOptions) {+ this.model = opts.model;+ this.label = opts.label ?? `${PROVIDER}:${opts.model}`;+ this.client = opts.client ?? new Anthropic({ apiKey: opts.apiKey, baseURL: opts.baseUrl });+ }++ async create(req: ChatRequest): Promise<ChatResponse> {+ const system: Anthropic.TextBlockParam[] = [];+ const messages: Anthropic.MessageParam[] = [];++ for (const m of req.messages) {+ if (m.role === "system") {+ system.push({ type: "text", text: m.content, ...cc(m.cacheBreakpoint) });+ } else if (m.role === "user") {+ messages.push({ role: "user", content: [{ type: "text", text: m.content, ...cc(m.cacheBreakpoint) }] });+ } else if (m.role === "tool") {+ // Tool results live in a user turn; coalesce consecutive results together.+ const block: Anthropic.ToolResultBlockParam = {+ type: "tool_result",+ tool_use_id: m.toolCallId ?? "",+ content: [{ type: "text", text: m.content }],+ ...cc(m.cacheBreakpoint),+ };+ const last = messages[messages.length - 1];+ if (last?.role === "user" && Array.isArray(last.content)) {+ (last.content as Anthropic.ContentBlockParam[]).push(block);+ } else {+ messages.push({ role: "user", content: [block] });+ }+ } else {+ messages.push(this.assistantParam(m));+ }+ }++ const tools = req.tools?.map(toAnthropicTool);+ const params: Anthropic.MessageCreateParamsNonStreaming = {+ model: this.model,+ max_tokens: req.maxTokens ?? DEFAULT_MAX_TOKENS,+ messages,+ ...(system.length ? { system } : {}),+ };+ // temperature is intentionally NOT forwarded — current models reject it.++ const fmt = req.responseFormat ?? { kind: "text" };+ if (fmt.kind === "json") {+ params.tools = [+ ...(tools ?? []),+ { name: JSON_TOOL, description: "Return the answer as a JSON object.", input_schema: { type: "object" } },+ ];+ params.tool_choice = { type: "tool", name: JSON_TOOL };+ } else if (fmt.kind === "tool") {+ params.tools = tools;+ params.tool_choice = { type: "tool", name: fmt.name };+ } else if (tools) {+ params.tools = tools;+ }++ const resp = await this.client.messages.create(params);+ return this.fromResponse(resp, fmt.kind);+ }++ /** Reconstruct an assistant turn, replaying the original blocks when we made them. */+ private assistantParam(m: Message): Anthropic.MessageParam {+ if (m.providerRaw?.provider === PROVIDER) return m.providerRaw.raw as Anthropic.MessageParam;+ const content: Anthropic.ContentBlockParam[] = [];+ if (m.content) content.push({ type: "text", text: m.content });+ for (const tc of m.toolCalls ?? []) {+ content.push({ type: "tool_use", id: tc.id, name: tc.name, input: tc.args as Record<string, unknown> });+ }+ return { role: "assistant", content };+ }++ private fromResponse(resp: Anthropic.Messages.Message, format: "text" | "json" | "tool"): ChatResponse {+ let text = "";+ let toolCalls: ToolCall[] = [];+ for (const block of resp.content) {+ if (block.type === "text") text += block.text;+ else if (block.type === "tool_use") toolCalls.push({ id: block.id, name: block.name, args: block.input });+ }++ if (format === "json") {+ const jsonCall = toolCalls.find((c) => c.name === JSON_TOOL);+ if (jsonCall) text = JSON.stringify(jsonCall.args);+ toolCalls = toolCalls.filter((c) => c.name !== JSON_TOOL);+ }++ return {+ text,+ toolCalls,+ usage: normalizeUsage(resp.usage),+ stopReason: resp.stop_reason ?? null,+ // Replay the raw content verbatim so thinking-block signatures survive.+ assistant: {+ role: "assistant",+ content: text,+ toolCalls: toolCalls.length ? toolCalls : undefined,+ providerRaw: { provider: PROVIDER, raw: { role: "assistant", content: resp.content } },+ },+ };+ }+}++function toAnthropicTool(t: ToolSpec): Anthropic.Tool {+ return { name: t.name, description: t.description, input_schema: t.parameters as Anthropic.Tool.InputSchema };+}++/** Anthropic reports uncached input in `input_tokens` and cache tokens separately. */+function normalizeUsage(u: Anthropic.Usage): Usage {+ return {+ input: u.input_tokens ?? 0,+ output: u.output_tokens ?? 0,+ cacheRead: u.cache_read_input_tokens ?? 0,+ cacheCreate: u.cache_creation_input_tokens ?? 0,+ };+}diff --git a/src/ai/llm/factory.ts b/src/ai/llm/factory.tsnew file mode 100644index 00000000..632cef6d--- /dev/null+++ b/src/ai/llm/factory.ts@@ -0,0 +1,39 @@+/**+ * One place that turns resolved config into a {@link ChatModel}. `provider` names+ * the WIRE FORMAT, not a vendor: `openai` speaks the OpenAI-compatible API (point+ * `baseUrl` at OpenRouter, Fireworks, a LiteLLM proxy, Groq, a local server, …),+ * `anthropic` speaks the native Messages API. Adding a vendor is a base URL, not+ * a code change; adding a wire format is one new adapter here.+ */+import type { ChatModel } from "./types.js";+import { OpenAIChatModel } from "./openai.js";+import { AnthropicChatModel } from "./anthropic.js";++export type ProviderKind = "openai" | "anthropic";++export interface ChatModelConfig {+ provider: ProviderKind;+ apiKey: string;+ model: string;+ baseUrl?: string;+ /** Extra default headers for OpenAI-compatible endpoints (e.g. OpenRouter `X-Title`). */+ headers?: Record<string, string>;+}++export function createChatModel(cfg: ChatModelConfig): ChatModel {+ switch (cfg.provider) {+ case "anthropic":+ return new AnthropicChatModel({ apiKey: cfg.apiKey, model: cfg.model, baseUrl: cfg.baseUrl });+ case "openai":+ return new OpenAIChatModel({+ apiKey: cfg.apiKey,+ model: cfg.model,+ baseUrl: cfg.baseUrl,+ headers: cfg.headers,+ });+ default: {+ const _exhaustive: never = cfg.provider;+ throw new Error(`unknown provider: ${String(_exhaustive)}`);+ }+ }+}diff --git a/src/ai/llm/openai.ts b/src/ai/llm/openai.tsnew file mode 100644index 00000000..08020dc2--- /dev/null+++ b/src/ai/llm/openai.ts@@ -0,0 +1,174 @@+/**+ * OpenAI-compatible transport. Wraps the `openai` SDK pointed at any+ * OpenAI-compatible endpoint (OpenAI, OpenRouter, Fireworks, a LiteLLM proxy,+ * Groq, Together, DeepSeek, a local server, …) — the user picks the endpoint+ * with `baseUrl` and authenticates with their own key.+ *+ * This adapter reproduces graft's historical wire behavior exactly: temperature+ * is forwarded, cache breakpoints become `cache_control` content parts (which+ * OpenRouter forwards to Anthropic), and cached tokens are subtracted out of the+ * input count so {@link Usage.input} is uncached-only.+ */+import OpenAI from "openai";+import type { ChatModel, ChatRequest, ChatResponse, Message, ToolCall, ToolSpec, Usage } from "./types.js";++const PROVIDER = "openai";+/** Synthetic tool used to coerce a plain JSON object out of `{ kind: "json" }`. */+const JSON_TOOL = "emit_json";++export interface OpenAIChatModelOptions {+ apiKey: string;+ model: string;+ baseUrl?: string;+ /** Stable manifest label; defaults to `openai:<model>`. */+ label?: string;+ /** Extra default headers (e.g. OpenRouter's `X-Title`). */+ headers?: Record<string, string>;+ /** Inject a pre-built client (tests pass a stub; production omits it). */+ client?: OpenAI;+}++type ChatParams = OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming;+type ChatMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;++/** A text content part, optionally carrying a cache breakpoint (OpenRouter passthrough). */+function textPart(text: string, cache: boolean | undefined) {+ return cache+ ? [{ type: "text" as const, text, cache_control: { type: "ephemeral" as const } }]+ : text;+}++function toChatMessage(m: Message): ChatMessage {+ switch (m.role) {+ case "system":+ return { role: "system", content: textPart(m.content, m.cacheBreakpoint) } as ChatMessage;+ case "user":+ return { role: "user", content: textPart(m.content, m.cacheBreakpoint) } as ChatMessage;+ case "tool":+ return {+ role: "tool",+ tool_call_id: m.toolCallId ?? "",+ content: textPart(m.content, m.cacheBreakpoint),+ } as ChatMessage;+ case "assistant": {+ if (m.providerRaw?.provider === PROVIDER) return m.providerRaw.raw as ChatMessage;+ const tool_calls = m.toolCalls?.map((tc) => ({+ id: tc.id,+ type: "function" as const,+ function: { name: tc.name, arguments: JSON.stringify(tc.args ?? {}) },+ }));+ return {+ role: "assistant",+ content: m.content || null,+ ...(tool_calls?.length ? { tool_calls } : {}),+ } as ChatMessage;+ }+ }+}++function toChatTool(t: ToolSpec): OpenAI.Chat.Completions.ChatCompletionTool {+ return { type: "function", function: { name: t.name, description: t.description, parameters: t.parameters } };+}++export class OpenAIChatModel implements ChatModel {+ readonly label: string;+ private client: OpenAI;+ private model: string;++ constructor(opts: OpenAIChatModelOptions) {+ this.model = opts.model;+ this.label = opts.label ?? `${PROVIDER}:${opts.model}`;+ this.client =+ opts.client ??+ new OpenAI({+ apiKey: opts.apiKey,+ baseURL: opts.baseUrl,+ defaultHeaders: opts.headers,+ });+ }++ async create(req: ChatRequest): Promise<ChatResponse> {+ const messages = req.messages.map(toChatMessage);+ const tools = req.tools ? req.tools.map(toChatTool) : undefined;+ const params: ChatParams = { model: this.model, messages };+ if (req.temperature !== undefined) params.temperature = req.temperature;+ if (req.maxTokens !== undefined) params.max_tokens = req.maxTokens;++ const fmt = req.responseFormat ?? { kind: "text" };+ if (fmt.kind === "json") {+ // Coerce JSON via a forced synthetic tool — the one structured-output+ // mechanism shared with Anthropic (no reliance on `response_format`).+ params.tools = [+ ...(tools ?? []),+ { type: "function", function: { name: JSON_TOOL, description: "Return the answer as a JSON object.", parameters: { type: "object", additionalProperties: true } } },+ ];+ params.tool_choice = { type: "function", function: { name: JSON_TOOL } };+ } else if (fmt.kind === "tool") {+ params.tools = tools;+ params.tool_choice = { type: "function", function: { name: fmt.name } };+ } else if (tools) {+ params.tools = tools;+ }++ const resp = await this.client.chat.completions.create(params);+ return this.fromResponse(resp, fmt.kind);+ }++ private fromResponse(+ resp: OpenAI.Chat.Completions.ChatCompletion,+ format: "text" | "json" | "tool",+ ): ChatResponse {+ const choice = resp.choices[0];+ const msg = choice?.message;+ const rawCalls = (msg?.tool_calls ?? []).filter(+ (c): c is OpenAI.Chat.Completions.ChatCompletionMessageToolCall & { type: "function" } =>+ c.type === "function",+ );+ const parse = (s: string): unknown => {+ try {+ return JSON.parse(s || "{}");+ } catch {+ return {};+ }+ };++ let text = msg?.content ?? "";+ let toolCalls: ToolCall[] = rawCalls.map((c) => ({+ id: c.id,+ name: c.function.name,+ args: parse(c.function.arguments),+ }));++ if (format === "json") {+ // Surface the synthetic tool's object as JSON text; hide it from `toolCalls`.+ const jsonCall = toolCalls.find((c) => c.name === JSON_TOOL);+ if (jsonCall) text = JSON.stringify(jsonCall.args);+ toolCalls = toolCalls.filter((c) => c.name !== JSON_TOOL);+ }++ return {+ text,+ toolCalls,+ usage: normalizeUsage(resp.usage),+ stopReason: choice?.finish_reason ?? null,+ assistant: {+ role: "assistant",+ content: msg?.content ?? "",+ toolCalls: toolCalls.length ? toolCalls : undefined,+ providerRaw: { provider: PROVIDER, raw: msg },+ },+ };+ }+}++/** Cached tokens are inside `prompt_tokens`; subtract so `input` is uncached-only. */+function normalizeUsage(u: OpenAI.Completions.CompletionUsage | undefined): Usage {+ const prompt = u?.prompt_tokens ?? 0;+ const cacheRead = u?.prompt_tokens_details?.cached_tokens ?? 0;+ return {+ input: Math.max(0, prompt - cacheRead),+ output: u?.completion_tokens ?? 0,+ cacheRead,+ cacheCreate: 0,+ };+}diff --git a/src/ai/llm/types.ts b/src/ai/llm/types.tsnew file mode 100644index 00000000..7e10d791--- /dev/null+++ b/src/ai/llm/types.ts@@ -0,0 +1,113 @@+/**+ * Provider-neutral chat transport.+ *+ * Every LLM call in graft — the engine's single-shot summarize/synthesize/crux+ * ops AND the benchmark's multi-turn ReAct loop — goes through one interface,+ * {@link ChatModel}. Adapters translate this neutral shape to a concrete SDK+ * (OpenAI-compatible or native Anthropic). Nothing above this layer knows which+ * provider is in play, so adding a provider is a new adapter, never a change to+ * a call site.+ *+ * The design carries three affordances that let a single interface serve the+ * multi-turn loop as cleanly as a one-shot call:+ * - {@link ChatResponse.assistant} — a ready-to-append assistant message, so a+ * caller continues a conversation without touching provider shapes.+ * - {@link Message.providerRaw} — opaque verbatim replay of a message the same+ * adapter produced (preserves Anthropic thinking-block signatures, which must+ * be echoed back unchanged).+ * - {@link Usage} normalized to uncached-input, so token accounting is identical+ * across providers.+ */++/** A single tool invocation requested by the model. `args` is ALREADY parsed. */+export interface ToolCall {+ id: string;+ name: string;+ /** Parsed argument object. Adapters (de)serialize to their wire format. */+ args: unknown;+}++/** One turn in a conversation, in provider-neutral form. */+export interface Message {+ role: "system" | "user" | "assistant" | "tool";+ /** Plain-text content. Empty string when a turn is purely tool calls/results. */+ content: string;+ /** Assistant turns only: tool calls the model asked for. */+ toolCalls?: ToolCall[];+ /** Tool turns only: the id of the {@link ToolCall} this result answers. */+ toolCallId?: string;+ /**+ * Request a provider cache marker (`cache_control: ephemeral`) on THIS message.+ * The transport only understands this per-message flag; any sliding/rotation+ * policy lives in the caller (see the bench loop).+ */+ cacheBreakpoint?: boolean;+ /**+ * Opaque, provider-tagged payload from the adapter that produced this message.+ * When the SAME adapter replays it, the original wire form is sent verbatim+ * (preserving e.g. Anthropic thinking blocks + signatures). A different adapter+ * ignores it and reconstructs from {@link content}/{@link toolCalls}.+ */+ providerRaw?: { provider: string; raw: unknown };+}++/** A tool the model may call. `parameters` is a JSON Schema object. */+export interface ToolSpec {+ name: string;+ description: string;+ parameters: Record<string, unknown>;+}++/**+ * How the model must shape its reply:+ * - `text` — free-form assistant text.+ * - `json` — a JSON object (mapped to a forced synthetic tool on both providers,+ * since that is the one structured-output mechanism they share).+ * - `tool` — force a call to the named tool (structured output with a schema).+ */+export type ResponseFormat =+ | { kind: "text" }+ | { kind: "json" }+ | { kind: "tool"; name: string };++/**+ * Token accounting, normalized across providers. `input` is UNCACHED input only+ * (OpenAI reports cached tokens inside `prompt_tokens`; Anthropic reports them+ * separately — adapters reconcile so callers can sum these directly).+ */+export interface Usage {+ input: number;+ output: number;+ cacheRead: number;+ cacheCreate: number;+}++export interface ChatRequest {+ messages: Message[];+ tools?: ToolSpec[];+ /** Default: `{ kind: "text" }`. */+ responseFormat?: ResponseFormat;+ /** Providers that reject it (current Anthropic models) drop it in the adapter. */+ temperature?: number;+ /** Max output tokens. Required by Anthropic; adapters supply a default. */+ maxTokens?: number;+}++export interface ChatResponse {+ /** Concatenated assistant text (empty when the turn only made tool calls). */+ text: string;+ toolCalls: ToolCall[];+ usage: Usage;+ stopReason: string | null;+ /** The assistant turn as a neutral message — push straight back into `messages`. */+ assistant: Message;+}++/**+ * A configured connection to one model. `label` is a stable `<provider>:<model>`+ * string recorded in the graph manifest.+ */+export interface ChatModel {+ readonly label: string;+ create(req: ChatRequest): Promise<ChatResponse>;+}diff --git a/src/ai/providers.ts b/src/ai/providers.tsindex 5dc6019d..b03d9a57 100644--- a/src/ai/providers.ts+++ b/src/ai/providers.ts@@ -1,55 +1,106 @@import type { Summarizer } from "./summarize.js";import type { Synthesizer } from "./synthesize.js";+import type { CruxSummarizer } from "./crux.js";+import type { ChatModel } from "./llm/types.js";+import type { ProviderKind } from "./llm/factory.js";/*** User-facing configuration. Anything omitted falls back to environment- * variables and then to sensible defaults. The engine calls OpenRouter, so an- * API key is required for any LLM-backed operation.+ * variables and then to sensible defaults.+ *+ * graft is vendor-neutral: `provider` names only the WIRE FORMAT, not a company.+ * `openai` speaks the OpenAI-compatible API — point `baseUrl` at OpenRouter,+ * Fireworks, a LiteLLM proxy, Groq, a local server, or OpenAI itself, and pass+ * your own key. `anthropic` speaks the native Messages API. Any LLM-backed+ * operation needs an API key.*/export interface EngineConfig {/** Where the graph lives. Env: GRAFT_DIR. Default: `<repo>/.context`. */contextDir?: string;- /** OpenRouter key for extraction + summarization. Env: OPENROUTER_API_KEY. */- openrouterApiKey?: string;- /** OpenRouter model id. Env: GRAFT_OPENROUTER_MODEL. Default: openai/gpt-4o-mini */- openrouterModel?: string;- /** OpenRouter API base URL. Env: OPENROUTER_BASE_URL. Default: https://openrouter.ai/api/v1 */- openrouterBaseUrl?: string;+ /** Wire format / SDK. Env: GRAFT_PROVIDER. Default: `openai`. */+ provider?: ProviderKind;+ /** API key for the chosen provider. Env: GRAFT_API_KEY (legacy: OPENROUTER_API_KEY). */+ apiKey?: string;+ /** Model id. Env: GRAFT_MODEL. Provider-specific default. */+ model?: string;+ /** Base URL for OpenAI-compatible endpoints. Env: GRAFT_BASE_URL. */+ baseUrl?: string;// --- advanced: bring your own components ---- /** Override the synthesizer (defaults to OpenRouter). */+ /** Override the whole transport (skips provider/apiKey/baseUrl). */+ chatModel?: ChatModel;+ /** Override the synthesizer. */synthesizer?: Synthesizer;- /** Override the code summarizer (defaults to OpenRouter). */+ /** Override the code summarizer. */summarizer?: Summarizer;+ /** Override the per-symbol crux summarizer. */+ cruxSummarizer?: CruxSummarizer;}/** Fully-resolved configuration with all defaults applied. */export interface ResolvedConfig {contextDir?: string;- openrouterApiKey?: string;- openrouterModel: string;- openrouterBaseUrl: string;+ provider: ProviderKind;+ apiKey?: string;+ model: string;+ baseUrl?: string;+ headers?: Record<string, string>;+ /** True when the key came from the deprecated OPENROUTER_* fallback. */+ usedLegacyEnv: boolean;+ chatModel?: ChatModel;synthesizer?: Synthesizer;summarizer?: Summarizer;+ cruxSummarizer?: CruxSummarizer;}+const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";++/** Per-provider default model. */+export const DEFAULT_MODELS: Record<ProviderKind, string> = {+ openai: "openai/gpt-4o-mini",+ anthropic: "claude-sonnet-5",+};+export const DEFAULTS = {- openrouterModel: "openai/gpt-4o-mini",- openrouterBaseUrl: "https://openrouter.ai/api/v1",+ provider: "openai" as ProviderKind,+ model: DEFAULT_MODELS.openai,} as const;/** Merge user config with environment variables and defaults. */export function resolveConfig(config: EngineConfig = {}): ResolvedConfig {const env = process.env;+ const provider = config.provider ?? (env.GRAFT_PROVIDER as ProviderKind | undefined) ?? DEFAULTS.provider;++ const explicitKey = config.apiKey ?? env.GRAFT_API_KEY;+ const legacyKey = env.OPENROUTER_API_KEY;+ const apiKey = explicitKey ?? legacyKey;+ const usedLegacyEnv = !explicitKey && !!legacyKey;++ const model =+ config.model ?? env.GRAFT_MODEL ?? env.GRAFT_OPENROUTER_MODEL ?? DEFAULT_MODELS[provider];++ let baseUrl = config.baseUrl ?? env.GRAFT_BASE_URL ?? env.OPENROUTER_BASE_URL;+ // Back-compat: an existing setup with only OPENROUTER_API_KEY keeps hitting+ // OpenRouter without any config change.+ if (!baseUrl && provider === "openai" && usedLegacyEnv) baseUrl = OPENROUTER_BASE_URL;++ const headers =+ provider === "openai" && baseUrl?.includes("openrouter.ai")+ ? { "X-Title": "graft" }+ : undefined;+return {contextDir: config.contextDir ?? env.GRAFT_DIR,- openrouterApiKey: config.openrouterApiKey ?? env.OPENROUTER_API_KEY,- openrouterModel:- config.openrouterModel ?? env.GRAFT_OPENROUTER_MODEL ?? DEFAULTS.openrouterModel,- openrouterBaseUrl:- config.openrouterBaseUrl ?? env.OPENROUTER_BASE_URL ?? DEFAULTS.openrouterBaseUrl,+ provider,+ apiKey,+ model,+ baseUrl,+ headers,+ usedLegacyEnv,+ chatModel: config.chatModel,synthesizer: config.synthesizer,summarizer: config.summarizer,+ cruxSummarizer: config.cruxSummarizer,};}diff --git a/src/ai/summarize.ts b/src/ai/summarize.tsindex 82548af6..e1ff5737 100644--- a/src/ai/summarize.ts+++ b/src/ai/summarize.ts@@ -1,4 +1,4 @@-import OpenAI from "openai";+import type { ChatModel } from "./llm/types.js";/*** Turns one source-code file into a short prose summary for the knowledge graph.@@ -33,29 +33,19 @@ function userContent(code: string, path: string): string {return `File: ${path}\n\n${clipped}`;}-/** Summarizer backed by OpenRouter's OpenAI-compatible chat API. */-export class OpenRouterSummarizer implements Summarizer {- private client: OpenAI;- private model: string;-- constructor(apiKey: string, model: string, baseUrl = "https://openrouter.ai/api/v1") {- this.client = new OpenAI({- apiKey,- baseURL: baseUrl,- defaultHeaders: { "X-Title": "Context Graph Engine" },- });- this.model = model;- }+/** Summarizer backed by any {@link ChatModel} (a plain-text completion). */+export class ChatSummarizer implements Summarizer {+ constructor(private model: ChatModel) {}async summarize(code: string, opts: { path: string }): Promise<string> {- const response = await this.client.chat.completions.create({- model: this.model,+ const res = await this.model.create({temperature: 0,+ maxTokens: 2048,messages: [{ role: "system", content: SYSTEM_PROMPT },{ role: "user", content: userContent(code, opts.path) },],});- return response.choices[0]?.message?.content?.trim() ?? "";+ return res.text.trim();}}diff --git a/src/ai/synthesize.ts b/src/ai/synthesize.tsindex 96e73f7c..b4638692 100644--- a/src/ai/synthesize.ts+++ b/src/ai/synthesize.ts@@ -6,7 +6,7 @@* incidental identifier. Each node is attributed to the source files it is* grounded in, so provenance (and staleness) stays exact.*/-import OpenAI from "openai";+import type { ChatModel } from "./llm/types.js";/** A directed edge to another node, by node name (resolved to a slug later). */export interface SynthLink {@@ -122,44 +122,34 @@ function clean(nodes: unknown): SynthNode[] {return out;}-const RECORD_TOOL = {- type: "function" as const,- function: {- name: "record_graph",- description: "Record the curated architecture-graph nodes and their links.",- parameters: NODES_SCHEMA,- },-};--/** Synthesizer backed by OpenRouter's OpenAI-compatible chat API (tool calling). */-export class OpenRouterSynthesizer implements Synthesizer {- private client: OpenAI;- private model: string;+const RECORD_TOOL = "record_graph";- constructor(apiKey: string, model: string, baseUrl = "https://openrouter.ai/api/v1") {- this.client = new OpenAI({ apiKey, baseURL: baseUrl, defaultHeaders: { "X-Title": "Context Graph Engine" } });- this.model = model;- }+/** Synthesizer backed by any {@link ChatModel} via forced tool calling. */+export class ChatSynthesizer implements Synthesizer {+ constructor(private model: ChatModel) {}async synthesize(files: FileSummary[]): Promise<SynthNode[]> {if (files.length === 0) return [];- const response = await this.client.chat.completions.create({- model: this.model,+ const res = await this.model.create({temperature: 0,- tools: [RECORD_TOOL],- tool_choice: { type: "function", function: { name: "record_graph" } },+ maxTokens: 8192,+ tools: [+ {+ name: RECORD_TOOL,+ description: "Record the curated architecture-graph nodes and their links.",+ parameters: NODES_SCHEMA as unknown as Record<string, unknown>,+ },+ ],+ responseFormat: { kind: "tool", name: RECORD_TOOL },messages: [{ role: "system", content: SYSTEM_PROMPT },{ role: "user", content: userContent(files) },],});- const call = response.choices[0]?.message?.tool_calls?.[0];- if (!call || call.type !== "function") return [];- try {- return clean((JSON.parse(call.function.arguments) as { nodes?: unknown }).nodes);- } catch {- return [];- }+ const call = res.toolCalls[0];+ if (!call) return [];+ // `args` is already a parsed object — no JSON.parse.+ return clean((call.args as { nodes?: unknown })?.nodes);}}diff --git a/src/cli.ts b/src/cli.tsindex 3488aede..6f840004 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -20,7 +20,8 @@ import { Command } from "commander";import { relative, resolve } from "node:path";import { fileURLToPath } from "node:url";import { Graft } from "./engine.js";-import { resolveConfig } from "./ai/providers.js";+import { resolveConfig, type EngineConfig } from "./ai/providers.js";+import type { ProviderKind } from "./ai/llm/factory.js";import { formatCheckReport } from "./context/check.js";import { formatGraphCheckReport } from "./graph/check.js";import { runInit } from "./claude/init.js";@@ -38,11 +39,34 @@ 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)");+ .option("--dir <path>", "context graph directory (default: <repo>/graft)")+ .option("--provider <name>", "LLM wire format: openai | anthropic (env GRAFT_PROVIDER)")+ .option("--model <id>", "model id for the LLM pass (env GRAFT_MODEL)")+ .option("--api-key <key>", "provider API key (env GRAFT_API_KEY)")+ .option("--base-url <url>", "OpenAI-compatible endpoint URL (env GRAFT_BASE_URL)");++interface GlobalOpts {+ dir?: string;+ provider?: string;+ model?: string;+ apiKey?: string;+ baseUrl?: string;+}++/** Config drawn from the global CLI flags (env + defaults fill the rest). */+function cliConfig(): EngineConfig {+ const o = program.opts<GlobalOpts>();+ return {+ contextDir: o.dir,+ provider: o.provider as ProviderKind | undefined,+ model: o.model,+ apiKey: o.apiKey,+ baseUrl: o.baseUrl,+ };+}function engineFrom(): Graft {- const opts = program.opts<{ dir?: string }>();- return new Graft({ contextDir: opts.dir });+ return new Graft(cliConfig());}program@@ -88,12 +112,18 @@ program// --deep needs a key; without one, degrade to the $0 structural build// rather than failing — the wiring graph is still worth having.let deep = opts.deep;- if (deep && !resolveConfig().openrouterApiKey) {+ const resolved = resolveConfig(cliConfig());+ if (deep && !resolved.apiKey) {deep = false;console.error(- "⚠ no OPENROUTER_API_KEY set — falling back to the structural build (no LLM summaries).\n" +- " Set OPENROUTER_API_KEY (https://openrouter.ai/keys) and re-run `graft build --deep`\n" +- " to add concept nodes and per-symbol summaries.",+ "⚠ no API key set — falling back to the structural build (no LLM summaries).\n" ++ " Set GRAFT_API_KEY (and GRAFT_PROVIDER / GRAFT_BASE_URL / GRAFT_MODEL for your\n" ++ " provider) and re-run `graft build --deep` to add concept nodes and summaries.",+ );+ }+ if (deep && resolved.usedLegacyEnv) {+ console.error(+ "⚠ using OPENROUTER_API_KEY (deprecated) — prefer GRAFT_API_KEY + GRAFT_BASE_URL.",);}diff --git a/src/engine.ts b/src/engine.tsindex 84b2f32b..8f9e2106 100644--- a/src/engine.ts+++ b/src/engine.ts@@ -7,13 +7,15 @@* sync with the code (for CI).** The graph is a folder of linked markdown files committed to the repo; git is- * the sync. This class wires the OpenRouter LLM providers into the build/check+ * the sync. This class wires the configured LLM provider into the build/check* pipelines; an API key is required for any LLM-backed operation.*/import { resolveConfig, type EngineConfig, type ResolvedConfig } from "./ai/providers.js";-import { OpenRouterSynthesizer, type Synthesizer } from "./ai/synthesize.js";-import { OpenRouterSummarizer, type Summarizer } from "./ai/summarize.js";-import { OpenRouterCruxSummarizer, type CruxSummarizer } from "./ai/crux.js";+import { ChatSynthesizer, type Synthesizer } from "./ai/synthesize.js";+import { ChatSummarizer, type Summarizer } from "./ai/summarize.js";+import { ChatCruxSummarizer, type CruxSummarizer } from "./ai/crux.js";+import { createChatModel } from "./ai/llm/factory.js";+import type { ChatModel } from "./ai/llm/types.js";import { buildContext, CODE_EXTENSIONS, type BuildProgress, type BuildResult } from "./context/build.js";import { checkContext, type CheckResult } from "./context/check.js";import { buildGraph, type GraphBuildOptions, type GraphBuildResult } from "./graph/build.js";@@ -94,35 +96,45 @@ export class Graft {return ask(dir, query, { contextDir: this.cfg.contextDir, limit: opts.limit, source: opts.source, full: opts.full });}- /** The OpenRouter API key, or a clear error telling the user how to set it. */- private requireKey(): string {- if (!this.cfg.openrouterApiKey) {+ private _chatModel?: ChatModel;++ /** The configured transport, or a clear error telling the user how to set a key. */+ private chatModel(): ChatModel {+ if (this.cfg.chatModel) return this.cfg.chatModel;+ if (this._chatModel) return this._chatModel;+ if (!this.cfg.apiKey) {throw new Error(- "No OpenRouter API key. Set OPENROUTER_API_KEY (get one at https://openrouter.ai/keys) " +- "to build or summarize the graph.",+ "No API key. Set GRAFT_API_KEY (and GRAFT_PROVIDER / GRAFT_BASE_URL / GRAFT_MODEL " ++ "for your provider) to build or summarize the graph.",);}- return this.cfg.openrouterApiKey;+ this._chatModel = createChatModel({+ provider: this.cfg.provider,+ apiKey: this.cfg.apiKey,+ model: this.cfg.model,+ baseUrl: this.cfg.baseUrl,+ headers: this.cfg.headers,+ });+ return this._chatModel;}private synthesizer(): Synthesizer {- if (this.cfg.synthesizer) return this.cfg.synthesizer;- return new OpenRouterSynthesizer(this.requireKey(), this.cfg.openrouterModel, this.cfg.openrouterBaseUrl);+ return this.cfg.synthesizer ?? new ChatSynthesizer(this.chatModel());}/** Per-node crux summarizer for the code graph's Tier-2 pass. */private cruxSummarizer(): CruxSummarizer {- return new OpenRouterCruxSummarizer(this.requireKey(), this.cfg.openrouterModel, this.cfg.openrouterBaseUrl);+ return this.cfg.cruxSummarizer ?? new ChatCruxSummarizer(this.chatModel());}private summarizer(): Summarizer {- if (this.cfg.summarizer) return this.cfg.summarizer;- return new OpenRouterSummarizer(this.requireKey(), this.cfg.openrouterModel, this.cfg.openrouterBaseUrl);+ return this.cfg.summarizer ?? new ChatSummarizer(this.chatModel());}/** Human label for the active model, recorded in the manifest. */private modelLabel(): string {- if (this.cfg.synthesizer || this.cfg.summarizer) return "custom";- return `openrouter:${this.cfg.openrouterModel}`;+ if (this.cfg.chatModel) return this.cfg.chatModel.label;+ if (this.cfg.synthesizer || this.cfg.summarizer || this.cfg.cruxSummarizer) return "custom";+ return `${this.cfg.provider}:${this.cfg.model}`;}}diff --git a/src/index.ts b/src/index.tsindex 34ce34c8..6f491457 100644--- a/src/index.ts+++ b/src/index.ts@@ -27,10 +27,18 @@ export type { GraphCheckResult, GraphCheckOptions } from "./graph/check.js";export type { ContextNode, NodeLink, SourceRef, Manifest } from "./context/node-file.js";export type { EngineConfig, ResolvedConfig } from "./ai/providers.js";-export { resolveConfig, DEFAULTS } from "./ai/providers.js";+export { resolveConfig, DEFAULTS, DEFAULT_MODELS } from "./ai/providers.js";-// Providers, for advanced/custom setups.-export { OpenRouterSynthesizer } from "./ai/synthesize.js";+// Provider transport, for advanced/custom setups.+export type { ChatModel, ChatRequest, ChatResponse, Message, ToolSpec, ToolCall, Usage } from "./ai/llm/types.js";+export { createChatModel, type ProviderKind, type ChatModelConfig } from "./ai/llm/factory.js";+export { OpenAIChatModel } from "./ai/llm/openai.js";+export { AnthropicChatModel } from "./ai/llm/anthropic.js";++// Engine ops, for advanced/custom setups.+export { ChatSynthesizer } from "./ai/synthesize.js";export type { Synthesizer, SynthNode, SynthLink, FileSummary } from "./ai/synthesize.js";-export { OpenRouterSummarizer } from "./ai/summarize.js";+export { ChatSummarizer } from "./ai/summarize.js";export type { Summarizer } from "./ai/summarize.js";+export { ChatCruxSummarizer } from "./ai/crux.js";+export type { CruxSummarizer, FileCruxInput, NodeCrux, NodeRef } from "./ai/crux.js";diff --git a/test/llm-adapters.test.ts b/test/llm-adapters.test.tsnew file mode 100644index 00000000..9363bc2d--- /dev/null+++ b/test/llm-adapters.test.ts@@ -0,0 +1,215 @@+/**+ * Network-free adapter tests. Each adapter is handed a STUB SDK client that+ * records the request it received and returns a canned response, so we assert+ * both directions of the translation (neutral → wire, wire → neutral) with no+ * key and no network.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import type OpenAI from "openai";+import type Anthropic from "@anthropic-ai/sdk";+import { OpenAIChatModel } from "../src/ai/llm/openai.js";+import { AnthropicChatModel } from "../src/ai/llm/anthropic.js";+import type { ChatRequest } from "../src/ai/llm/types.js";++// --- OpenAI adapter ---------------------------------------------------------++function fakeOpenAI(resp: unknown) {+ const box: { params?: any } = {};+ const client = {+ chat: { completions: { create: async (params: any) => ((box.params = params), resp) } },+ } as unknown as OpenAI;+ return { client, box };+}++function openAiResp(over: Partial<any> = {}): any {+ return {+ choices: [{ message: { content: "hello", tool_calls: [] }, finish_reason: "stop" }],+ usage: { prompt_tokens: 100, completion_tokens: 20, prompt_tokens_details: { cached_tokens: 30 } },+ ...over,+ };+}++test("openai: plain text — system/user map to strings, usage is uncached-only", async () => {+ const { client, box } = fakeOpenAI(openAiResp());+ const m = new OpenAIChatModel({ apiKey: "x", model: "gpt-x", client });+ const res = await m.create({+ messages: [+ { role: "system", content: "sys" },+ { role: "user", content: "hi" },+ ],+ temperature: 0,+ });+ assert.equal(box.params.model, "gpt-x");+ assert.equal(box.params.messages[0].content, "sys"); // plain string, no cache parts+ assert.equal(box.params.temperature, 0); // forwarded on OpenAI-compatible+ assert.equal(box.params.tools, undefined);+ assert.equal(res.text, "hello");+ assert.deepEqual(res.usage, { input: 70, output: 20, cacheRead: 30, cacheCreate: 0 });+});++test("openai: cacheBreakpoint turns content into a cache_control part", async () => {+ const { client, box } = fakeOpenAI(openAiResp());+ const m = new OpenAIChatModel({ apiKey: "x", model: "gpt-x", client });+ await m.create({ messages: [{ role: "user", content: "hi", cacheBreakpoint: true }] });+ const part = box.params.messages[0].content[0];+ assert.equal(part.type, "text");+ assert.deepEqual(part.cache_control, { type: "ephemeral" });+});++test("openai: forced tool — args come back PARSED", async () => {+ const resp = openAiResp({+ choices: [+ {+ message: {+ content: null,+ tool_calls: [{ id: "c1", type: "function", function: { name: "record_graph", arguments: '{"nodes":[1,2]}' } }],+ },+ finish_reason: "tool_calls",+ },+ ],+ });+ const { client, box } = fakeOpenAI(resp);+ const m = new OpenAIChatModel({ apiKey: "x", model: "gpt-x", client });+ const res = await m.create({+ messages: [{ role: "user", content: "go" }],+ tools: [{ name: "record_graph", description: "d", parameters: { type: "object" } }],+ responseFormat: { kind: "tool", name: "record_graph" },+ });+ assert.deepEqual(box.params.tool_choice, { type: "function", function: { name: "record_graph" } });+ assert.equal(res.toolCalls.length, 1);+ assert.deepEqual(res.toolCalls[0].args, { nodes: [1, 2] });+});++test("openai: json mode routes through a synthetic forced tool and returns JSON text", async () => {+ const resp = openAiResp({+ choices: [+ {+ message: {+ content: null,+ tool_calls: [{ id: "c1", type: "function", function: { name: "emit_json", arguments: '{"correct":true}' } }],+ },+ finish_reason: "tool_calls",+ },+ ],+ });+ const { client, box } = fakeOpenAI(resp);+ const m = new OpenAIChatModel({ apiKey: "x", model: "gpt-x", client });+ const res = await m.create({ messages: [{ role: "user", content: "grade" }], responseFormat: { kind: "json" } });+ assert.equal(box.params.tool_choice.function.name, "emit_json");+ assert.equal(res.text, '{"correct":true}');+ assert.equal(res.toolCalls.length, 0); // synthetic tool hidden+});++test("openai: assistant providerRaw replays verbatim", async () => {+ const { client, box } = fakeOpenAI(openAiResp());+ const m = new OpenAIChatModel({ apiKey: "x", model: "gpt-x", client });+ const raw = { role: "assistant", content: "verbatim", extra: 1 };+ await m.create({+ messages: [+ { role: "user", content: "hi" },+ { role: "assistant", content: "reconstructed", providerRaw: { provider: "openai", raw } },+ ],+ });+ assert.deepEqual(box.params.messages[1], raw);+});++// --- Anthropic adapter ------------------------------------------------------++function fakeAnthropic(resp: unknown) {+ const box: { params?: any } = {};+ const client = {+ messages: { create: async (params: any) => ((box.params = params), resp) },+ } as unknown as Anthropic;+ return { client, box };+}++function anthropicResp(over: Partial<any> = {}): any {+ return {+ content: [{ type: "text", text: "hi there" }],+ stop_reason: "end_turn",+ usage: { input_tokens: 70, output_tokens: 20, cache_read_input_tokens: 30, cache_creation_input_tokens: 5 },+ ...over,+ };+}++test("anthropic: system is hoisted, temperature dropped, max_tokens defaulted", async () => {+ const { client, box } = fakeAnthropic(anthropicResp());+ const m = new AnthropicChatModel({ apiKey: "x", model: "claude-x", client });+ const res = await m.create({+ messages: [+ { role: "system", content: "sys" },+ { role: "user", content: "hi" },+ ],+ temperature: 0, // must NOT be forwarded+ });+ assert.equal(box.params.system[0].text, "sys");+ assert.equal(box.params.messages.length, 1);+ assert.equal(box.params.messages[0].role, "user");+ assert.equal(box.params.temperature, undefined);+ assert.equal(box.params.max_tokens, 4096);+ assert.deepEqual(res.usage, { input: 70, output: 20, cacheRead: 30, cacheCreate: 5 });+});++test("anthropic: consecutive tool results coalesce into ONE user turn", async () => {+ const { client, box } = fakeAnthropic(anthropicResp());+ const m = new AnthropicChatModel({ apiKey: "x", model: "claude-x", client });+ const req: ChatRequest = {+ messages: [+ { role: "user", content: "q" },+ { role: "assistant", content: "", toolCalls: [{ id: "a", name: "t", args: {} }, { id: "b", name: "t", args: {} }] },+ { role: "tool", toolCallId: "a", content: "ra" },+ { role: "tool", toolCallId: "b", content: "rb" },+ ],+ };+ await m.create(req);+ const msgs = box.params.messages;+ const lastUser = msgs[msgs.length - 1];+ assert.equal(lastUser.role, "user");+ assert.equal(lastUser.content.length, 2); // both tool_result blocks in one turn+ assert.equal(lastUser.content[0].tool_use_id, "a");+ assert.equal(lastUser.content[1].tool_use_id, "b");+});++test("anthropic: tool_use input is an object (no JSON.parse round-trip)", async () => {+ const resp = anthropicResp({+ content: [{ type: "tool_use", id: "u1", name: "record_graph", input: { nodes: [1] } }],+ stop_reason: "tool_use",+ });+ const { client } = fakeAnthropic(resp);+ const m = new AnthropicChatModel({ apiKey: "x", model: "claude-x", client });+ const res = await m.create({+ messages: [{ role: "user", content: "go" }],+ tools: [{ name: "record_graph", description: "d", parameters: { type: "object" } }],+ responseFormat: { kind: "tool", name: "record_graph" },+ });+ assert.deepEqual(res.toolCalls[0].args, { nodes: [1] });+});++test("anthropic: reconstructed assistant tool_use carries the object input", async () => {+ const { client, box } = fakeAnthropic(anthropicResp());+ const m = new AnthropicChatModel({ apiKey: "x", model: "claude-x", client });+ await m.create({+ messages: [+ { role: "user", content: "q" },+ { role: "assistant", content: "", toolCalls: [{ id: "u1", name: "t", args: { k: 1 } }] },+ { role: "tool", toolCallId: "u1", content: "res" },+ ],+ });+ const asst = box.params.messages[1];+ assert.equal(asst.content[0].type, "tool_use");+ assert.deepEqual(asst.content[0].input, { k: 1 });+});++test("anthropic: json mode forces emit_json and returns serialized text", async () => {+ const resp = anthropicResp({+ content: [{ type: "tool_use", id: "j1", name: "emit_json", input: { correct: true } }],+ stop_reason: "tool_use",+ });+ const { client, box } = fakeAnthropic(resp);+ const m = new AnthropicChatModel({ apiKey: "x", model: "claude-x", client });+ const res = await m.create({ messages: [{ role: "user", content: "grade" }], responseFormat: { kind: "json" } });+ assert.deepEqual(box.params.tool_choice, { type: "tool", name: "emit_json" });+ assert.equal(res.text, '{"correct":true}');+ assert.equal(res.toolCalls.length, 0);+});diff --git a/test/llm-ops.test.ts b/test/llm-ops.test.tsnew file mode 100644index 00000000..9ff7d082--- /dev/null+++ b/test/llm-ops.test.ts@@ -0,0 +1,81 @@+/**+ * The three engine ops (summarize / synthesize / crux) over a fake transport —+ * proves each builds the right ChatRequest and parses the response, with no key+ * and no network. Structured ops (synthesize, crux) ride forced tool-calling;+ * summarize is plain text.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { ChatSummarizer } from "../src/ai/summarize.js";+import { ChatSynthesizer } from "../src/ai/synthesize.js";+import { ChatCruxSummarizer } from "../src/ai/crux.js";+import type { ChatModel, ChatRequest, ChatResponse, ToolCall } from "../src/ai/llm/types.js";++/** Records the last request and replays a canned response. */+class FakeChatModel implements ChatModel {+ readonly label = "fake:model";+ last?: ChatRequest;+ constructor(private reply: { text?: string; toolCalls?: ToolCall[] }) {}+ async create(req: ChatRequest): Promise<ChatResponse> {+ this.last = req;+ return {+ text: this.reply.text ?? "",+ toolCalls: this.reply.toolCalls ?? [],+ usage: { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 },+ stopReason: "stop",+ assistant: { role: "assistant", content: this.reply.text ?? "" },+ };+ }+}++test("ChatSummarizer sends plain text and returns trimmed content", async () => {+ const m = new FakeChatModel({ text: " a prose summary " });+ const out = await new ChatSummarizer(m).summarize("code", { path: "a.ts" });+ assert.equal(out, "a prose summary");+ assert.equal(m.last?.responseFormat, undefined); // plain text+ assert.equal(m.last?.messages[0].role, "system");+});++test("ChatSynthesizer forces record_graph and cleans parsed args", async () => {+ const m = new FakeChatModel({+ toolCalls: [+ {+ id: "1",+ name: "record_graph",+ args: { nodes: [{ name: "Auth", type: "system", summary: "s", sources: ["a.ts"], links: [] }] },+ },+ ],+ });+ const nodes = await new ChatSynthesizer(m).synthesize([{ path: "a.ts", summary: "x" }]);+ assert.deepEqual(m.last?.responseFormat, { kind: "tool", name: "record_graph" });+ assert.equal(nodes.length, 1);+ assert.equal(nodes[0].name, "Auth");+});++test("ChatCruxSummarizer forces record_symbols and normalizes numbers", async () => {+ const m = new FakeChatModel({+ toolCalls: [+ { id: "1", name: "record_symbols", args: { symbols: [{ id: "sym1", summary: "does x", crux_start: 3.9, crux_end: 5 }] } },+ ],+ });+ const out = await new ChatCruxSummarizer(m).describeFile({+ path: "a.ts",+ source: "l1\nl2\nl3\nl4\nl5\n",+ nodes: [{ id: "sym1", kind: "function", signature: null, startLine: 1, endLine: 5 }],+ });+ assert.deepEqual(m.last?.responseFormat, { kind: "tool", name: "record_symbols" });+ assert.deepEqual(out, [{ id: "sym1", summary: "does x", crux_start: 3, crux_end: 5 }]);+});++test("structured ops degrade gracefully when the model returns no tool call", async () => {+ const empty = new FakeChatModel({ toolCalls: [] });+ assert.deepEqual(await new ChatSynthesizer(empty).synthesize([{ path: "a.ts", summary: "x" }]), []);+ assert.deepEqual(+ await new ChatCruxSummarizer(empty).describeFile({+ path: "a.ts",+ source: "x",+ nodes: [{ id: "s", kind: "function", signature: null, startLine: 1, endLine: 1 }],+ }),+ [],+ );+});