Skip to content

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

feat(ask): per-scope ranking with reciprocal-rank fusion — big repos stop drowning small ones

Shrish Dwivedib8b3ca441743
diff --git a/src/ask/ask.ts b/src/ask/ask.ts
index ac6a82b0..e06303b7 100644
--- a/src/ask/ask.ts
+++ b/src/ask/ask.ts
@@ -18,8 +18,10 @@ import { join, resolve } from "node:path";
import matter from "gray-matter";
import { contextDirFor } from "../context/node-file.js";
import { loadGraphCached, loadAskIndexCached } from "../graph/load.js";
+import { scopeOf, scopesOfGraph } from "../graph/scopes.js";
import { resolveSymbol } from "../graph/traverse.js";
import type { EdgeV1, GraphV1, NodeV1, Relation } from "../graph/types.js";
+import { rankScopesAndFuse } from "./fuse.js";
import { personalizedPageRank } from "./graphrank.js";
import { counts, tokenize, type AskIndex, type AskIndexDoc } from "./index-file.js";
@@ -36,6 +38,10 @@ export interface AskHit {
* This is what makes `ask` substitutive — the agent reads the span here
* instead of opening the file, so no source read happens on top of the query. */
code?: string;
+ /** Multi-scope repos only: the ranking scope (path prefix, "" = root) this
+ * hit was ranked within — answers "which sub-project is this from?". Drives
+ * the `[scope/] ` label in formatAsk. Absent on single-scope repos. */
+ scope?: string;
}
/** Max source lines to inline per hit — a definition longer than this is
@@ -59,6 +65,11 @@ export interface AskResult {
* best result, i.e. the pack is probably noise for this prompt. Absent in
* structural mode — a resolved "who calls X" is itself the relevance signal. */
coverage?: number;
+ /** Multi-scope lexical results only: which scopes federated into the fused
+ * ranking, plus scopes that matched too weakly to federate (with their best
+ * doc id). Drives formatAsk's `matched in:` / `also matched:` footer.
+ * Absent on single-scope repos — zero output change there. */
+ scopes?: { federated: string[]; alsoMatched: { scope: string; bestId: string }[] };
}
/** First real prose line of a node body (skips headings, markers, blanks). */
@@ -418,6 +429,86 @@ function lexical(query: string, corpus: Corpus, limit: number, graphRank: boolea
for (const v of m.values()) s += v;
return s;
};
+ const docsById = new Map(symbolDocs.map((d) => [d.n.id, d]));
+ const symbolHits: AskHit[] = [];
+ // The single-vs-multi-scope branch keys on `scopesOfGraph` ONLY: one scope
+ // (or no graph) takes the existing path below completely untouched — that
+ // branch is a byte-level regression guarantee for single-scope repos.
+ const scopes = graph ? scopesOfGraph(graph) : null;
+ let scopeMeta: AskResult["scopes"];
+ if (scopes && scopes.length > 1) {
+ // ── Multi-scope repo: rank each sub-project against its OWN corpus (its
+ // IDF, its BM25 length prior, its subgraph walk), then fuse the per-scope
+ // orderings by reciprocal rank — the big scope can't drown the small one.
+ // Same scoring functions and blend as the single-scope path, just fed
+ // per-scope inputs; the fusion itself lives in fuse.ts. ──
+ const byScope = new Map<string, typeof symbolDocs>();
+ for (const d of symbolDocs) {
+ const s = scopeOf(d.n.path, scopes).prefix;
+ const list = byScope.get(s);
+ if (list) list.push(d);
+ else byScope.set(s, [d]);
+ }
+ const idfOf = new Map<string, { idf: Map<string, number>; dflt: number }>();
+ const fusion = rankScopesAndFuse(
+ [...byScope.keys()].sort(),
+ {
+ lex: (s) => {
+ const docs = byScope.get(s)!;
+ // Per-scope IDF/BM25 stats: concepts are repo-level so their bags
+ // fold in everywhere, symbol bags come from this scope only. (The
+ // build sidecar's df/avgBodyLen are corpus-global, so multi-scope
+ // always computes these live — from the sidecar's own token maps.)
+ const sIdf = computeIdf([
+ ...conceptBags,
+ ...docs.map((d) => new Set([...d.name.keys(), ...d.path.keys(), ...d.body.keys()])),
+ ]);
+ idfOf.set(s, { idf: sIdf, dflt: Math.log(1 + conceptBags.length + docs.length) });
+ const avg = docs.reduce((a, d) => a + bodyLen(d.body), 0) / docs.length;
+ const out = new Map<string, number>();
+ for (const { n, name, path, body } of docs) {
+ const total =
+ score(q, name, sIdf) * 3 +
+ score(q, path, sIdf) * 2 +
+ bm25(q, body, sIdf, bodyLen(body), avg);
+ if (total > 0) out.set(n.id, total);
+ }
+ return out;
+ },
+ walk: (s, seeds) =>
+ graphRank
+ ? personalizedPageRank(graph!, seeds, {
+ nodeFilter: (id) => scopeOf(byId.get(id)?.path ?? "", scopes).prefix === s,
+ })
+ : new Map<string, number>(),
+ },
+ GRAPH_WEIGHT,
+ RESCUE_FLOOR,
+ );
+ for (const rd of fusion.ranked) {
+ const n = byId.get(rd.id);
+ if (!n) continue;
+ const hit: AskHit = {
+ kind: "symbol",
+ title: `${n.name} · ${n.kind}`,
+ pointer: n.kind === "file" ? n.path : `${n.path}:${n.span}`,
+ snippet: n.summary?.split("\n")[0].trim() ?? n.signature ?? "",
+ score: rd.score,
+ scope: rd.scope,
+ };
+ const d = docsById.get(rd.id);
+ const si = idfOf.get(rd.scope);
+ matchedOf.set(hit, d && si ? matchedIdfShare(q, [d.name, d.path, d.body], si.idf, si.dflt) : 0);
+ symbolHits.push(hit);
+ }
+ // Label + footer only when federation actually happened (or a scope was
+ // gated out and is worth mentioning) — a query matching one scope of a
+ // multi-scope repo reads exactly like today.
+ if (fusion.federated.length > 1 || fusion.alsoMatched.length > 0)
+ scopeMeta = { federated: fusion.federated, alsoMatched: fusion.alsoMatched };
+ } else {
+ // Single-scope: the pre-scopes ranking path, byte-identical output. Kept at
+ // its original indentation on purpose — the git diff proves it untouched.
const avgBodyLen = askIndex
? askIndex.avgBodyLen
: symbolDocs.length
@@ -448,8 +539,6 @@ function lexical(query: string, corpus: Corpus, limit: number, graphRank: boolea
const candidates = new Set<string>(lex.keys());
for (const [id, p] of pr) if (p >= RESCUE_FLOOR) candidates.add(id);
- const docsById = new Map(symbolDocs.map((d) => [d.n.id, d]));
- const symbolHits: AskHit[] = [];
for (const id of candidates) {
const n = byId.get(id);
if (!n) continue;
@@ -469,6 +558,7 @@ function lexical(query: string, corpus: Corpus, limit: number, graphRank: boolea
matchedOf.set(hit, d ? matchedIdfShare(q, [d.name, d.path, d.body], idf, dfltIdf) : 0);
symbolHits.push(hit);
}
+ }
// Concepts and symbols live on comparable 0..~1.5 scales so they merge fairly:
// concept scores are normalized to their own max, symbol scores are the
@@ -481,6 +571,7 @@ function lexical(query: string, corpus: Corpus, limit: number, graphRank: boolea
query,
mode: scored.length ? "lexical" : "empty",
hits: scored.slice(0, limit),
+ scopes: scopeMeta,
coverage: scored.length && q.size > 0 ? matchedOf.get(scored[0]) ?? 0 : undefined,
note: scored.length ? undefined : "no matching nodes — try different words, or `graft build` if graft/ is empty",
};
@@ -718,13 +809,17 @@ export function formatAsk(r: AskResult): string {
}
} else {
r.hits.forEach((h, i) => {
- lines.push(`${i + 1}. ${h.title} [${h.kind}]`);
+ // Multi-scope results label each hit with its sub-project (root scope
+ // "" stays unlabeled) so a reviewer can tell WHICH codebase answered.
+ const label = r.scopes && h.scope ? `[${h.scope}/] ` : "";
+ lines.push(`${i + 1}. ${label}${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(", ")}`);
if (h.code) lines.push("", "```", h.code, "```");
lines.push("");
});
+ lines.push(...scopeFooterLines(r));
}
const body = lines.join("\n").trimEnd();
return body + savingsFooter(r, body) + "\n";
@@ -746,3 +841,23 @@ function savingsFooter(r: AskResult, body: string): string {
`${base.toLocaleString()} tok. Estimate (baseline = those files read in full).`
);
}
+
+/** Multi-scope footer: answers a reviewer's two questions — "which
+ * sub-projects did this pack come from?" (`matched in:`, displayed-hit counts,
+ * biggest first) and "did anything else match that I should know about?"
+ * (`also matched:` for scopes gated out of fusion, with the flag to narrow).
+ * Empty (zero output) whenever the result isn't a federated multi-scope one. */
+function scopeFooterLines(r: AskResult): string[] {
+ if (!r.scopes) return [];
+ const label = (s: string) => (s === "" ? "(root)" : `${s}/`);
+ const perScope = new Map<string, number>();
+ for (const h of r.hits)
+ if (h.scope !== undefined) perScope.set(h.scope, (perScope.get(h.scope) ?? 0) + 1);
+ const parts = [...perScope]
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
+ .map(([s, c]) => `${label(s)} (${c})`);
+ const out = parts.length ? [`matched in: ${parts.join(" · ")}`] : [];
+ for (const m of r.scopes.alsoMatched)
+ out.push(`also matched: ${label(m.scope)} — narrow with --in ${label(m.scope)}`);
+ return out;
+}
diff --git a/src/ask/fuse.ts b/src/ask/fuse.ts
new file mode 100644
index 00000000..e2d3dea7
--- /dev/null
+++ b/src/ask/fuse.ts
@@ -0,0 +1,172 @@
+/**
+ * Scope-aware ranking for `graft ask` — per-scope ranking + reciprocal-rank
+ * fusion (RRF). Pure functions, no fs.
+ *
+ * The problem: lexical + graph scores are corpus-relative. In a multi-scope
+ * repo (a monorepo's `frontend/` + `backend/`, sub-projects under one root),
+ * pooling every node into one ranking lets the biggest sub-project set the
+ * score scale and drown the small one — its IDF, its BM25 length prior, its
+ * PageRank mass. The fix: rank each scope against ITS OWN corpus (per-scope
+ * IDF/BM25/walk, done by the caller), then fuse the per-scope ORDERINGS here
+ * with RRF — rank positions are comparable across corpora where raw scores
+ * are not, so the tiny scope's best hit lands next to the huge scope's best.
+ *
+ * Soft federation: a scope whose best score is far below the global best
+ * (< {@link PARTICIPATION_RATIO} ×) is probably an incidental word collision,
+ * not a second home for the query — it is left out of the fused order and
+ * reported in `alsoMatched` instead, so the output can say "also matched:
+ * docs/ — narrow with --in docs/" rather than diluting the pack.
+ */
+
+/** One scored document, attributed to the ranking scope (path prefix, "" =
+ * root) it was scored within. Scores must be per-scope-normalized (each
+ * scope's best ≈ its own ceiling) — fusion compares ranks, not raw scores. */
+export interface ScopedDoc {
+ id: string;
+ scope: string;
+ score: number;
+}
+
+export interface FusionResult {
+ /** fused order, best first; carries per-doc scope label + fused score in [0,1] */
+ ranked: { id: string; scope: string; score: number }[];
+ /** scopes that participated in fusion */
+ federated: string[];
+ /** scopes that matched weakly (≥1 scoring doc but below the participation gate) with their best doc */
+ alsoMatched: { scope: string; bestId: string }[];
+}
+
+/** RRF smoothing constant — the standard value from the original RRF paper;
+ * high enough that rank 1 vs 2 differ gently rather than by 2×. */
+export const RRF_K = 60;
+
+/** A scope federates only when its best doc scores at least this share of the
+ * global best — below it the match is reported, not fused. */
+export const PARTICIPATION_RATIO = 0.25;
+
+/** Score-desc, id-asc ordering — the id tiebreak is what makes fusion
+ * deterministic under input shuffle. */
+function byScore(a: ScopedDoc, b: ScopedDoc): number {
+ return b.score - a.score || a.id.localeCompare(b.id);
+}
+
+/**
+ * Partition by scope, rank within scope (input scores are already
+ * per-scope-normalized), gate by soft federation, fuse by RRF:
+ * `fused(id) = Σ 1/(K + rank_in_scope(id))`, then normalized so the top fused
+ * doc is 1. Non-scoring docs (score ≤ 0) are dropped entirely.
+ *
+ * Degenerate cases degrade to current behavior: zero scoring docs → empty
+ * result; exactly one scoring scope → its docs pass through in score order
+ * with their ORIGINAL scores (no RRF re-scoring, no gate) — byte-for-byte the
+ * single-corpus ranking the caller would have produced anyway.
+ */
+export function fuseScopes(docs: ScopedDoc[]): FusionResult {
+ const byScope = new Map<string, ScopedDoc[]>();
+ for (const d of docs) {
+ if (d.score <= 0) continue;
+ const list = byScope.get(d.scope);
+ if (list) list.push(d);
+ else byScope.set(d.scope, [d]);
+ }
+ for (const list of byScope.values()) list.sort(byScore);
+
+ if (byScope.size === 0) return { ranked: [], federated: [], alsoMatched: [] };
+ if (byScope.size === 1) {
+ const [scope, list] = byScope.entries().next().value as [string, ScopedDoc[]];
+ return {
+ ranked: list.map((d) => ({ id: d.id, scope, score: d.score })),
+ federated: [scope],
+ alsoMatched: [],
+ };
+ }
+
+ // Gate: order scopes by their best doc (desc, scope-name tiebreak), split
+ // into federated (≥ ratio × global best, inclusive) and alsoMatched.
+ const scopesByBest = [...byScope.entries()].sort(
+ (a, b) => b[1][0].score - a[1][0].score || a[0].localeCompare(b[0]),
+ );
+ const gate = PARTICIPATION_RATIO * scopesByBest[0][1][0].score;
+ const federated: string[] = [];
+ const alsoMatched: FusionResult["alsoMatched"] = [];
+ for (const [scope, list] of scopesByBest) {
+ if (list[0].score >= gate) federated.push(scope);
+ else alsoMatched.push({ scope, bestId: list[0].id });
+ }
+
+ // RRF: each federated scope contributes 1/(K + rank) per doc; an id listed
+ // in more than one scope sums its contributions and is attributed to the
+ // scope where it ranked best.
+ const acc = new Map<string, { scope: string; score: number; bestRank: number }>();
+ for (const scope of federated) {
+ byScope.get(scope)!.forEach((d, i) => {
+ const contribution = 1 / (RRF_K + i + 1);
+ const prev = acc.get(d.id);
+ if (!prev) acc.set(d.id, { scope, score: contribution, bestRank: i });
+ else {
+ prev.score += contribution;
+ if (i < prev.bestRank) {
+ prev.scope = scope;
+ prev.bestRank = i;
+ }
+ }
+ });
+ }
+
+ let max = 0;
+ for (const e of acc.values()) if (e.score > max) max = e.score;
+ const ranked = [...acc.entries()].map(([id, e]) => ({
+ id,
+ scope: e.scope,
+ score: e.score / max,
+ }));
+ ranked.sort(
+ (a, b) => b.score - a.score || a.scope.localeCompare(b.scope) || a.id.localeCompare(b.id),
+ );
+ return { ranked, federated, alsoMatched };
+}
+
+/** The per-scope scoring hooks `rankScopesAndFuse` drives — the caller owns
+ * the actual lexical math and graph walk (they need its corpus state); this
+ * module owns the orchestration so the shape of "rank per scope, then fuse"
+ * lives in one place. */
+export interface ScopeRankOps {
+ /** Lexical scores for the scope's own docs (positive entries only),
+ * computed against the scope's OWN corpus statistics. */
+ lex(scope: string): Map<string, number>;
+ /** Graph walk restricted to the scope's subgraph, seeded by that scope's
+ * lexical scores; returns top-normalized centrality (or an empty map). */
+ walk(scope: string, seeds: Map<string, number>): Map<string, number>;
+}
+
+/**
+ * Multi-scope orchestration for `ask`'s symbol ranking: for each scope, score
+ * lexically, walk the scope's subgraph, blend exactly like the single-scope
+ * path (`lexN + graphWeight·pr`, both per-scope-normalized; walk-rescued
+ * nodes join above `rescueFloor`), then fuse all scopes' blended lists with
+ * {@link fuseScopes}. A scope with zero lexical matches contributes nothing
+ * (no seeds → no walk → no docs).
+ */
+export function rankScopesAndFuse(
+ scopes: string[],
+ ops: ScopeRankOps,
+ graphWeight: number,
+ rescueFloor: number,
+): FusionResult {
+ const scoped: ScopedDoc[] = [];
+ for (const scope of scopes) {
+ const lex = ops.lex(scope);
+ if (lex.size === 0) continue;
+ const pr = ops.walk(scope, lex);
+ let maxLex = 0;
+ for (const v of lex.values()) if (v > maxLex) maxLex = v;
+ const candidates = new Set(lex.keys());
+ for (const [id, p] of pr) if (p >= rescueFloor) candidates.add(id);
+ for (const id of candidates) {
+ const lexN = maxLex > 0 ? (lex.get(id) ?? 0) / maxLex : 0;
+ const blended = lexN + graphWeight * (pr.get(id) ?? 0);
+ if (blended > 0) scoped.push({ id, scope, score: blended });
+ }
+ }
+ return fuseScopes(scoped);
+}
diff --git a/test/ask-fusion.test.ts b/test/ask-fusion.test.ts
new file mode 100644
index 00000000..8bfd40a8
--- /dev/null
+++ b/test/ask-fusion.test.ts
@@ -0,0 +1,97 @@
+/**
+ * Pure tests for `fuseScopes` (src/ask/fuse.ts) — per-scope ranking +
+ * reciprocal-rank fusion. No fs, no graph build: these pin the fusion math
+ * that keeps a big sub-project from drowning a small one in `graft ask`.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { fuseScopes, RRF_K, PARTICIPATION_RATIO, type ScopedDoc } from "../src/ask/fuse.js";
+
+/** A scope's docs with per-scope-normalized-looking scores, best first. */
+function scopeDocs(scope: string, scores: number[]): ScopedDoc[] {
+ return scores.map((score, i) => ({ id: `${scope}${i + 1}`, scope, score }));
+}
+
+test("fusion constants match the spec", () => {
+ assert.equal(RRF_K, 60);
+ assert.equal(PARTICIPATION_RATIO, 0.25);
+});
+
+test("10-doc scope vs 2-doc scope: top-6 of the fused order contains both scopes' best", () => {
+ const huge = scopeDocs("h", [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]);
+ const tiny = scopeDocs("t", [1.0, 0.4]);
+ const { ranked, federated } = fuseScopes([...huge, ...tiny]);
+ const top6 = ranked.slice(0, 6).map((d) => d.id);
+ assert.ok(top6.includes("h1"), `huge scope's best in top-6, got ${top6}`);
+ assert.ok(top6.includes("t1"), `tiny scope's best in top-6, got ${top6}`);
+ assert.deepEqual([...federated].sort(), ["h", "t"], "both scopes federated");
+});
+
+test("rank-1 of the tiny scope fuses equal to rank-1 of the huge scope, by construction", () => {
+ const { ranked } = fuseScopes([
+ ...scopeDocs("huge", [1.0, 0.9, 0.8, 0.7, 0.6, 0.5]),
+ ...scopeDocs("tiny", [0.9]),
+ ]);
+ const byId = new Map(ranked.map((d) => [d.id, d.score]));
+ assert.equal(byId.get("huge1"), byId.get("tiny1"), "equal fused score for both rank-1 docs");
+ assert.equal(byId.get("huge1"), 1, "fused scores are normalized to [0,1], top = 1");
+ assert.ok(byId.get("huge2")! < 1, "rank-2 fuses strictly below rank-1");
+});
+
+test("participation gate: a scope whose best is < 0.25 × global best is excluded but reported in alsoMatched", () => {
+ const strong = scopeDocs("a", [1.0, 0.5, 0.3]);
+ const weak = scopeDocs("b", [0.2, 0.1]); // 0.2 < 0.25 × 1.0
+ const r = fuseScopes([...strong, ...weak]);
+ assert.deepEqual(r.federated, ["a"]);
+ assert.deepEqual(r.alsoMatched, [{ scope: "b", bestId: "b1" }]);
+ assert.ok(r.ranked.every((d) => d.scope === "a"), "gated scope's docs are not in the fused order");
+});
+
+test("a scope at exactly the gate participates (gate is inclusive)", () => {
+ const r = fuseScopes([...scopeDocs("a", [1.0]), ...scopeDocs("b", [0.25])]);
+ assert.deepEqual([...r.federated].sort(), ["a", "b"]);
+ assert.deepEqual(r.alsoMatched, []);
+});
+
+test("single-scope input returns the docs unchanged in order, with their original scores", () => {
+ const docs = scopeDocs("only", [1.4, 0.9, 0.2, 0.05]); // below-gate scores stay too: no gate with one scope
+ const r = fuseScopes(docs);
+ assert.deepEqual(
+ r.ranked,
+ docs.map((d) => ({ id: d.id, scope: "only", score: d.score })),
+ "order and scores pass through untouched — degrades to current single-scope behavior",
+ );
+ assert.deepEqual(r.federated, ["only"]);
+ assert.deepEqual(r.alsoMatched, []);
+});
+
+test("non-scoring docs (score <= 0) never rank, federate, or report", () => {
+ const r = fuseScopes([
+ ...scopeDocs("a", [1.0, 0.6]),
+ { id: "z1", scope: "z", score: 0 },
+ { id: "z2", scope: "z", score: -1 },
+ ]);
+ assert.deepEqual(r.federated, ["a"]);
+ assert.deepEqual(r.alsoMatched, []);
+ assert.ok(r.ranked.every((d) => d.scope === "a"));
+});
+
+test("empty input fuses to an empty result", () => {
+ assert.deepEqual(fuseScopes([]), { ranked: [], federated: [], alsoMatched: [] });
+});
+
+test("deterministic under input shuffle, including score ties", () => {
+ const docs: ScopedDoc[] = [
+ ...scopeDocs("api", [1.0, 0.8, 0.8, 0.3]), // tie inside a scope
+ ...scopeDocs("web", [1.0, 0.5]),
+ ...scopeDocs("docs", [0.1]), // gated out — must still be reported identically
+ ];
+ const baseline = fuseScopes(docs);
+ const shuffles = [
+ [...docs].reverse(),
+ [docs[3], docs[6], docs[0], docs[5], docs[2], docs[1], docs[4]],
+ ];
+ for (const shuffled of shuffles) {
+ assert.deepEqual(fuseScopes(shuffled), baseline, "same result regardless of input order");
+ }
+});
diff --git a/test/ask.test.ts b/test/ask.test.ts
index 1f318bdc..a37171d7 100644
--- a/test/ask.test.ts
+++ b/test/ask.test.ts
@@ -6,7 +6,7 @@
*/
import { test } from "node:test";
import assert from "node:assert/strict";
-import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { readFileSync } from "node:fs";
@@ -266,6 +266,91 @@ test("formatAsk: the structural fallthrough note prints prominently, before any
}
});
+// ── Scope-aware ranking: per-scope rank + RRF fusion (multi-scope repos) ────
+
+/** Two sub-projects under one root: `frontend/` (ts, ~6 symbols) and
+ * `backend/` (py, ~30 symbols — 5× bigger), each with its own project marker
+ * so scope discovery splits them, and each with error-handling symbols so a
+ * "how are errors handled" query matches in BOTH scopes. Without fusion the
+ * backend's sheer size drowns the frontend's hits. */
+function multiScopeFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-ask-scopes-"));
+ mkdirSync(join(dir, "frontend", "src"), { recursive: true });
+ mkdirSync(join(dir, "backend"), { recursive: true });
+ writeFileSync(join(dir, "frontend", "package.json"), "{}\n");
+ writeFileSync(join(dir, "backend", "pyproject.toml"), `[project]\nname = "backend"\n`);
+ writeFileSync(
+ join(dir, "frontend", "src", "errors.ts"),
+ `export function handleErrors(err: Error): string {\n` +
+ ` // errors from the ui are handled with a banner\n` +
+ ` return renderBanner(err.message);\n` +
+ `}\n\n` +
+ `export function renderBanner(msg: string): string {\n` +
+ ` return "banner: " + msg;\n` +
+ `}\n\n` +
+ `export function reportErrors(err: Error): string {\n` +
+ ` // handled errors are also reported upstream\n` +
+ ` return handleErrors(err);\n` +
+ `}\n\n` +
+ `export function clearBanner(): string {\n return "";\n}\n\n` +
+ `export function bannerVisible(): boolean {\n return false;\n}\n\n` +
+ `export function resetUi(): string {\n return "reset";\n}\n`,
+ );
+ let py =
+ `def handle_errors(exc):\n` +
+ ` """errors are handled by returning a serialized problem response"""\n` +
+ ` return {"error": str(exc)}\n\n\n` +
+ `def wrap_errors(fn):\n` +
+ ` """errors raised by route handlers get handled and logged here"""\n` +
+ ` return fn\n\n\n`;
+ for (let i = 0; i < 28; i++) py += `def route_${i}(payload):\n return payload\n\n\n`;
+ writeFileSync(join(dir, "backend", "app.py"), py);
+ return dir;
+}
+
+test("ask on a multi-scope repo: top hits federate both scopes, labeled, with a matched-in footer", async () => {
+ const dir = multiScopeFixture();
+ try {
+ await buildGraph(dir);
+ const r = ask(dir, "how are errors handled", { limit: 10 });
+ const scopesHit = new Set(r.hits.map((h) => h.scope));
+ assert.ok(scopesHit.has("frontend"), "top-10 contains a frontend/ hit despite backend being 5× bigger");
+ assert.ok(scopesHit.has("backend"), "top-10 contains a backend/ hit");
+ assert.ok(r.scopes, "multi-scope result carries fusion telemetry");
+ const out = formatAsk(r);
+ assert.match(out, /\[frontend\/\] /, "frontend hits carry a scope label");
+ assert.match(out, /\[backend\/\] /, "backend hits carry a scope label");
+ assert.match(out, /matched in: .*frontend\/ \(\d+\)/, "footer reports frontend's hit count");
+ assert.match(out, /matched in: .*backend\/ \(\d+\)/, "footer reports backend's hit count");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+/** The regression pin Task 7's cross-version gate relies on: on a single-scope
+ * graph the fusion code paths must be completely inert. `meta.scopes` hand-set
+ * to the canonical single form vs deleted (an old graph) must produce
+ * byte-identical `formatAsk` output — the early branch keys on
+ * `scopesOfGraph(graph).length <= 1`, and both forms take it. */
+test("regression pin: single-scope ask output is byte-equal with canonical meta.scopes vs no meta.scopes", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const p = join(dir, "graft", ".graph", "wiring.json");
+ const g = JSON.parse(readFileSync(p, "utf8"));
+ delete g.meta.scopes;
+ writeFileSync(p, JSON.stringify(g));
+ const absent = formatAsk(ask(dir, "addNumbers", { source: true }));
+ g.meta.scopes = [{ prefix: "", label: "", markers: [] }];
+ writeFileSync(p, JSON.stringify(g));
+ const canonical = formatAsk(ask(dir, "addNumbers", { source: true }));
+ assert.equal(canonical, absent, "single-scope output must not drift by a byte");
+ assert.doesNotMatch(absent, /matched in:|also matched:|\[\w+\/\] /, "zero new output on single-scope");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test("ask with source inlines the actual span from disk", async () => {
const dir = makeFixture();
try {