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(surfaces): scope-aware map, hooks scope hint, guidance + docs
Shrish Dwivedi4c298da00e60
diff --git a/.claude/skills/graft/SKILL.md b/.claude/skills/graft/SKILL.mdindex ef762e4b..9523f485 100644--- a/.claude/skills/graft/SKILL.md+++ b/.claude/skills/graft/SKILL.md@@ -32,6 +32,10 @@ same understanding costs thousands.- **First contact with an unfamiliar repo** → `graft map` — token-budgetedorientation (dir clusters, hubs, hotspots). Read the hub cards it names ratherthan asking per subsystem.+- **Monorepos / a folder of multiple repos** → graft ranks fairly across+ sub-projects instead of letting the biggest one drown the rest; hits carry+ `[scope/]` labels naming which sub-project they're from. Know where you're+ working? Narrow with `graft ask "<task>" --in <scope>/`.You can also grep / ls / cat inside `graft/` directly (the nodes are plainmarkdown; `graft/INDEX.md` lists them) — but the commands above are faster anddiff --git a/README.md b/README.mdindex 0a4c07e1..1aeb1f10 100644--- a/README.md+++ b/README.md@@ -189,6 +189,7 @@ graft build --extensions .ts .py # only include these code extensionsgraft ask "<task>" [dir] # query the graph — ranked nodes + exact file:line (no LLM, no key)graft ask "<task>" --json # machine-readable result+graft ask "<task>" --in <scope> # narrow to one sub-project of a monorepo/multi-repo folder (see below)graft callers <symbol> [dir] # who calls/references/imports/implements/extends a symbol (no LLM, no key)graft callers <symbol> --direction out # the reverse: what the symbol itself calls/references (was `graft callees`)@@ -259,6 +260,25 @@ scripts/ 2 files · 0 symbolshotspots: set · method · src/graph/bindings.ts:L21-L23 · 38← contextDirFor · function · src/context/node-file.ts:L100-L103 · 11← wiringPath · function · src/graph/write.ts:L20-L22 · 10← ...```+## Monorepos & multi-repo folders++Graft handles two shapes without any config:++- **A monorepo with one `.git`** (a `pnpm-workspace.yaml`/`package.json`+ `workspaces`, or per-package `go.mod`/`pyproject.toml`/`Cargo.toml`) —+ `graft build` discovers each sub-project as a ranking scope. `ask`/`map`+ rank every scope on its own terms and fuse the results, so the biggest+ sub-project can't drown a small one; hits carry `[scope/]` labels, and+ `graft map` groups its directory clusters by scope first.+- **A folder of separate git repos** (no `.git` at the top) — `graft build`+ auto-splits: each child keeps its own committable `graft/`, and the parent+ gets a `graft/workspace.json` index. Queries from the parent federate across+ every child, always labeled `<child>/`. Run `graft build` inside a child to+ work on just that repo.++Either way, narrow to one sub-project with `graft ask "<task>" --in <scope>/`+once you know where you're working.+## Visualize it (`graft viz`)`graft viz` opens a local, interactive view of both graphs — no install, no devdiff --git a/src/claude/format.ts b/src/claude/format.tsindex deb05052..20a3287b 100644--- a/src/claude/format.ts+++ b/src/claude/format.ts@@ -169,7 +169,7 @@ export function formatOrientation(indexMd: string, budgetBytes = 1500): string {const directive =`[graft] This repo is indexed by graft. To find or understand code, reach for graft first — it cites exact file:line and is faster than grep/read:\n` +` • graft ask "<task>" --source — the relevant code, inline (skip the file read)\n` +- ` • graft callers <sym> · graft impact <sym> — who/what breaks if it changes\n` ++ ` • graft callers <sym> --depth 2 — who/what breaks if it changes\n` +` • graft grep "<literal>" — exhaustive search, grouped by enclosing symbol\n` +` • graft skeleton <file> · graft map — a file's API · whole-repo orientation\n`;return `${directive}\nrepo map (graft/INDEX.md):\n${indexMd.slice(0, budgetBytes)}`;diff --git a/src/claude/hooks.ts b/src/claude/hooks.tsindex 289171e8..968672b4 100644--- a/src/claude/hooks.ts+++ b/src/claude/hooks.ts@@ -5,6 +5,7 @@ import { readWiring } from './stats.js';import { formatBlastRadius, relevantRetrieval, formatOrientation } from './format.js';import { patchStats, readStats, acquireLock, readSession, writeSession } from './state.js';import { graftCliPath, claudeScriptPath } from './paths.js';+import { scopeOf, scopesOfGraph } from '../graph/scopes.js';/** Prompts shorter than this never trigger retrieval — they are almost always* conversational ("yes go ahead", "thanks") and the coverage gate can't judge@@ -27,7 +28,12 @@ export function underGraft(dir: string, file: string): boolean {}function graftJson(dir: string, args: string[]): any | null {try {- const out = execFileSync(process.execPath, [graftCliPath(), ...args],+ // GRAFT_TEST_CLI is a test seam (mirrors GRAFT_TEST_STDIN/GRAFT_TEST_SYNC_RUN) so+ // tests can point the prompt hook's `graft ask`/`graft check` calls at a stub+ // script and observe the exact args it was invoked with, instead of shelling+ // out to the real CLI (which isn't built relative to the TS source under test).+ const cliPath = process.env.GRAFT_TEST_CLI ?? graftCliPath();+ const out = execFileSync(process.execPath, [cliPath, ...args],{ cwd: dir, encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'] });return JSON.parse(out);} catch (e: any) {@@ -56,6 +62,48 @@ async function handlePostEdit(input: any, dir: string): Promise<void> {if (w) { const br = formatBlastRadius(w, file); if (br) emit('PostToolUse', br); }}+/**+ * The "you're working in backend/, weight it" hint: on a multi-scope repo,+ * narrow the prompt hook's `ask` call to whatever scope the last-edited file+ * (`stats.lastFile`, captured at {@link handlePostEdit}) sits in.+ *+ * `lastFile` is only a basename (not a repo-relative path — see+ * `handlePostEdit`), so this is a best-effort lookup against the CURRENT+ * graph: any file node whose path ends in `/<lastFile>` (or equals it, for a+ * repo-root file). Fails soft in every direction a hook must never crash on —+ * no graph, a single-scope graph, a lastFile no longer in the graph (moved,+ * deleted, or edited before the first build), or a basename that lands in+ * more than one scope (ambiguous: could be either sub-project) all skip the+ * hint silently, logging one line to stderr so the miss is visible without+ * ever failing the hook.+ */+export function lastFileScopeHint(dir: string, lastFile: string | null | undefined): string | null {+ if (!lastFile) return null;+ try {+ const w = readWiring(dir);+ if (!w) return null;+ const scopes = scopesOfGraph(w);+ if (scopes.length <= 1) return null; // single-scope: no hint, no --in+ const matches = (w.nodes ?? []).filter(+ (n) => n.kind === 'file' && (n.path === lastFile || n.path.endsWith(`/${lastFile}`)),+ );+ if (matches.length === 0) {+ console.error(`[graft] prompt hook: lastFile "${lastFile}" not found in the graph — skipping scope hint`);+ return null;+ }+ const prefixes = new Set(matches.map((n) => scopeOf(n.path, scopes).prefix));+ if (prefixes.size > 1) {+ console.error(`[graft] prompt hook: lastFile "${lastFile}" matches more than one scope — skipping scope hint`);+ return null;+ }+ const [prefix] = prefixes;+ return prefix === '' ? null : prefix; // root scope: nothing to narrow+ } catch (e: any) {+ console.error(`[graft] prompt hook: scope hint lookup failed (${e?.message ?? e}) — skipping`);+ return null;+ }+}+function handleStop(dir: string): void {// sync-run.js ships next to this module inside the package, so it resolves in// any repo that installs graft (not just graft's own). Defensive existsSync:@@ -99,7 +147,12 @@ export async function main(event: string): Promise<void> {// pulls spans itself via `graft ask --source` when a pointer looks right.// relevantRetrieval then drops the pack entirely when the prompt barely// overlaps the top hit or when every hit was already injected this session.- const ask = graftJson(dir, ['ask', prompt, '.', '--json', '-n', '3']);+ const askArgs = ['ask', prompt, '.', '--json', '-n', '3'];+ // "You're working in backend/, weight it": only fires on a multi-scope+ // repo whose lastFile resolves cleanly to one scope — see lastFileScopeHint.+ const scopeHint = lastFileScopeHint(dir, readStats(dir)?.lastFile);+ if (scopeHint) askArgs.push('--in', scopeHint);+ const ask = graftJson(dir, askArgs);if (!ask) return;const id = input.session_id || 'default';const s = readSession(dir, id);diff --git a/src/claude/skill-template.ts b/src/claude/skill-template.tsindex 6e88ce36..a995bcc6 100644--- a/src/claude/skill-template.ts+++ b/src/claude/skill-template.ts@@ -38,6 +38,10 @@ same understanding costs thousands.- **First contact with an unfamiliar repo** → \`graft map\` — token-budgetedorientation (dir clusters, hubs, hotspots). Read the hub cards it names ratherthan asking per subsystem.+- **Monorepos / a folder of multiple repos** → graft ranks fairly across+ sub-projects instead of letting the biggest one drown the rest; hits carry+ \`[scope/]\` labels naming which sub-project they're from. Know where you're+ working? Narrow with \`graft ask "<task>" --in <scope>/\`.You can also grep / ls / cat inside \`graft/\` directly (the nodes are plainmarkdown; \`graft/INDEX.md\` lists them) — but the commands above are faster anddiff --git a/src/graph/map.ts b/src/graph/map.tsindex 078bdd4a..a936e5a3 100644--- a/src/graph/map.ts+++ b/src/graph/map.ts@@ -21,6 +21,7 @@import type { GraphV1, NodeV1 } from "./types.js";import { languageOf } from "./extract.js";import { WALK_RELATIONS } from "./relations.js";+import { scopeLabel, scopeOf, scopesOfGraph } from "./scopes.js";import { savingsFooter, savingsFor, type Savings } from "../context/savings.js";export interface Hub {@@ -39,13 +40,34 @@ export interface DirEntry {hubs: Hub[];}+/** One scope's own directory breakdown — same shape a single-scope `buildRepoMap`+ * would produce for that scope's nodes alone, dir paths repo-rooted (not+ * scope-relative) so a hit is directly openable without mentally re-prefixing. */+export interface ScopeGroup {+ /** Display label via `scopeLabel` — "(root)" or "backend/". */+ scope: string;+ /** Sorted by symbol count desc (ties by path asc), capped at `maxDirs`. */+ dirs: DirEntry[];+ /** This scope's directory groups beyond the `maxDirs` cap. */+ dropped: number;+}+export interface RepoMap {totals: { files: number; symbols: number; edges: number; languages: string[] };- /** Sorted by symbol count desc (ties by path asc), capped at `maxDirs`. */+ /** Single-scope repos: sorted by symbol count desc (ties by path asc), capped+ * at `maxDirs`. Multi-scope repos: empty — use `scopes` instead (see below). */dirs: DirEntry[];+ /** Multi-scope repos ONLY (`scopesOfGraph(graph).length > 1`): one entry per+ * scope, scope label as the top-level group key, that scope's own dirs+ * second — a monorepo's sub-projects each read like their own little map+ * instead of being pooled by raw first-path-segment. Absent on single-scope+ * repos (the byte-identical-output regression guarantee: same+ * `scopesOfGraph(g).length <= 1` early branch `ask.ts` uses). */+ scopes?: ScopeGroup[];/** Global top hubs by inDegree, ties by name asc then path asc. */hotspots: Hub[];- /** Directory groups beyond the `maxDirs` cap — never silently dropped. */+ /** Directory groups beyond the `maxDirs` cap — never silently dropped.+ * Multi-scope repos: always 0 here; see each `ScopeGroup.dropped` instead. */dropped: number;/** Tokens-saved baseline: every indexed file read whole — the cost of* orienting by reading the repo instead of this map. */@@ -109,23 +131,35 @@ function sortedLanguages(paths: string[]): string[] {}/**- * Build the repo map from an already-loaded `GraphV1`. Deterministic: same- * graph in → byte-identical `RepoMap` out (modulo insertion order, which is- * never observed — everything meaningful is sorted).+ * The directory-clustering core, factored out so it can run once over the+ * whole graph (single-scope) or once per scope's own node subset+ * (multi-scope) with identical grouping/splitting/sorting rules.+ *+ * `stripPrefix` is the scope prefix to strip before computing depth/split+ * ("" for single-scope / the root scope — a no-op, `relPath` is then the+ * identity function). Reported `DirEntry.path`s are always repo-rooted+ * (the prefix is reattached), never scope-relative — a hit stays directly+ * openable without mentally re-prefixing it.*/-export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RepoMap {- const maxDirs = opts.maxDirs ?? DEFAULT_MAX_DIRS;- const hubsPerDir = opts.hubsPerDir ?? DEFAULT_HUBS_PER_DIR;- const hotspotsN = opts.hotspots ?? DEFAULT_HOTSPOTS;-- const fileNodes = graph.nodes.filter((n) => n.kind === "file");+function computeDirEntries(+ nodes: NodeV1[],+ inDegree: Map<string, number>,+ maxDirs: number,+ hubsPerDir: number,+ stripPrefix: string,+): { dirs: DirEntry[]; dropped: number } {+ const fileNodes = nodes.filter((n) => n.kind === "file");const totalFiles = fileNodes.length;- // Pass 1: depth-1 file counts, to find (at most one) group over the- // split threshold — two groups can't both exceed 60% of the same total.+ const relPath = (path: string): string =>+ stripPrefix === "" ? path : path === stripPrefix ? "" : path.slice(stripPrefix.length + 1);++ // Pass 1: depth-1 file counts (relative to `stripPrefix`), to find (at most+ // one) group over the split threshold — two groups can't both exceed 60%+ // of the same total.const depth1FileCounts = new Map<string, number>();for (const n of fileNodes) {- const key = dirKey(n.path, 1);+ const key = dirKey(relPath(n.path), 1);depth1FileCounts.set(key, (depth1FileCounts.get(key) ?? 0) + 1);}let splitSegment: string | null = null;@@ -138,12 +172,13 @@ export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): Re}}- const depthFor = (path: string): number => (splitSegment !== null && dirKey(path, 1) === splitSegment ? 2 : 1);+ const depthFor = (rp: string): number => (splitSegment !== null && dirKey(rp, 1) === splitSegment ? 2 : 1);// Pass 2: assign every node (file and symbol alike) to its group.const groups = new Map<string, { files: NodeV1[]; symbols: NodeV1[] }>();- for (const n of graph.nodes) {- const key = dirKey(n.path, depthFor(n.path));+ for (const n of nodes) {+ const rp = relPath(n.path);+ const key = dirKey(rp, depthFor(rp));let g = groups.get(key);if (!g) {g = { files: [], symbols: [] };@@ -153,10 +188,11 @@ export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): Reelse g.symbols.push(n);}- const inDegree = computeInDegree(graph);+ const fullPath = (relKey: string): string =>+ stripPrefix === "" ? relKey : relKey === "" ? stripPrefix : `${stripPrefix}/${relKey}`;- const dirEntries: DirEntry[] = [...groups.entries()].map(([path, g]) => ({- path,+ const dirEntries: DirEntry[] = [...groups.entries()].map(([relKey, g]) => ({+ path: fullPath(relKey),files: g.files.length,symbols: g.symbols.length,languages: sortedLanguages(g.files.map((f) => f.path)),@@ -166,6 +202,53 @@ export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RedirEntries.sort((a, b) => b.symbols - a.symbols || a.path.localeCompare(b.path));const dropped = Math.max(0, dirEntries.length - maxDirs);const dirs = dirEntries.slice(0, maxDirs);+ return { dirs, dropped };+}++/**+ * Build the repo map from an already-loaded `GraphV1`. Deterministic: same+ * graph in → byte-identical `RepoMap` out (modulo insertion order, which is+ * never observed — everything meaningful is sorted).+ *+ * Single-scope repos (`scopesOfGraph(graph).length <= 1`, the overwhelming+ * majority) take the exact pre-scope-awareness path below — same branch guard+ * `ask.ts` uses, so this is a byte-level regression guarantee. Multi-scope+ * repos group `dirs` by scope FIRST (see `scopes` on `RepoMap`); `dirs` itself+ * is then empty and `scopes` carries the breakdown instead.+ */+export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): RepoMap {+ const maxDirs = opts.maxDirs ?? DEFAULT_MAX_DIRS;+ const hubsPerDir = opts.hubsPerDir ?? DEFAULT_HUBS_PER_DIR;+ const hotspotsN = opts.hotspots ?? DEFAULT_HOTSPOTS;++ const fileNodes = graph.nodes.filter((n) => n.kind === "file");+ const totalFiles = fileNodes.length;+ const inDegree = computeInDegree(graph);++ const scopes = scopesOfGraph(graph);+ let dirs: DirEntry[];+ let dropped: number;+ let scopeGroups: ScopeGroup[] | undefined;++ if (scopes.length <= 1) {+ const computed = computeDirEntries(graph.nodes, inDegree, maxDirs, hubsPerDir, "");+ dirs = computed.dirs;+ dropped = computed.dropped;+ } else {+ // Multi-scope: each scope gets its OWN dir breakdown, computed exactly+ // like the single-scope path above but fed only that scope's node+ // subset (prefix stripped for depth/split math, reattached on output).+ // Grouping by raw first-path-segment instead would pool every scope+ // nested more than one segment deep (e.g. two workspace packages both+ // under `packages/`) into one shared bucket, losing the split entirely.+ dirs = [];+ dropped = 0;+ scopeGroups = scopes.map((s) => {+ const nodesInScope = graph.nodes.filter((n) => scopeOf(n.path, scopes).prefix === s.prefix);+ const computed = computeDirEntries(nodesInScope, inDegree, maxDirs, hubsPerDir, s.prefix);+ return { scope: scopeLabel(s.prefix), dirs: computed.dirs, dropped: computed.dropped };+ });+ }const allSymbols = graph.nodes.filter((n) => n.kind !== "file");const hotspots = topHubs(allSymbols, inDegree, hotspotsN);@@ -178,6 +261,7 @@ export function buildRepoMap(graph: GraphV1, opts: BuildRepoMapOptions = {}): Relanguages: sortedLanguages(fileNodes.map((f) => f.path)),},dirs,+ scopes: scopeGroups,hotspots,dropped,saved: savingsFor(graph, fileNodes.map((f) => f.path)),@@ -206,6 +290,12 @@ function formatHotspot(h: Hub): string {return `${h.name} · ${h.kind} · ${h.path}:${h.span} · ${h.inDegree}←`;}+/** The "+N more directories not shown" note, or null when nothing was dropped. */+function droppedNote(dropped: number): string | null {+ if (dropped <= 0) return null;+ return `… +${dropped} more director${dropped === 1 ? "y" : "ies"} not shown (raise max-dirs to see more)`;+}+/*** Render a `RepoMap` as the human report. Deterministic (same map in → same* string out) and targets <= 6000 chars for a typical repo (the `maxDirs`/@@ -217,11 +307,22 @@ export function formatRepoMap(map: RepoMap): string {const header = `repo map — ${totals.files} files · ${totals.symbols} symbols · ${totals.edges} edges · ${totals.languages.join(", ")}`;const lines: string[] = [header, ""];- for (const d of map.dirs) lines.push(formatDirLine(d));- if (map.dropped > 0) {- lines.push(`… +${map.dropped} more director${map.dropped === 1 ? "y" : "ies"} not shown (raise max-dirs to see more)`);+ if (map.scopes) {+ // Multi-scope: scope label as the top-level group heading, that scope's+ // own dirs listed under it — `map.dirs` is empty here, see `buildRepoMap`.+ for (const sg of map.scopes) {+ lines.push(`## ${sg.scope}`);+ for (const d of sg.dirs) lines.push(formatDirLine(d));+ const note = droppedNote(sg.dropped);+ if (note) lines.push(note);+ lines.push("");+ }+ } else {+ for (const d of map.dirs) lines.push(formatDirLine(d));+ const note = droppedNote(map.dropped);+ if (note) lines.push(note);+ lines.push("");}- lines.push("");lines.push(`hotspots: ${map.hotspots.map(formatHotspot).join(" ")}`);const body = lines.join("\n");diff --git a/src/hosts/instructions.ts b/src/hosts/instructions.tsindex 1dd85292..417c37ed 100644--- a/src/hosts/instructions.ts+++ b/src/hosts/instructions.ts@@ -32,6 +32,9 @@ hotspots), no LLM, no key.transitively for the full blast radius. For structural questions, skipranking and use this directly.- Or browse: \`graft/INDEX.md\` lists every node; follow the links.+- Monorepos and folders of multiple repos rank fairly across sub-projects —+ hits carry \`[scope/]\` labels naming which one they're from. Narrow with+ \`graft ask "<task>" --in <scope>/\` once you know where you're working.If a returned span is truncated ("+N more lines"), open the file at that exactrange before finalizing. Only open source files when a node genuinely lacks adiff --git a/test/claude-format.test.ts b/test/claude-format.test.tsindex 942a1f86..fcf0984d 100644--- a/test/claude-format.test.ts+++ b/test/claude-format.test.ts@@ -142,6 +142,10 @@ test('formatOrientation labels and truncates to budget', () => {assert.match(out, /reach for graft first/, 'always-on usage directive present');// index truncated to budget (1500) + the fixed usage directive header (~500).assert.ok(out.length < 2200, 'index trimmed to budget; only the fixed directive adds to it');+ // Regression: `graft impact` was folded into `graft callers --depth` in 0.6.0 —+ // the always-on directive must teach the current command, not a dead one.+ assert.doesNotMatch(out, /graft impact\b/, 'does not teach the removed `graft impact` command');+ assert.match(out, /graft callers .*--depth/, 'teaches blast radius via callers --depth instead');});test('renderSubagent shows agent name and its last query', () => {diff --git a/test/claude-hooks.test.ts b/test/claude-hooks.test.tsindex ed9423a4..d2933fec 100644--- a/test/claude-hooks.test.ts+++ b/test/claude-hooks.test.ts@@ -1,9 +1,9 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { existsSync, mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { underGraft, main } from '../src/claude/hooks.js';+import { underGraft, main, lastFileScopeHint } from '../src/claude/hooks.js';import { readStats } from '../src/claude/state.js';import { runSync } from '../src/claude/sync-run.js';import { writeStats, emptyStats, acquireLock } from '../src/claude/state.js';@@ -119,6 +119,230 @@ test('runSync stays dirty when build succeeds but wiring is unreadable', () => {assert.equal(acquireLock(d), true, 'lock released');});+// ── lastFileScopeHint (the "you're working in backend/, weight it" hint) ──++/** backend/ (py) + frontend/ (ts) scopes, one file node each, distinct+ * basenames so a lookup by basename is unambiguous. */+function writeMultiScopeWiring(d: string): void {+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(+ join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({+ meta: {+ nodeCount: 2, edgeCount: 0, languages: ['typescript', 'python'],+ scopes: [+ { prefix: 'backend', label: 'backend', markers: ['pyproject.toml'] },+ { prefix: 'frontend', label: 'frontend', markers: ['package.json'] },+ ],+ },+ nodes: [+ { id: 'backend/app.py', name: 'app.py', kind: 'file', path: 'backend/app.py', span: 'L1-L1' },+ { id: 'frontend/src/auth.ts', name: 'auth.ts', kind: 'file', path: 'frontend/src/auth.ts', span: 'L1-L1' },+ ],+ edges: [],+ }),+ );+}++test('lastFileScopeHint: resolves a matching lastFile to its scope prefix', () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-hint-'));+ writeMultiScopeWiring(d);+ assert.equal(lastFileScopeHint(d, 'app.py'), 'backend');+ assert.equal(lastFileScopeHint(d, 'auth.ts'), 'frontend');+});++test('lastFileScopeHint: null on a single-scope graph, a missing lastFile, or no graph at all', () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-hint-'));+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(+ join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({+ meta: { nodeCount: 1, edgeCount: 0, languages: [] },+ nodes: [{ id: 'a.ts', name: 'a.ts', kind: 'file', path: 'a.ts', span: 'L1-L1' }],+ edges: [],+ }),+ );+ assert.equal(lastFileScopeHint(d, 'a.ts'), null, 'single-scope repo: no hint, no --in');+ assert.equal(lastFileScopeHint(d, null), null, 'no lastFile yet: no hint');+ assert.equal(lastFileScopeHint(d, undefined), null);+ const noGraphDir = mkdtempSync(join(tmpdir(), 'graft-hint-nograph-'));+ assert.equal(lastFileScopeHint(noGraphDir, 'a.ts'), null, 'no graph built yet: no hint');+});++test('lastFileScopeHint: a root-scope lastFile needs no --in (root already covers everything)', () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-hint-'));+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(+ join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({+ meta: {+ nodeCount: 2, edgeCount: 0, languages: [],+ scopes: [+ { prefix: '', label: '', markers: [] },+ { prefix: 'frontend', label: 'frontend', markers: ['package.json'] },+ ],+ },+ nodes: [+ { id: 'README.md', name: 'README.md', kind: 'file', path: 'README.md', span: 'L1-L1' },+ { id: 'frontend/a.ts', name: 'a.ts', kind: 'file', path: 'frontend/a.ts', span: 'L1-L1' },+ ],+ edges: [],+ }),+ );+ assert.equal(lastFileScopeHint(d, 'README.md'), null);+});++test('lastFileScopeHint: fails soft (null, logged to stderr) when lastFile is stale — not in the current graph', () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-hint-'));+ writeMultiScopeWiring(d);+ const errors: string[] = [];+ const origError = console.error;+ (console as any).error = (...a: unknown[]) => { errors.push(a.join(' ')); };+ try {+ assert.equal(lastFileScopeHint(d, 'nonexistent.ts'), null, 'a stale lastFile degrades to no hint, never throws');+ assert.ok(errors.length > 0, 'the skipped hint is logged to stderr, not silently swallowed');+ assert.match(errors[0], /nonexistent\.ts/);+ } finally {+ console.error = origError;+ }+});++test('lastFileScopeHint: fails soft (null, logged to stderr) when lastFile is ambiguous across scopes', () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-hint-'));+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(+ join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({+ meta: {+ nodeCount: 2, edgeCount: 0, languages: [],+ scopes: [+ { prefix: 'backend', label: 'backend', markers: ['go.mod'] },+ { prefix: 'frontend', label: 'frontend', markers: ['package.json'] },+ ],+ },+ nodes: [+ { id: 'backend/index.ts', name: 'index.ts', kind: 'file', path: 'backend/index.ts', span: 'L1-L1' },+ { id: 'frontend/index.ts', name: 'index.ts', kind: 'file', path: 'frontend/index.ts', span: 'L1-L1' },+ ],+ edges: [],+ }),+ );+ const errors: string[] = [];+ const origError = console.error;+ (console as any).error = (...a: unknown[]) => { errors.push(a.join(' ')); };+ try {+ assert.equal(lastFileScopeHint(d, 'index.ts'), null, 'ambiguous across scopes degrades to no hint, never throws');+ assert.ok(errors.length > 0, 'the skipped hint is logged to stderr, not silently swallowed');+ } finally {+ console.error = origError;+ }+});++// ── prompt hook: --in <scope> narrowing end-to-end ─────────────────────────++/** A `graft ask` stub (`.cjs` so it runs as CommonJS regardless of this+ * package's `"type": "module"`) that records the exact argv it was invoked+ * with — GRAFT_TEST_CLI (mirrors GRAFT_TEST_STDIN/GRAFT_TEST_SYNC_RUN) points+ * graftJson at it instead of the real, unbuilt-in-tests CLI. */+function writeAskArgsStub(d: string): { stub: string; argsFile: string } {+ const stub = join(d, 'ask-stub.cjs');+ const argsFile = join(d, 'args-seen.json');+ writeFileSync(+ stub,+ `const fs = require('fs');\n` ++ `const args = process.argv.slice(2);\n` ++ `fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(args));\n` ++ `process.stdout.write(JSON.stringify({ query: args[1] || '', mode: 'lexical', hits: [], coverage: 1 }));\n`,+ );+ return { stub, argsFile };+}++test('prompt hook passes --in <scope> when lastFile resolves to a scope on a multi-scope repo', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-prompt-scope-'));+ writeMultiScopeWiring(d);+ writeStats(d, { ...emptyStats(), lastFile: 'app.py' });+ const { stub, argsFile } = writeAskArgsStub(d);+ process.env.CLAUDE_PROJECT_DIR = d;+ process.env.GRAFT_TEST_CLI = stub;+ try {+ await runWithStdin(+ JSON.stringify({ session_id: 'p-scope', prompt: 'how does the backend handle auth' }),+ () => main('prompt'),+ );+ const argsSeen: string[] = JSON.parse(readFileSync(argsFile, 'utf8'));+ const inIdx = argsSeen.indexOf('--in');+ assert.ok(inIdx !== -1, 'the ask call carries --in');+ assert.equal(argsSeen[inIdx + 1], 'backend', 'narrowed to the scope lastFile (app.py) resolves to');+ } finally {+ delete process.env.GRAFT_TEST_CLI;+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});++test('prompt hook omits --in on a single-scope repo even with lastFile set', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-prompt-scope-'));+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));+ writeStats(d, { ...emptyStats(), lastFile: 'auth.ts' });+ const { stub, argsFile } = writeAskArgsStub(d);+ process.env.CLAUDE_PROJECT_DIR = d;+ process.env.GRAFT_TEST_CLI = stub;+ try {+ await runWithStdin(+ JSON.stringify({ session_id: 'p-single', prompt: 'how does auth work here' }),+ () => main('prompt'),+ );+ const argsSeen: string[] = JSON.parse(readFileSync(argsFile, 'utf8'));+ assert.equal(argsSeen.indexOf('--in'), -1, 'single-scope repo: no --in narrowing');+ } finally {+ delete process.env.GRAFT_TEST_CLI;+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});++test('prompt hook omits --in and logs to stderr when lastFile is ambiguous across scopes', async () => {+ const d = mkdtempSync(join(tmpdir(), 'graft-prompt-scope-'));+ mkdirSync(join(d, 'graft', '.graph'), { recursive: true });+ writeFileSync(+ join(d, 'graft', '.graph', 'wiring.json'),+ JSON.stringify({+ meta: {+ nodeCount: 2, edgeCount: 0, languages: [],+ scopes: [+ { prefix: 'backend', label: 'backend', markers: ['go.mod'] },+ { prefix: 'frontend', label: 'frontend', markers: ['package.json'] },+ ],+ },+ nodes: [+ { id: 'backend/index.ts', name: 'index.ts', kind: 'file', path: 'backend/index.ts', span: 'L1-L1' },+ { id: 'frontend/index.ts', name: 'index.ts', kind: 'file', path: 'frontend/index.ts', span: 'L1-L1' },+ ],+ edges: [],+ }),+ );+ writeStats(d, { ...emptyStats(), lastFile: 'index.ts' });+ const { stub, argsFile } = writeAskArgsStub(d);+ const errors: string[] = [];+ const origError = console.error;+ (console as any).error = (...a: unknown[]) => { errors.push(a.join(' ')); };+ process.env.CLAUDE_PROJECT_DIR = d;+ process.env.GRAFT_TEST_CLI = stub;+ try {+ await runWithStdin(+ JSON.stringify({ session_id: 'p-ambig', prompt: 'how is the index wired up' }),+ () => main('prompt'),+ );+ const argsSeen: string[] = JSON.parse(readFileSync(argsFile, 'utf8'));+ assert.equal(argsSeen.indexOf('--in'), -1, 'ambiguous lastFile: no --in narrowing');+ assert.ok(errors.length > 0, 'the skipped hint is logged to stderr — never a silent no-op the hook can hide');+ } finally {+ console.error = origError;+ delete process.env.GRAFT_TEST_CLI;+ delete process.env.CLAUDE_PROJECT_DIR;+ }+});+test('prompt branch stays silent and writes no session when graft is not built', async () => {const d = mkdtempSync(join(tmpdir(), 'graft-prompt-'));process.env.CLAUDE_PROJECT_DIR = d;diff --git a/test/claude-skill-template.test.ts b/test/claude-skill-template.test.tsindex 4de31331..7f9ebde4 100644--- a/test/claude-skill-template.test.ts+++ b/test/claude-skill-template.test.ts@@ -17,4 +17,6 @@ test('skill template is a well-formed SKILL.md', () => {assert.match(body, /truncated/i, 'body tells the agent to follow up on truncated spans');assert.match(body, /graft grep/, 'body routes sweeps to graft grep');assert.match(body, /graft map/, 'body tells the agent to orient with graft map before exploring');+ assert.match(body, /\[scope\/\]/, 'body teaches the [scope/] label on multi-scope hits');+ assert.match(body, /--in <scope>\//, 'body teaches narrowing with ask --in <scope>/');});diff --git a/test/graph-map.test.ts b/test/graph-map.test.tsindex e1524eee..b5847f28 100644--- a/test/graph-map.test.ts+++ b/test/graph-map.test.ts@@ -9,7 +9,7 @@import { test } from "node:test";import assert from "node:assert/strict";import { buildRepoMap, formatRepoMap } from "../src/graph/map.js";-import type { GraphV1, NodeV1, EdgeV1, Kind, Relation } from "../src/graph/types.js";+import type { GraphV1, NodeV1, EdgeV1, Kind, Relation, ScopeV1 } from "../src/graph/types.js";let counter = 0;@@ -60,6 +60,15 @@ function graphOf(nodes: NodeV1[], edges: EdgeV1[]): GraphV1 {};}+/** Same as `graphOf`, plus `meta.scopes` — the same hand-set-scopes pattern+ * `ask.test.ts`'s regression pin uses, so a multi-scope fixture doesn't need a+ * real repo build just to exercise `buildRepoMap`'s scope-aware branch. */+function graphOfWithScopes(nodes: NodeV1[], edges: EdgeV1[], scopes: ScopeV1[]): GraphV1 {+ const g = graphOf(nodes, edges);+ g.meta.scopes = scopes;+ return g;+}+// ── totals ────────────────────────────────────────────────────────────────test("buildRepoMap: totals count files, symbols, edges, and languages across the whole graph", () => {@@ -233,6 +242,138 @@ test("buildRepoMap: dirs beyond maxDirs are capped and counted into dropped", ()assert.equal(map.dropped, 3);});+// ── scope-aware grouping (multi-scope repos) ────────────────────────────++/** frontend/ (ts) and backend/ (py) as sibling scopes, each with its own+ * sub-dirs so the per-scope dir breakdown has something to group. */+function twoScopeFixture(): GraphV1 {+ const nodes = [+ fileNode("frontend/src/a.ts"),+ symNode("frontend/src/a.ts", "one"),+ fileNode("frontend/lib/b.ts"),+ symNode("frontend/lib/b.ts", "two"),+ symNode("frontend/lib/b.ts", "three"),+ fileNode("backend/app.py"),+ symNode("backend/app.py", "four"),+ ];+ const scopes: ScopeV1[] = [+ { prefix: "backend", label: "backend", markers: ["pyproject.toml"] },+ { prefix: "frontend", label: "frontend", markers: ["package.json"] },+ ];+ return graphOfWithScopes(nodes, [], scopes);+}++test("buildRepoMap: single-scope output is byte-identical whether meta.scopes is absent or the canonical root form", () => {+ const nodes = [fileNode("src/a.ts"), symNode("src/a.ts", "fn")];+ const bare = buildRepoMap(graphOf(nodes, []));+ const canonical = buildRepoMap(+ graphOfWithScopes(nodes, [], [{ prefix: "", label: "", markers: [] }]),+ );+ assert.deepEqual(bare, canonical, "canonical single root scope must not change buildRepoMap's output");+ assert.equal(bare.scopes, undefined, "single-scope RepoMap carries no `scopes` field");+});++test("buildRepoMap: multi-scope graph groups dirs by scope first, dirs within scope second", () => {+ const map = buildRepoMap(twoScopeFixture());++ assert.equal(map.dirs.length, 0, "multi-scope: the flat `dirs` field is empty, `scopes` carries the breakdown");+ assert.ok(map.scopes, "multi-scope RepoMap carries a `scopes` field");+ assert.deepEqual(map.scopes!.map((s) => s.scope), ["backend/", "frontend/"], "scope order follows meta.scopes");++ const backend = map.scopes!.find((s) => s.scope === "backend/")!;+ // backend has a single, root-level (within the scope) file — same rule a+ // single-scope repo-root file follows: with nothing deeper to group by, the+ // file's own path becomes its group (see `dirKey`'s module doc).+ assert.deepEqual(backend.dirs.map((d) => d.path), ["backend/app.py"]);+ assert.equal(backend.dirs[0].symbols, 1);++ const frontend = map.scopes!.find((s) => s.scope === "frontend/")!;+ // frontend has two sub-dirs (src, lib) — dirs within the scope, sorted by+ // symbol count desc, same rule as single-scope dirs.+ assert.deepEqual(+ frontend.dirs.map((d) => d.path),+ ["frontend/lib", "frontend/src"],+ "frontend's own dirs are grouped and sorted independently of backend's",+ );+ assert.equal(frontend.dirs.find((d) => d.path === "frontend/lib")!.symbols, 2);+ assert.equal(frontend.dirs.find((d) => d.path === "frontend/src")!.symbols, 1);+});++test("buildRepoMap: a root scope alongside named scopes gets its own '(root)' group for files outside any sub-project", () => {+ const nodes = [+ fileNode("README.md"),+ fileNode("frontend/src/a.ts"),+ symNode("frontend/src/a.ts", "one"),+ ];+ // An explicit "" (root) entry alongside "frontend" — two scopes, so this+ // takes the multi-scope path (a lone non-root scope with no "" entry is+ // the single-scope case: same `scopes.length <= 1` convention `ask.ts`+ // uses, since `scopeOf` synthesizes a fallback root for it anyway).+ const scopes: ScopeV1[] = [+ { prefix: "", label: "", markers: [] },+ { prefix: "frontend", label: "frontend", markers: ["package.json"] },+ ];+ const map = buildRepoMap(graphOfWithScopes(nodes, [], scopes));++ assert.deepEqual(map.scopes!.map((s) => s.scope).sort(), ["(root)", "frontend/"]);+ const root = map.scopes!.find((s) => s.scope === "(root)")!;+ assert.deepEqual(root.dirs.map((d) => d.path), ["README.md"]);+});++test("buildRepoMap: the >60% split threshold is evaluated PER SCOPE, not pooled across scopes", () => {+ // backend alone holds 4 files, 3 of which (75%) sit under backend/svc — that+ // must split into backend/svc/a, backend/svc/b even though svc is nowhere+ // near 60% of the WHOLE graph's files (it's 3 of 5 total, i.e. exactly at+ // the single-scope-pooled threshold that wouldn't trip the split at all).+ const nodes = [+ fileNode("backend/svc/a/x.ts"),+ fileNode("backend/svc/b/y.ts"),+ fileNode("backend/svc/c/z.ts"),+ fileNode("backend/other.ts"),+ fileNode("frontend/main.ts"),+ ];+ const scopes: ScopeV1[] = [+ { prefix: "backend", label: "backend", markers: ["go.mod"] },+ { prefix: "frontend", label: "frontend", markers: ["package.json"] },+ ];+ const map = buildRepoMap(graphOfWithScopes(nodes, [], scopes));+ const backend = map.scopes!.find((s) => s.scope === "backend/")!;+ const paths = backend.dirs.map((d) => d.path);+ assert.ok(!paths.includes("backend/svc"), "svc holds 75% of backend's own files — must split");+ assert.ok(paths.includes("backend/svc/a"));+ assert.ok(paths.includes("backend/svc/b"));+ assert.ok(paths.includes("backend/svc/c"));+ assert.ok(paths.includes("backend/other.ts"), "backend's non-svc file is its own group (root-level-in-scope file)");+});++test("buildRepoMap: maxDirs caps each scope's dirs independently, with per-scope dropped counts", () => {+ const nodes: NodeV1[] = [];+ for (const dir of ["backend/a", "backend/b", "backend/c"]) nodes.push(fileNode(`${dir}/x.ts`));+ nodes.push(fileNode("frontend/x.ts"));+ const scopes: ScopeV1[] = [+ { prefix: "backend", label: "backend", markers: ["go.mod"] },+ { prefix: "frontend", label: "frontend", markers: ["package.json"] },+ ];+ const map = buildRepoMap(graphOfWithScopes(nodes, [], scopes), { maxDirs: 1 });+ const backend = map.scopes!.find((s) => s.scope === "backend/")!;+ const frontend = map.scopes!.find((s) => s.scope === "frontend/")!;+ assert.equal(backend.dirs.length, 1);+ assert.equal(backend.dropped, 2, "backend alone has 3 dirs, capped to 1 → 2 dropped");+ assert.equal(frontend.dirs.length, 1);+ assert.equal(frontend.dropped, 0, "frontend only has 1 dir — nothing dropped");+});++test("formatRepoMap: multi-scope renders one '## scope/' heading per scope, dirs nested under it", () => {+ const text = formatRepoMap(buildRepoMap(twoScopeFixture()));+ assert.match(text, /^## backend\/$/m);+ assert.match(text, /^## frontend\/$/m);+ const backendIdx = text.indexOf("## backend/");+ const frontendIdx = text.indexOf("## frontend/");+ const frontendLibIdx = text.indexOf("frontend/lib/", frontendIdx);+ assert.ok(backendIdx < frontendIdx, "scopes render in meta.scopes order");+ assert.ok(frontendIdx < frontendLibIdx, "frontend's own dirs render under its own heading, not backend's");+});+// ── formatRepoMap ────────────────────────────────────────────────────────/** 60-node-ish fixture: a handful of dirs, each with several hub-worthydiff --git a/test/hosts-instructions.test.ts b/test/hosts-instructions.test.tsindex b17b6f08..41bd1281 100644--- a/test/hosts-instructions.test.ts+++ b/test/hosts-instructions.test.ts@@ -13,6 +13,8 @@ test('canonical body names the three essentials', () => {assert.match(b, /truncated/i, 'tells the agent to follow up on truncated spans');assert.match(b, /graft grep/, 'routes sweeps to graft grep');assert.match(b, /graft map/, 'tells the agent to orient with graft map before exploring');+ assert.match(b, /\[scope\/\]/, 'teaches the [scope/] label on multi-scope/monorepo hits');+ assert.match(b, /--in <scope>\//, 'teaches narrowing with ask --in <scope>/');assert.ok(!/\bhook|statusline\b/i.test(b), 'no host-specific machinery in the shared body');});