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
Collapse CLI to build/check/ask, add wiring cards + active ask channel
anirudhkumar-nanonets3aca1f337eb5
diff --git a/.claude/skills/graft/SKILL.md b/.claude/skills/graft/SKILL.mdnew file mode 100644index 00000000..7645bb6f--- /dev/null+++ b/.claude/skills/graft/SKILL.md@@ -0,0 +1,27 @@+---+name: graft+description: This repo is indexed by graft/. For ANY task here — understanding+ how something works, finding where code lives, or scoping a change — get your+ context from graft before grepping or reading source files.+---++# graft++This repo's code is summarised in `graft/` — small markdown nodes, each+explaining one part in plain prose and naming the exact files and line-spans it+covers. Reading a node costs a few hundred tokens; reading source to rebuild the+same understanding costs thousands.++**Get context from graft first — two ways, both land here:**++- Ask: `graft ask "<your task, in plain words>"` — returns the relevant nodes,+ ranked, with file:line pointers.+- Or explore as usual: grep / ls / cat inside `graft/`. A grep for any concept,+ symbol, or filename hits the node that covers it; `graft/INDEX.md` lists them+ all.++**Then work from the node.** Its summary is the answer; its `covers:` list gives+the exact file:line. Open a source file only to edit those lines.++Don't grep or read whole source files to build understanding — graft already+did.diff --git a/.context/ai-model-integration.md b/.context/ai-model-integration.mddeleted file mode 100644index 7ed26adf..00000000--- a/.context/ai-model-integration.md+++ /dev/null@@ -1,32 +0,0 @@-----name: AI Model Integration-slug: ai-model-integration-type: system-sources:- - path: src/ai/providers.ts- hash: 8d4258cf8990f2fb6ac4664221fe96b5385edf8428f5f5b8a75958b8447c2cb0- - path: src/ai/summarize.ts- hash: c207e3e66f7386f7baff659cf00a3d87901e86d33ad1c0b04e4bb7943f5b5c21- - path: src/ai/synthesize.ts- hash: 2455b828410429e13cb029b6d9d4ee00532808bb63deec658445aeabb1323db0-sources_digest: 22e2c0a1bc0211ff99916ab816560b79484d4b9f608ea978eeecd3c5f4116637-links:- - to: benchmarking-system- relation: part_of- description: Supports the benchmarking system by providing AI model capabilities.-generator:- version: 1-----<!-- context:generated:start -->-## Summary--This system manages the integration of AI models for summarization and synthesis tasks, allowing for both local and remote processing through configurable settings.--## Related--- part of [[benchmarking-system]] — Supports the benchmarking system by providing AI model capabilities.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/.context/benchmarking-metrics.md b/.context/benchmarking-metrics.mddeleted file mode 100644index 9fad783f..00000000--- a/.context/benchmarking-metrics.md+++ /dev/null@@ -1,32 +0,0 @@-----name: Benchmarking Metrics-slug: benchmarking-metrics-type: concept-sources:- - path: bench/agent.ts- hash: e10d64f913c9517cef84cce58ea042d71bed3e94182c791245170eca54060e31- - path: bench/judge.ts- hash: 94c222341b066e4f3134b3d9d3f30f31b9ffe7b92967086b07c58f297d349936- - path: bench/report.ts- hash: 775be8c40a8e4172521bba8f6a1f026fa23c4d24b9b5225da3ed5b745077a5b0-sources_digest: 1a67b360c8323619bb19a61d96bfa51c43becce2db8f6422cc49ad32c0ef8fa6-links:- - to: benchmarking-system- relation: defines- description: Establishes the metrics used for performance evaluation.-generator:- version: 1-----<!-- context:generated:start -->-## Summary--This concept defines the key performance metrics used in benchmarking, including token usage, latency, correctness, and cost, which are critical for evaluating AI model performance.--## Related--- defines [[benchmarking-system]] — Establishes the metrics used for performance evaluation.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/.context/benchmarking-results-reporting.md b/.context/benchmarking-results-reporting.mddeleted file mode 100644index c1e394c2..00000000--- a/.context/benchmarking-results-reporting.md+++ /dev/null@@ -1,28 +0,0 @@-----name: Benchmarking Results Reporting-slug: benchmarking-results-reporting-type: system-sources:- - path: bench/report.ts- hash: 775be8c40a8e4172521bba8f6a1f026fa23c4d24b9b5225da3ed5b745077a5b0-sources_digest: f7b46f3036503f43413cb48d25fa6ce54585514fb19e9b4e923c0c5628ce8aed-links:- - to: benchmarking-system- relation: depends_on- description: Relies on benchmarking data for generating reports.-generator:- version: 1-----<!-- context:generated:start -->-## Summary--This system aggregates and formats benchmarking results into a human-readable report, providing insights into performance metrics and cost evaluations.--## Related--- depends on [[benchmarking-system]] — Relies on benchmarking data for generating reports.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/.context/benchmarking-system.md b/.context/benchmarking-system.mddeleted file mode 100644index 9359f3a9..00000000--- a/.context/benchmarking-system.md+++ /dev/null@@ -1,44 +0,0 @@-----name: Benchmarking System-slug: benchmarking-system-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: f9d9235f3661e03b721564a786cc80cbd50584cedb6a80f0bbb5f7757ccd724b- - path: bench/selfcheck.ts- hash: 0eaf577938e20fa27d9cd0157bc8843fdc37165d85696789334b8605138f4bb4- - path: bench/tasks.ts- hash: d21168797f40d193a914aca0c438409d29d300441bc0a6a518c93869240b3b69-sources_digest: b82fc41740c1a096a0fd5c3f20776231e57194958bef6c87a28a6975ff3d9142-links:- - to: ai-model-integration- relation: uses- description: Utilizes AI models for benchmarking tasks.- - to: benchmarking-results-reporting- relation: produces- description: Generates reports summarizing benchmarking results.-generator:- version: 1-----<!-- context:generated:start -->-## Summary--This system orchestrates the benchmarking of AI models, facilitating the evaluation of performance metrics such as token usage, latency, and correctness through various components including agents, judges, and reporting mechanisms.--## Related--- uses [[ai-model-integration]] — Utilizes AI models for benchmarking tasks.-- produces [[benchmarking-results-reporting]] — Generates reports summarizing benchmarking results.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/.context/configuration-management.md b/.context/configuration-management.mddeleted file mode 100644index 28f3db63..00000000--- a/.context/configuration-management.md+++ /dev/null@@ -1,28 +0,0 @@-----name: Configuration Management-slug: configuration-management-type: concept-sources:- - path: src/ai/providers.ts- hash: 8d4258cf8990f2fb6ac4664221fe96b5385edf8428f5f5b8a75958b8447c2cb0-sources_digest: 12e8fd63a512b486816eb62cb8cb53f9e8f7f3b5306eeb5d0bc2b30042178bf9-links:- - to: ai-model-integration- relation: influences- description: Affects how AI models are integrated and utilized.-generator:- version: 1-----<!-- context:generated:start -->-## Summary--This concept encompasses the management of configuration settings for AI engines, allowing for flexible integration of local and remote processing options based on user-defined parameters and environment variables.--## Related--- influences [[ai-model-integration]] — Affects how AI models are integrated and utilized.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/.context/context-graph-management.md b/.context/context-graph-management.mddeleted file mode 100644index 3a0f7b95..00000000--- a/.context/context-graph-management.md+++ /dev/null@@ -1,36 +0,0 @@-----name: Context Graph Management-slug: context-graph-management-type: system-sources:- - path: src/context/build.ts- hash: cfe11ecfeab1f69aad383db3a0a282a45033b61dc8b0af1ae80dc3d41687f0cb- - path: src/context/check.ts- hash: df6c8cb642ea53f533c4deeb1143932d74b36fa5eb424c3bac73f46aca95a312- - path: src/context/node-file.ts- hash: 32e046ecd962e8709c5795fc42e3934064da5f3acc5eb5df584188b37cbfd5b9- - path: src/engine.ts- hash: 9ce688dafb10d7d3acbad361c36f7b13be33a104721779d3d8bfcb431ca6e2e9- - path: src/index.ts- hash: 5e3bfb88d938f9fbfbcefd4917e15fa32fb09ab3bd06e9de5739d248416b054a-sources_digest: 2f4644c3979157085af4d66d5e6435e8e37100d180d5dd2b3519dbd7e01b96e2-links:- - to: benchmarking-system- relation: part_of- description: Provides context management capabilities for benchmarking.-generator:- version: 1-----<!-- context:generated:start -->-## Summary--This system is responsible for building and maintaining a context graph from a codebase, ensuring that the generated content remains in sync with the underlying source files through initialization and verification processes.--## Related--- part of [[benchmarking-system]] — Provides context management capabilities for benchmarking.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/.context/error-handling-and-validation.md b/.context/error-handling-and-validation.mddeleted file mode 100644index ea318666..00000000--- a/.context/error-handling-and-validation.md+++ /dev/null@@ -1,34 +0,0 @@-----name: Error Handling and Validation-slug: error-handling-and-validation-type: concept-sources:- - path: bench/run.ts- hash: f9d9235f3661e03b721564a786cc80cbd50584cedb6a80f0bbb5f7757ccd724b- - path: src/context/check.ts- hash: df6c8cb642ea53f533c4deeb1143932d74b36fa5eb424c3bac73f46aca95a312- - path: test/context.test.ts- hash: 977ca7f64b4b9e3f5661be18ea3710399b976cb989aa5d17af3c6ee4692aed33-sources_digest: e957e54820d8650507a9ff640ca697db275bf5cc32a1452e76c5e7fc2c302048-links:- - to: benchmarking-system- relation: supports- description: >-- Enhances the reliability of the benchmarking system through validation- mechanisms.-generator:- version: 1-----<!-- context:generated:start -->-## Summary--This concept addresses the strategies employed for error handling and validation throughout the benchmarking and context management processes, ensuring robustness and reliability in operations.--## Related--- supports [[benchmarking-system]] — Enhances the reliability of the benchmarking system through validation mechanisms.-<!-- context:generated:end -->--## Notes--_Anything written below the generated block is preserved when the graph is regenerated._diff --git a/.context/manifest.json b/.context/manifest.jsondeleted file mode 100644index b4931992..00000000--- a/.context/manifest.json+++ /dev/null@@ -1,172 +0,0 @@-{- "version": 1,- "model": "openrouter:openai/gpt-4o-mini",- "repoDigest": "83e9219d224cc08f493579beca8812a8f7cc05ac76ecc206b055bfc033f85830",- "files": [- {- "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": "f9d9235f3661e03b721564a786cc80cbd50584cedb6a80f0bbb5f7757ccd724b"- },- {- "path": "bench/selfcheck.ts",- "hash": "0eaf577938e20fa27d9cd0157bc8843fdc37165d85696789334b8605138f4bb4"- },- {- "path": "bench/tasks.ts",- "hash": "d21168797f40d193a914aca0c438409d29d300441bc0a6a518c93869240b3b69"- },- {- "path": "install.sh",- "hash": "01ca60d495dca47e9831b5fe2f0c80bdbe8405a944124d758b951ae263639ac2"- },- {- "path": "src/ai/providers.ts",- "hash": "8d4258cf8990f2fb6ac4664221fe96b5385edf8428f5f5b8a75958b8447c2cb0"- },- {- "path": "src/ai/summarize.ts",- "hash": "c207e3e66f7386f7baff659cf00a3d87901e86d33ad1c0b04e4bb7943f5b5c21"- },- {- "path": "src/ai/synthesize.ts",- "hash": "2455b828410429e13cb029b6d9d4ee00532808bb63deec658445aeabb1323db0"- },- {- "path": "src/cli.ts",- "hash": "b61374af84daa862309aef1b92fb43082be4021d4d19f2a14fb1b8378beb58bb"- },- {- "path": "src/context/build.ts",- "hash": "cfe11ecfeab1f69aad383db3a0a282a45033b61dc8b0af1ae80dc3d41687f0cb"- },- {- "path": "src/context/check.ts",- "hash": "df6c8cb642ea53f533c4deeb1143932d74b36fa5eb424c3bac73f46aca95a312"- },- {- "path": "src/context/node-file.ts",- "hash": "32e046ecd962e8709c5795fc42e3934064da5f3acc5eb5df584188b37cbfd5b9"- },- {- "path": "src/engine.ts",- "hash": "9ce688dafb10d7d3acbad361c36f7b13be33a104721779d3d8bfcb431ca6e2e9"- },- {- "path": "src/index.ts",- "hash": "5e3bfb88d938f9fbfbcefd4917e15fa32fb09ab3bd06e9de5739d248416b054a"- },- {- "path": "src/ingest/fs.ts",- "hash": "a8339532da34b44d35eb9ad16e7106adb1262d73d9895b1bd94574337fb2019f"- },- {- "path": "src/util/id.ts",- "hash": "5fabc8ddcc3abc907ce69f04ad2ebe51933262cf44aa2dfd40589f71f1926e8a"- },- {- "path": "test/context.test.ts",- "hash": "977ca7f64b4b9e3f5661be18ea3710399b976cb989aa5d17af3c6ee4692aed33"- },- {- "path": "test/helpers.ts",- "hash": "e45af1d38d7c6d4abc804fc74e9ae4c3373cf78769c17b16b185c3ee0e2c3228"- }- ],- "nodes": [- {- "slug": "ai-model-integration",- "name": "AI Model Integration",- "type": "system",- "sources": [- "src/ai/providers.ts",- "src/ai/summarize.ts",- "src/ai/synthesize.ts"- ],- "sourcesDigest": "22e2c0a1bc0211ff99916ab816560b79484d4b9f608ea978eeecd3c5f4116637"- },- {- "slug": "benchmarking-metrics",- "name": "Benchmarking Metrics",- "type": "concept",- "sources": [- "bench/agent.ts",- "bench/judge.ts",- "bench/report.ts"- ],- "sourcesDigest": "1a67b360c8323619bb19a61d96bfa51c43becce2db8f6422cc49ad32c0ef8fa6"- },- {- "slug": "benchmarking-results-reporting",- "name": "Benchmarking Results Reporting",- "type": "system",- "sources": [- "bench/report.ts"- ],- "sourcesDigest": "f7b46f3036503f43413cb48d25fa6ce54585514fb19e9b4e923c0c5628ce8aed"- },- {- "slug": "benchmarking-system",- "name": "Benchmarking System",- "type": "system",- "sources": [- "bench/agent.ts",- "bench/judge.ts",- "bench/llm.ts",- "bench/report.ts",- "bench/run.ts",- "bench/selfcheck.ts",- "bench/tasks.ts"- ],- "sourcesDigest": "b82fc41740c1a096a0fd5c3f20776231e57194958bef6c87a28a6975ff3d9142"- },- {- "slug": "configuration-management",- "name": "Configuration Management",- "type": "concept",- "sources": [- "src/ai/providers.ts"- ],- "sourcesDigest": "12e8fd63a512b486816eb62cb8cb53f9e8f7f3b5306eeb5d0bc2b30042178bf9"- },- {- "slug": "context-graph-management",- "name": "Context Graph Management",- "type": "system",- "sources": [- "src/context/build.ts",- "src/context/check.ts",- "src/context/node-file.ts",- "src/engine.ts",- "src/index.ts"- ],- "sourcesDigest": "2f4644c3979157085af4d66d5e6435e8e37100d180d5dd2b3519dbd7e01b96e2"- },- {- "slug": "error-handling-and-validation",- "name": "Error Handling and Validation",- "type": "concept",- "sources": [- "bench/run.ts",- "src/context/check.ts",- "test/context.test.ts"- ],- "sourcesDigest": "e957e54820d8650507a9ff640ca697db275bf5cc32a1452e76c5e7fc2c302048"- }- ]-}diff --git a/src/ask/ask.ts b/src/ask/ask.tsnew file mode 100644index 00000000..91d4d664--- /dev/null+++ b/src/ask/ask.ts@@ -0,0 +1,276 @@+/**+ * `graft ask "<task>"` — the ACTIVE channel.+ *+ * One tool that routes a plain-words query to the right graph and returns a lean,+ * ranked context pack (prose + exact `file:line` + related), never raw JSON and+ * never whole files:+ *+ * - Structural intent ("what calls X", "callers of X", "what does X import")+ * → walk the wiring graph's edges and return the neighbour symbols with spans.+ * - Everything else → lexical rank over concept nodes (prose) and wiring symbols+ * (name + signature + summary), returning the best few with pointers.+ *+ * v1 is deterministic and $0 (term-overlap scoring, no LLM, no embeddings). The+ * output is markdown so it drops straight into an agent's context.+ */+import { existsSync, readdirSync, readFileSync } from "node:fs";+import { join, resolve } from "node:path";+import matter from "gray-matter";+import { contextDirFor } from "../context/node-file.js";+import { readGraph, wiringPath } from "../graph/write.js";+import type { EdgeV1, GraphV1, NodeV1, Relation } from "../graph/types.js";++export interface AskHit {+ kind: "concept" | "symbol" | "caller" | "callee";+ title: string;+ /** A `file` or `file:Lx-Ly` pointer the agent can open directly. */+ pointer: string;+ snippet: string;+ relation?: Relation;+ related?: string[];+ score: number;+}++export interface AskResult {+ query: string;+ mode: "structural" | "lexical" | "empty";+ /** For structural mode: the symbol whose neighbours we walked. */+ subject?: string;+ hits: AskHit[];+ note?: string;+}++const STOP = new Set([+ "the", "a", "an", "of", "to", "in", "is", "are", "how", "does", "do", "what",+ "where", "which", "that", "this", "it", "for", "on", "and", "or", "with",+ "i", "we", "get", "set", "use", "used", "using", "when", "why", "can",+]);++/** Split prose + identifiers into lowercased subword tokens (camelCase, snake, kebab). */+function tokenize(text: string): string[] {+ return text+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2") // camelCase → camel Case+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter((t) => t.length > 1 && !STOP.has(t));+}++/** Term-frequency count map. */+function counts(tokens: string[]): Map<string, number> {+ const m = new Map<string, number>();+ for (const t of tokens) m.set(t, (m.get(t) ?? 0) + 1);+ return m;+}++/** First real prose line of a node body (skips headings, markers, blanks). */+function firstProse(body: string): string {+ for (const raw of body.split("\n")) {+ const line = raw.trim();+ if (!line || line.startsWith("#") || line.startsWith("<!--") || line.startsWith("-")) continue;+ return line;+ }+ return "";+}++interface Corpus {+ concepts: Array<{ slug: string; name: string; sources: string[]; related: string[]; snippet: string; text: string }>;+ graph: GraphV1 | null;+}++function loadCorpus(outDir: string): Corpus {+ const concepts: Corpus["concepts"] = [];+ if (existsSync(outDir)) {+ for (const entry of readdirSync(outDir)) {+ if (!entry.endsWith(".md") || entry === "INDEX.md") continue;+ const parsed = matter(readFileSync(join(outDir, entry), "utf8"));+ const fm = parsed.data as Record<string, unknown>;+ const sources = Array.isArray(fm.sources)+ ? (fm.sources as Array<{ path: string }>).map((s) => s.path)+ : [];+ const related = Array.isArray(fm.links)+ ? (fm.links as Array<{ to: string }>).map((l) => l.to)+ : [];+ const snippet = firstProse(parsed.content);+ concepts.push({+ slug: String(fm.slug ?? entry.replace(/\.md$/, "")),+ name: String(fm.name ?? ""),+ sources,+ related,+ snippet,+ text: `${fm.name ?? ""} ${snippet} ${sources.join(" ")}`,+ });+ }+ }+ return { concepts, graph: readGraph(wiringPath(outDir)) };+}++/** Score a document's token counts against the query counts (name field pre-weighted by caller). */+function score(query: Map<string, number>, doc: Map<string, number>): number {+ let s = 0;+ for (const [t, qn] of query) {+ const dn = doc.get(t);+ if (dn) s += qn * dn;+ }+ return s;+}++// ── Structural intent ──────────────────────────────────────────────────────++const INCOMING = /\b(caller|callers|calls?\s+into|who\s+calls|what\s+calls|called\s+by|used\s+by|uses)\b/;+const OUTGOING = /\b(callee|callees|what\s+does\s+\w+\s+call|calls\s+what|imports?|depends\s+on)\b/;+const INCOMING_RELS: Relation[] = ["calls", "references", "implements", "extends"];+const OUTGOING_RELS: Relation[] = ["calls", "references", "imports", "implements", "extends"];++/** Pick the query word that names a real symbol (longest exact name match wins). */+function findSubject(query: string, graph: GraphV1): NodeV1[] {+ const byName = new Map<string, NodeV1[]>();+ for (const n of graph.nodes) {+ if (n.kind === "file") continue;+ const key = n.name.toLowerCase();+ byName.set(key, [...(byName.get(key) ?? []), n]);+ }+ const words = query.split(/[^A-Za-z0-9_.]+/).filter(Boolean);+ let best: NodeV1[] = [];+ let bestLen = 0;+ for (const w of words) {+ const hit = byName.get(w.toLowerCase());+ if (hit && w.length > bestLen) {+ best = hit;+ bestLen = w.length;+ }+ }+ return best;+}++function structural(query: string, graph: GraphV1, limit: number): AskResult | null {+ const wantsIn = INCOMING.test(query);+ const wantsOut = OUTGOING.test(query);+ if (!wantsIn && !wantsOut) return null;++ const subjects = findSubject(query, graph);+ if (subjects.length === 0) return null;++ const ids = new Set(subjects.map((n) => n.id));+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));+ const outgoing = wantsOut && !wantsIn; // "what does X call / import" — else default to callers+ const rels = new Set(outgoing ? OUTGOING_RELS : INCOMING_RELS);++ const hits: AskHit[] = [];+ const seen = new Set<string>();+ for (const e of graph.edges as EdgeV1[]) {+ if (!rels.has(e.relation)) continue;+ const anchor = outgoing ? e.source : e.target;+ const other = outgoing ? e.target : e.source;+ if (!ids.has(anchor) || seen.has(other + e.relation)) continue;+ seen.add(other + e.relation);+ const node = byId.get(other);+ hits.push({+ kind: outgoing ? "callee" : "caller",+ title: node ? node.name : other, // unresolved import target → raw module string+ pointer: node ? `${node.path}:${node.span}` : other,+ snippet: node?.summary?.split("\n")[0].trim() ?? node?.signature ?? "",+ relation: e.relation,+ score: 1,+ });+ }+ hits.sort((a, b) => a.pointer.localeCompare(b.pointer));+ return {+ query,+ mode: "structural",+ subject: subjects[0].name,+ hits: hits.slice(0, limit),+ note: outgoing+ ? `outgoing edges from ${subjects[0].name}`+ : `callers / references of ${subjects[0].name}`,+ };+}++// ── Lexical rank ─────────────────────────────────────────────────────────────++function lexical(query: string, corpus: Corpus, limit: number): AskResult {+ const q = counts(tokenize(query));+ const scored: AskHit[] = [];++ for (const c of corpus.concepts) {+ const nameScore = score(q, counts(tokenize(c.name))) * 3;+ const bodyScore = score(q, counts(tokenize(c.text)));+ const total = nameScore + bodyScore;+ if (total > 0) {+ scored.push({+ kind: "concept",+ title: c.name || c.slug,+ pointer: c.sources.join(", ") || c.slug,+ snippet: c.snippet,+ related: c.related,+ score: total,+ });+ }+ }++ for (const n of corpus.graph?.nodes ?? []) {+ if (n.kind === "file") continue;+ const nameScore = score(q, counts(tokenize(n.name))) * 3;+ const pathScore = score(q, counts(tokenize(n.path))) * 2;+ const bodyScore = score(q, counts(tokenize(`${n.signature ?? ""} ${n.summary ?? ""}`)));+ const total = nameScore + pathScore + bodyScore;+ if (total > 0) {+ scored.push({+ kind: "symbol",+ title: `${n.name} · ${n.kind}`,+ pointer: `${n.path}:${n.span}`,+ snippet: n.summary?.split("\n")[0].trim() ?? n.signature ?? "",+ score: total,+ });+ }+ }++ scored.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));+ return {+ query,+ mode: scored.length ? "lexical" : "empty",+ hits: scored.slice(0, limit),+ note: scored.length ? undefined : "no matching nodes — try different words, or `graft build` if graft/ is empty",+ };+}++export interface AskOptions {+ contextDir?: string;+ limit?: number;+}++/** Answer a query from the graft/ graph at `dir`. Deterministic, $0. */+export function ask(dir: string, query: string, opts: AskOptions = {}): AskResult {+ const outDir = contextDirFor(resolve(dir), opts.contextDir);+ const limit = opts.limit ?? 8;+ const corpus = loadCorpus(outDir);++ if (corpus.graph) {+ const s = structural(query, corpus.graph, limit);+ if (s) return s;+ }+ return lexical(query, corpus, limit);+}++/** Render an {@link AskResult} as a compact markdown context pack. */+export function formatAsk(r: AskResult): string {+ const head = `graft ask — "${r.query}" (${r.mode}${r.note ? `: ${r.note}` : ""})`;+ if (r.hits.length === 0) {+ return `${head}\n\n${r.note ?? "no matches."}`;+ }+ const lines = [head, ""];+ if (r.mode === "structural") {+ for (const h of r.hits) {+ const tail = h.snippet ? ` — ${h.snippet}` : "";+ lines.push(`- ${h.title} ${h.pointer} (${h.relation})${tail}`);+ }+ } else {+ r.hits.forEach((h, i) => {+ lines.push(`${i + 1}. ${h.title} [${h.kind}]`);+ lines.push(` ${h.pointer}`);+ if (h.snippet) lines.push(` ${h.snippet}`);+ if (h.related?.length) lines.push(` related: ${h.related.join(", ")}`);+ lines.push("");+ });+ }+ return lines.join("\n").trimEnd() + "\n";+}diff --git a/src/cli.ts b/src/cli.tsindex 903b3885..207ebf29 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -21,7 +21,7 @@ const program = new Command();program.name("graft").description("Build a repo's context graph as linked markdown, and keep it in sync with the code.")- .option("--dir <path>", "context graph directory (default: <repo>/.context)");+ .option("--dir <path>", "context graph directory (default: <repo>/graft)");function engineFrom(): Graft {const opts = program.opts<{ dir?: string }>();@@ -29,63 +29,81 @@ function engineFrom(): Graft {}program- .command("init")- .description("Build .context/ from your code — one markdown node per system, API, or concept")+ .command("build")+ .description(+ "Build graft/ from your code — wiring graph + per-file cards ($0, no key). " ++ "Add --deep for the LLM concept map + per-symbol summaries/crux.",+ ).argument("[dir]", "repository root", ".")+ .option("--deep", "run the LLM pass: concept nodes (graft/*.md) + per-symbol summary/crux").option("-e, --extensions <exts...>", 'code extensions to include (e.g. ".ts" ".py")')- .action(async (dir: string, opts: { extensions?: string[] }) => {+ .action(async (dir: string, opts: { deep?: boolean; extensions?: string[] }) => {const engine = engineFrom();- const r = await engine.init(dir, {- extensions: opts.extensions,+ const fmt = (o: Record<string, number>) =>+ Object.entries(o)+ .sort((a, b) => b[1] - a[1])+ .map(([k, n]) => `${n} ${k}`)+ .join(", ");++ // --deep: concept nodes first (they're LLM prose; the wiring cards link up to+ // them), then the wiring graph rewrites the cards + INDEX with those up-links.+ if (opts.deep) {+ const c = await engine.init(dir, {+ extensions: opts.extensions,+ onProgress: ({ phase, index, total, file }) =>+ process.stderr.write(+ `\r${phase === "summarize" ? "reading" : "writing"} concepts ${index + 1}/${total}: ${file.slice(0, 40).padEnd(40)}`,+ ),+ });+ process.stderr.write("\n");+ console.log(+ `✓ concepts: ${c.nodes} nodes, ${c.links} links from ${c.files} files (${c.summarized} read, ${c.cached} cached)`,+ );+ for (const e of c.errors) console.error(`✗ ${e}`);+ }++ // Wiring graph (Tier-2 cards + Tier-3 wiring.json) — always. LLM meaning only with --deep.+ const g = await engine.graph(dir, {+ llm: opts.deep,onProgress: ({ phase, index, total, file }) =>process.stderr.write(- `\r${phase === "summarize" ? "reading" : "writing"} ${index + 1}/${total}: ${file.slice(0, 50).padEnd(50)}`,+ `\r${phase === "enrich" ? "summarizing" : "parsing"} ${index + 1}/${total}: ${file.slice(0, 50).padEnd(50)}`,),});process.stderr.write("\n");- console.log(- `✓ ${r.nodes} nodes, ${r.links} links from ${r.files} files ` +- `(${r.summarized} read, ${r.cached} cached)`,- );- console.log(` → ${r.contextDir}`);- for (const e of r.errors) console.error(`✗ ${e}`);- const rel = relative(process.cwd(), r.contextDir) || ".context";- console.log(` commit it: git add ${rel} && git commit -m "update context graph"`);+ console.log(`✓ wiring: ${g.nodes} nodes (${fmt(g.byKind)}), ${g.edges} edges, ${g.cards} cards [${g.languages.join(", ")}]`);+ if (opts.deep) {+ const m = g.meaning;+ console.log(` meaning: ${m.computed} computed, ${m.cached} cached, ${m.stale} stale, ${m.pending} pending`);+ }+ console.log(` → ${g.contextDir}`);+ for (const e of g.errors) console.error(`✗ ${e}`);++ const rel = relative(process.cwd(), g.contextDir) || "graft";+ console.log(` commit it: git add ${rel} && git commit -m "update graft"`);});program- .command("graph")- .description("Build .context/graph.json — a per-symbol code graph (tree-sitter structure + optional LLM meaning)")+ .command("ask")+ .description("Query the graft/ graph — returns ranked nodes + exact file:line, routed to prose or wiring ($0, no key)")+ .argument("<query>", "what you want to understand, in plain words").argument("[dir]", "repository root", ".")- .option("--llm", "run the Tier-2 LLM pass (summary + crux); unchanged bodies are served from cache")- .action(async (dir: string, opts: { llm?: boolean }) => {+ .option("-n, --limit <n>", "max results", "8")+ .option("--json", "output the result as JSON")+ .action(async (query: string, dir: string, opts: { limit: string; json?: boolean }) => {const engine = engineFrom();- const r = await engine.graph(dir, {- llm: opts.llm,- onProgress: ({ phase, index, total, file }) =>- process.stderr.write(- `\r${phase === "enrich" ? "summarizing" : "parsing"} ${index + 1}/${total}: ${file.slice(0, 50).padEnd(50)}`,- ),- });- process.stderr.write("\n");- const fmt = (o: Record<string, number>) =>- Object.entries(o)- .sort((a, b) => b[1] - a[1])- .map(([k, n]) => `${n} ${k}`)- .join(", ");- console.log(`✓ ${r.nodes} nodes (${fmt(r.byKind)}) from ${r.files} files [${r.languages.join(", ")}]`);- console.log(` ${r.edges} edges (${fmt(r.byRelation)})`);- const m = r.meaning;- console.log(- ` meaning: ${m.computed} computed, ${m.cached} cached, ${m.stale} stale, ${m.pending} pending`,- );- console.log(` → ${r.graphPath}`);- for (const e of r.errors) console.error(`✗ ${e}`);+ const r = engine.ask(dir, query, { limit: Number(opts.limit) });+ if (opts.json) {+ console.log(JSON.stringify(r, null, 2));+ } else {+ const { formatAsk } = await import("./ask/ask.js");+ process.stdout.write(formatAsk(r));+ }});program.command("check")- .description("Fail if .context/ is stale relative to the code (for CI)")+ .description("Fail if graft/ is stale relative to the code (for CI)").argument("[dir]", "repository root", ".").option("-e, --extensions <exts...>", "code extensions to include").option("--json", "output the drift as JSON")@@ -123,7 +141,7 @@ programconst globalOpts = program.opts<{ dir?: string }>();const contextDir = contextDirFor(root, globalOpts.dir);if (!existsSync(contextDir)) {- console.error(`✗ no context graph at ${contextDir} — run \`graft init\` first`);+ console.error(`✗ no context graph at ${contextDir} — run \`graft build --deep\` first`);process.exit(1);}// dist/cli.js → dist/viewer/ (prebuilt at package build time)diff --git a/src/context/check.ts b/src/context/check.tsindex 2f53bed8..327a5a35 100644--- a/src/context/check.ts+++ b/src/context/check.ts@@ -4,7 +4,7 @@* Pure I/O + hashing: no LLM, no network, milliseconds. It re-hashes the source* files the manifest recorded and compares. Meant to run in CI: exit 0 when the* graph is fresh, 1 when it has drifted (so a PR that changed code but not the- * graph fails until `graft init` is re-run and committed).+ * graph fails until `graft build --deep` is re-run and committed).** Drift categories:* content a recorded source file's bytes changed@@ -109,7 +109,7 @@ export function checkContext(dir: string, opts: CheckOptions = {}): CheckResult/** Render a check result as a human-readable report. */export function formatCheckReport(r: CheckResult): string {if (r.missing) {- return "graft check: NO GRAPH\n\nNo .context/manifest.json found. Run `graft init` first.";+ return "graft check: NO GRAPH\n\nNo graft/manifest.json found. Run `graft build --deep` first.";}if (r.ok) return "graft check: OK — the graph is in sync with the code.";@@ -130,7 +130,7 @@ export function formatCheckReport(r: CheckResult): string {lines.push(`index mismatch (${r.indexDrift.length}):`);for (const s of r.indexDrift) lines.push(` ! ${s}`);}- lines.push("", "Run `graft init` to regenerate, then commit .context/.");+ lines.push("", "Run `graft build --deep` to regenerate, then commit graft/.");return lines.join("\n");}diff --git a/src/context/node-file.ts b/src/context/node-file.tsindex cf0453c9..c34b59cf 100644--- a/src/context/node-file.ts+++ b/src/context/node-file.ts@@ -94,10 +94,12 @@ export function digestSources(sources: SourceRef[]): string {return contentHash(lines);}-/** Absolute path of the `.context/` directory for a repo root. */+/** Absolute path of the `graft/` directory for a repo root. Visible (not+ * dot-prefixed) on purpose: default ripgrep skips hidden dirs, so the agent's+ * grep/ls/find reflex must be able to land on the graph. */export function contextDirFor(root: string, override?: string): string {if (override) return override;- return join(root, ".context");+ return join(root, "graft");}/** Render the generated body (Summary + Related) for a node. */@@ -181,7 +183,7 @@ export function readNodes(dir: string): ParsedNode[] {if (!existsSync(dir)) return [];const out: ParsedNode[] = [];for (const entry of readdirSync(dir)) {- if (!entry.endsWith(".md")) continue;+ if (!entry.endsWith(".md") || entry === "INDEX.md") continue;const fm = matter(readFileSync(join(dir, entry), "utf8")).data as Record<string, unknown>;out.push({slug: String(fm.slug ?? entry.replace(/\.md$/, "")),@@ -200,7 +202,7 @@ export function existingNodeSlugs(dir: string): Set<string> {if (!existsSync(dir)) return new Set();return new Set(readdirSync(dir)- .filter((e) => e.endsWith(".md"))+ .filter((e) => e.endsWith(".md") && e !== "INDEX.md").map((e) => e.replace(/\.md$/, "")),);}diff --git a/src/engine.ts b/src/engine.tsindex 135221dd..3ab6d3f3 100644--- a/src/engine.ts+++ b/src/engine.ts@@ -18,9 +18,10 @@ import { buildContext, CODE_EXTENSIONS, type BuildProgress, type BuildResult } fimport { checkContext, type CheckResult } from "./context/check.js";import { buildGraph, type GraphBuildOptions, type GraphBuildResult } from "./graph/build.js";import { checkGraph, type GraphCheckResult } from "./graph/check.js";+import { ask, type AskResult } from "./ask/ask.js";export { CODE_EXTENSIONS };-export type { BuildResult, BuildProgress, CheckResult, GraphBuildResult, GraphCheckResult };+export type { BuildResult, BuildProgress, CheckResult, GraphBuildResult, GraphCheckResult, AskResult };export interface InitOptions {/** Code extensions to include. Default: {@link CODE_EXTENSIONS}. */@@ -81,6 +82,15 @@ export class Graft {});}+ /**+ * Answer a plain-words query from the committed `graft/` graph — the active+ * channel. Deterministic and $0: routes structural queries to the wiring+ * edges and everything else to a lexical rank over concepts + symbols.+ */+ ask(dir: string, query: string, opts: { limit?: number } = {}): AskResult {+ return ask(dir, query, { contextDir: this.cfg.contextDir, limit: opts.limit });+ }+/** The OpenRouter API key, or a clear error telling the user how to set it. */private requireKey(): string {if (!this.cfg.openrouterApiKey) {diff --git a/src/graph/build.ts b/src/graph/build.tsindex a9ee8671..a9ecde93 100644--- a/src/graph/build.ts+++ b/src/graph/build.ts@@ -8,13 +8,14 @@* Edges (M2) and LLM summary/crux (M3) layer onto this without changing it.*/import { readFileSync } from "node:fs";-import { join, relative, resolve } from "node:path";+import { relative, resolve } from "node:path";import { walkDir } from "../ingest/fs.js";import { contextDirFor } from "../context/node-file.js";import { extractFile, languageOf, type Language, type RawEdge } from "./extract.js";import { resolveEdges } from "./resolve.js";import { enrichGraph, type EnrichStats } from "./enrich.js";-import { GRAPH_FILE, readGraph, writeGraph } from "./write.js";+import { readGraph, writeGraph, wiringPath } from "./write.js";+import { writeCards, writeIndex } from "./cards.js";import type { GraphV1, Kind, NodeV1, Relation } from "./types.js";import type { CruxSummarizer } from "../ai/crux.js";@@ -34,6 +35,8 @@ export interface GraphBuildOptions {export interface GraphBuildResult {contextDir: string;graphPath: string;+ /** Per-file wiring cards written (Tier-2 passive surface). */+ cards: number;files: number;nodes: number;edges: number;@@ -89,7 +92,7 @@ export async function buildGraph(// graph.json is its own Tier-2 cache: fold in the prior meaning layer so an// unchanged body is never re-summarized (and a Tier-1-only run never wipes it).- const prior = readGraph(join(outDir, GRAPH_FILE));+ const prior = readGraph(wiringPath(outDir));const priorById = new Map((prior?.nodes ?? []).map((n) => [n.id, n]));const meaning = await enrichGraph(nodes, priorById, sources, {summarizer: opts.summarizer,@@ -111,6 +114,11 @@ export async function buildGraph(const graphPath = writeGraph(graph, outDir);+ // Tier-2 passive surface: project the nodes into per-file markdown cards, and+ // refresh the INDEX roster. Pure projection — no LLM, no network.+ const cardStats = writeCards(graph, outDir);+ writeIndex(outDir, cardStats.files);+const byKind = {} as Record<Kind, number>;for (const n of nodes) byKind[n.kind] = (byKind[n.kind] ?? 0) + 1;const byRelation = {} as Record<Relation, number>;@@ -119,6 +127,7 @@ export async function buildGraph(return {contextDir: outDir,graphPath,+ cards: cardStats.written,files: files.length,nodes: nodes.length,edges: edges.length,@@ -129,5 +138,3 @@ export async function buildGraph(errors,};}--export { GRAPH_FILE };diff --git a/src/graph/cards.ts b/src/graph/cards.tsnew file mode 100644index 00000000..8fa0c1cb--- /dev/null+++ b/src/graph/cards.ts@@ -0,0 +1,223 @@+/**+ * Tier-2 "wiring cards" — the passive-channel surface of the wiring graph.+ *+ * The wiring graph itself lives as machine-only JSON in `graft/.graph/wiring.json`+ * (nodes + edges), which an agent never greps or reads. This module projects its+ * NODES up into markdown: one small card per source file, mirroring the source+ * tree under `graft/` (e.g. `graft/src/ai/providers.md`). Each card lists the+ * file's symbols with their `L<start>-L<end>` spans and a one-line description, so+ * a `grep <symbol>` / `find <name>` / `cat` lands on the card and the agent reads+ * ~150 tokens instead of the whole source file. Edges stay in the JSON — you can't+ * grep a traversal — and are reached through `graft ask`.+ *+ * Cards are a pure projection: no LLM work here. The one-liner is the node's LLM+ * `summary` when present (after `graft build --deep`), else its deterministic+ * `signature`, so cards are useful even in a $0 structure-only build.+ */+import { mkdirSync, writeFileSync, existsSync, readdirSync, rmSync } from "node:fs";+import { dirname, join, relative } from "node:path";+import type { GraphV1, NodeV1 } from "./types.js";+import { CACHE_DIR, readNodes } from "../context/node-file.js";+import { GRAPH_DIR } from "./write.js";++const INDEX_FILE = "INDEX.md";++export interface CardFileInfo {+ /** Card path relative to the context dir, e.g. "src/ai/providers.md". */+ card: string;+ /** Source path the card mirrors, e.g. "src/ai/providers.ts". */+ path: string;+ symbols: number;+}++export interface CardStats {+ written: number;+ pruned: number;+ files: CardFileInfo[];+}++/** The card path for a source path: mirror the tree, swap the extension for .md. */+function cardPathFor(outDir: string, sourcePath: string): string {+ const md = sourcePath.replace(/\.[^./]+$/, "") + ".md";+ return join(outDir, md);+}++/** Starting line of an "L43-L55" span, for stable ordering (0 if unparseable). */+function spanStart(span: string): number {+ const m = /^L(\d+)/.exec(span);+ return m ? Number(m[1]) : 0;+}++/** First line of a node's meaning: LLM summary if ready, else its signature. */+function oneLiner(node: NodeV1): string {+ const s = node.summary?.trim();+ if (s) return s.split("\n")[0].trim();+ return node.signature?.trim() ?? "";+}++/** path → concept-node slugs that cite it as a source (for the up-links). */+function conceptsByPath(outDir: string): Map<string, string[]> {+ const map = new Map<string, string[]>();+ for (const node of readNodes(outDir)) {+ for (const src of node.sources) {+ const list = map.get(src.path) ?? [];+ list.push(node.slug);+ map.set(src.path, list);+ }+ }+ return map;+}++/** Render one file's card. `fileNode` may be absent for parse-only fragments. */+function renderCard(+ sourcePath: string,+ fileNode: NodeV1 | undefined,+ symbols: NodeV1[],+ conceptSlugs: string[],+): string {+ const uplinks = conceptSlugs+ .sort()+ .map((s) => `[[${s}]]`)+ .join(" ");+ const head = uplinks ? `# ${sourcePath} · ${uplinks}` : `# ${sourcePath}`;+ const lines: string[] = [head, ""];++ const fileSummary = fileNode ? oneLiner(fileNode) : "";+ if (fileSummary) lines.push(fileSummary, "");++ const sorted = [...symbols].sort(+ (a, b) => spanStart(a.span) - spanStart(b.span) || a.name.localeCompare(b.name),+ );+ for (const n of sorted) {+ const desc = oneLiner(n);+ const tail = desc ? ` — ${desc}` : "";+ lines.push(`- ${n.name} · ${n.kind} · ${n.span}${tail}`);+ }+ if (sorted.length === 0) lines.push("_No extracted symbols in this file._");+ return lines.join("\n") + "\n";+}++/** Every existing card file (`.md` inside subdirs of outDir; not concept nodes). */+function listExistingCards(outDir: string): string[] {+ const out: string[] = [];+ const walk = (dir: string): void => {+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ if (e.isDirectory()) {+ if (dir === outDir && (e.name === CACHE_DIR || e.name === GRAPH_DIR)) continue;+ walk(join(dir, e.name));+ } else if (e.isFile() && e.name.endsWith(".md")) {+ out.push(join(dir, e.name));+ }+ }+ };+ for (const e of readdirSync(outDir, { withFileTypes: true })) {+ // Concept nodes and INDEX.md are top-level files — skip. Cards are in subdirs.+ if (e.isDirectory() && e.name !== CACHE_DIR && e.name !== GRAPH_DIR) {+ walk(join(outDir, e.name));+ }+ }+ return out;+}++/** Remove now-empty directories under outDir (bottom-up), skipping .cache/.graph. */+function pruneEmptyDirs(outDir: string): void {+ const visit = (dir: string): boolean => {+ // returns true if dir is empty after visiting children+ let empty = true;+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ if (dir === outDir && (e.name === CACHE_DIR || e.name === GRAPH_DIR)) {+ empty = false;+ continue;+ }+ const child = join(dir, e.name);+ if (e.isDirectory()) {+ if (visit(child)) rmSync(child, { recursive: true, force: true });+ else empty = false;+ } else {+ empty = false;+ }+ }+ return empty;+ };+ if (existsSync(outDir)) visit(outDir);+}++/**+ * Write one wiring card per source file into `outDir`, mirroring the source tree,+ * and prune cards whose source no longer exists. Returns what changed.+ */+export function writeCards(graph: GraphV1, outDir: string): CardStats {+ const byPath = new Map<string, NodeV1[]>();+ for (const n of graph.nodes) {+ const list = byPath.get(n.path) ?? [];+ list.push(n);+ byPath.set(n.path, list);+ }++ const concepts = conceptsByPath(outDir);+ const written = new Set<string>();+ const files: CardFileInfo[] = [];++ for (const [sourcePath, group] of byPath) {+ const fileNode = group.find((n) => n.kind === "file");+ const symbols = group.filter((n) => n.kind !== "file");+ const cardPath = cardPathFor(outDir, sourcePath);+ mkdirSync(dirname(cardPath), { recursive: true });+ writeFileSync(cardPath, renderCard(sourcePath, fileNode, symbols, concepts.get(sourcePath) ?? []));+ written.add(cardPath);+ files.push({ card: relative(outDir, cardPath), path: sourcePath, symbols: symbols.length });+ }++ let pruned = 0;+ for (const existing of listExistingCards(outDir)) {+ if (!written.has(existing)) {+ rmSync(existing);+ pruned++;+ }+ }+ pruneEmptyDirs(outDir);++ files.sort((a, b) => a.card.localeCompare(b.card));+ return { written: written.size, pruned, files };+}++/**+ * Write `graft/INDEX.md` — the roster an agent `cat`s to orient. Lists the concept+ * nodes on disk and the per-file cards. Deterministic order; no timestamps.+ */+export function writeIndex(outDir: string, files: CardFileInfo[]): void {+ const lines: string[] = [+ "# graft — repo map",+ "",+ "Small markdown nodes summarising this repo. `grep` any term, symbol, or",+ 'filename here, or run `graft ask "<task>"`. Each node carries prose plus exact',+ "`file:line`; open a source file only to edit the named span.",+ "",+ ];++ const concepts = readNodes(outDir).sort((a, b) => a.slug.localeCompare(b.slug));+ if (concepts.length) {+ lines.push("## Concepts", "");+ for (const c of concepts) {+ const srcs = c.sources.map((s) => s.path).join(", ");+ const tail = srcs ? ` · ${srcs}` : "";+ lines.push(`- [${c.slug}](${c.slug}.md) — ${c.name || c.slug}${tail}`);+ }+ lines.push("");+ }++ if (files.length) {+ lines.push("## Files", "");+ lines.push(+ "Per-file wiring cards mirror the source tree. `grep` a symbol or `find` a",+ "filename to land on its card.",+ "",+ );+ for (const f of files) {+ lines.push(`- [${f.card}](${f.card}) — ${f.symbols} symbol${f.symbols === 1 ? "" : "s"}`);+ }+ lines.push("");+ }++ writeFileSync(join(outDir, INDEX_FILE), lines.join("\n"));+}diff --git a/src/graph/check.ts b/src/graph/check.tsindex 5f35f96a..c0dd2046 100644--- a/src/graph/check.ts+++ b/src/graph/check.ts@@ -11,18 +11,18 @@* removed a node in graph.json no longer exists in code (run `graph`)* changed a node's body_hash differs from the committed one (run `graph`)* stale a committed node's summary is flagged stale — its body changed- * since it was last summarized (run `graph --llm`)+ * since it was last summarized (run `graft build --deep`)** `added`/`removed`/`changed` are structural: the graph no longer describes the* code. `stale` is a meaning-layer signal the last build already recorded.* `pending` (never summarized) is not drift — it's a deliberate Tier-1-only build.*/import { readFileSync } from "node:fs";-import { join, relative, resolve } from "node:path";+import { relative, resolve } from "node:path";import { contextDirFor } from "../context/node-file.js";import { extractFile, languageOf } from "./extract.js";import { listSourceFiles } from "./build.js";-import { GRAPH_FILE, readGraph } from "./write.js";+import { readGraph, wiringPath } from "./write.js";export interface GraphCheckResult {ok: boolean;@@ -54,7 +54,7 @@ export function checkGraph(dir: string, opts: GraphCheckOptions = {}): GraphChecpending: 0,};- const committed = readGraph(join(outDir, GRAPH_FILE));+ const committed = readGraph(wiringPath(outDir));if (!committed) {result.missing = true;return result;@@ -103,11 +103,11 @@ export function checkGraph(dir: string, opts: GraphCheckOptions = {}): GraphChec/** Render a graph-check result as a human-readable report. */export function formatGraphCheckReport(r: GraphCheckResult): string {if (r.missing) {- return "graph check: NO GRAPH\n\nNo .context/graph.json found. Run `graft graph` first.";+ return "graph check: NO GRAPH\n\nNo graft/.graph/wiring.json found. Run `graft build` first.";}if (r.ok) {const note = r.pending ? ` (${r.pending} node(s) not yet summarized — run \`graph --llm\`)` : "";- return `graph check: OK — graph.json is in sync with the code.${note}`;+ return `graph check: OK — the wiring graph is in sync with the code.${note}`;}const lines: string[] = ["graph check: STALE", ""];@@ -129,7 +129,7 @@ export function formatGraphCheckReport(r: GraphCheckResult): string {for (const id of r.stale) lines.push(` ! ${id}`);}lines.push("");- if (structural) lines.push("Run `graft graph` to rebuild the structure, then commit .context/.");- if (r.stale.length) lines.push("Run `graft graph --llm` to refresh stale summaries.");+ if (structural) lines.push("Run `graft build` to rebuild the structure, then commit graft/.");+ if (r.stale.length) lines.push("Run `graft build --deep` to refresh stale summaries.");return lines.join("\n");}diff --git a/src/graph/write.ts b/src/graph/write.tsindex 0aa0dfc3..e969b669 100644--- a/src/graph/write.ts+++ b/src/graph/write.ts@@ -1,18 +1,28 @@/**- * Serialize a {@link GraphV1} to `<contextDir>/graph.json`.+ * Serialize a {@link GraphV1} to `<contextDir>/.graph/wiring.json`.*- * Output is sorted (nodes by id, edges by source/relation/target) and carries no+ * The wiring graph lives in a hidden `.graph/` subdir because it is machine-only:+ * the agent never greps or reads it — it reaches the wiring data through the+ * per-file markdown cards (grep) and the `ask` tool (edge traversal). Output is+ * sorted (nodes by id, edges by source/relation/target) and carries no* timestamps, so rebuilding an unchanged repo produces a byte-identical file and* git diffs stay minimal.*/import { mkdirSync, readFileSync, writeFileSync } from "node:fs";-import { join } from "node:path";+import { dirname, join } from "node:path";import type { EdgeV1, GraphV1 } from "./types.js";-export const GRAPH_FILE = "graph.json";+/** Hidden subdir under the context dir that holds machine-only graph artifacts. */+export const GRAPH_DIR = ".graph";+export const GRAPH_FILE = "wiring.json";++/** Absolute path to the wiring graph for a context dir: `<dir>/.graph/wiring.json`. */+export function wiringPath(outDir: string): string {+ return join(outDir, GRAPH_DIR, GRAPH_FILE);+}/**- * Read an existing graph.json for use as the Tier-2 cache. Returns null when the+ * Read an existing wiring graph for use as the Tier-2 cache. Returns null when the* file is absent or unparseable (a fresh build, or a corrupt file we'll replace).*/export function readGraph(path: string): GraphV1 | null {@@ -29,8 +39,8 @@ export function writeGraph(graph: GraphV1, outDir: string): string {nodes: [...graph.nodes].sort((a, b) => a.id.localeCompare(b.id)),edges: [...graph.edges].sort(edgeOrder),};- mkdirSync(outDir, { recursive: true });- const path = join(outDir, GRAPH_FILE);+ const path = wiringPath(outDir);+ mkdirSync(dirname(path), { recursive: true });writeFileSync(path, JSON.stringify(sorted, null, 2) + "\n");return path;}diff --git a/src/viz/serve.ts b/src/viz/serve.tsindex 2a8a1e15..8d7ac1ec 100644--- a/src/viz/serve.ts+++ b/src/viz/serve.ts@@ -80,20 +80,20 @@ export async function startVizServer(opts: VizServerOptions): Promise<VizServer>}if (path === "/api/code-graph") {- const file = join(opts.contextDir, "graph.json");+ const file = join(opts.contextDir, ".graph", "wiring.json");if (!existsSync(file)) {- sendJson(res, 404, { error: "no graph.json in this context dir — run `graft graph` first" });+ sendJson(res, 404, { error: "no wiring graph in this context dir — run `graft build` first" });return;}try {const parsed = JSON.parse(readFileSync(file, "utf8"));if (parsed?.meta?.version !== 1) {- sendJson(res, 404, { error: "graph.json has an unsupported version — regenerate with `graft graph`" });+ sendJson(res, 404, { error: "wiring.json has an unsupported version — regenerate with `graft build`" });return;}sendJson(res, 200, parsed);} catch {- sendJson(res, 404, { error: "graph.json is unreadable — regenerate with `graft graph`" });+ sendJson(res, 404, { error: "wiring.json is unreadable — regenerate with `graft build`" });}return;}diff --git a/test/context.test.ts b/test/context.test.tsindex 1c29ac05..7a87aca2 100644--- a/test/context.test.ts+++ b/test/context.test.ts@@ -37,7 +37,7 @@ test("init builds one markdown node per entity, with links and a manifest", asynassert.equal(r.links, 2);assert.equal(r.files, 2);- const ctx = join(dir, ".context");+ const ctx = join(dir, "graft");assert.ok(existsSync(join(ctx, "auth-service.md")));assert.ok(existsSync(join(ctx, "token-store.md")));assert.ok(existsSync(join(ctx, "billing.md")));@@ -125,7 +125,7 @@ test("human notes below the generated block survive regeneration", async () => {const dir = makeFixture();try {await buildContext(dir, buildOpts());- const path = join(dir, ".context", "billing.md");+ const path = join(dir, "graft", "billing.md");const withNote = readFileSync(path, "utf8") + "\nHand-written note: watch out for retries.\n";writeFileSync(path, withNote);await buildContext(dir, buildOpts());diff --git a/test/viz-serve.test.ts b/test/viz-serve.test.tsindex d8c91649..a2884068 100644--- a/test/viz-serve.test.ts+++ b/test/viz-serve.test.ts@@ -38,15 +38,16 @@ test("viz server serves viewer, context graph, and gates code graph", async () =assert.equal(graph.meta.repoName, "fixture");assert.equal(graph.nodes[0].id, "alpha");- // no graph.json yet → 404 with an explanatory error+ // no wiring graph yet → 404 with an explanatory errorconst missing = await fetch(`${srv.url}/api/code-graph`);assert.equal(missing.status, 404);const body = await missing.json();- assert.match(body.error, /graft graph/);+ assert.match(body.error, /graft build/);- // valid graph.json → passthrough+ // valid wiring graph → passthrough+ mkdirSync(join(contextDir, ".graph"), { recursive: true });writeFileSync(- join(contextDir, "graph.json"),+ join(contextDir, ".graph", "wiring.json"),JSON.stringify({ meta: { version: 1, nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }),);const code = await fetch(`${srv.url}/api/code-graph`).then((r) => r.json());