Skip to content

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

fix(workspace): cross-child participation gate on raw coverage; federated --in narrows by child

Shrish Dwivedi45c8a004b59b
diff --git a/src/cli.ts b/src/cli.ts
index 6ee86eef..9864ce2a 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -187,7 +187,7 @@ program
const askGlobalDir = program.opts<GlobalOpts>().dir;
if (readWorkspace(resolve(dir), askGlobalDir)) {
runWorkspaceAsk(resolve(dir), askGlobalDir, query, {
- limit: Number(opts.limit), source: opts.source, full: opts.full, json: opts.json,
+ limit: Number(opts.limit), source: opts.source, full: opts.full, in: opts.in, json: opts.json,
});
return;
}
diff --git a/src/graph/workspace-cli.ts b/src/graph/workspace-cli.ts
index 8e065126..8c5f20fe 100644
--- a/src/graph/workspace-cli.ts
+++ b/src/graph/workspace-cli.ts
@@ -60,9 +60,9 @@ export function runWorkspaceAsk(
root: string,
override: string | undefined,
query: string,
- opts: { limit?: number; source?: boolean; full?: boolean; json?: boolean },
+ opts: { limit?: number; source?: boolean; full?: boolean; in?: string; json?: boolean },
): void {
- const r = federateAsk(root, override, query, { limit: opts.limit, source: opts.source, full: opts.full });
+ const r = federateAsk(root, override, query, { limit: opts.limit, source: opts.source, full: opts.full, in: opts.in });
if (opts.json) console.log(JSON.stringify(r, null, 2));
else process.stdout.write(formatAsk(r));
}
diff --git a/src/graph/workspace.ts b/src/graph/workspace.ts
index 3a2eda64..8980e01d 100644
--- a/src/graph/workspace.ts
+++ b/src/graph/workspace.ts
@@ -34,7 +34,7 @@ import { edgeWalk, resolveSymbol, type Direction } from "./traverse.js";
import { wiringPath } from "./write.js";
import type { GraphV1 } from "./types.js";
import { ask, type AskHit, type AskResult } from "../ask/ask.js";
-import { fuseScopes, type ScopedDoc } from "../ask/fuse.js";
+import { fuseScopes, PARTICIPATION_RATIO, type ScopedDoc } from "../ask/fuse.js";
import { grepGraph, type GrepGroup, type GrepResult } from "../search/grep.js";
import { formatGrepResult, zeroHitNote } from "../search/grep-cli.js";
import { savingsFooter, type Savings } from "../context/savings.js";
@@ -169,6 +169,17 @@ export interface FederateAskOptions {
source?: boolean;
full?: boolean;
graphRank?: boolean;
+ /** Narrow to one child (`repoA`) or a sub-scope within it (`repoA/backend`).
+ * A prefix matching NO child throws, listing the repos. */
+ in?: string;
+}
+
+interface ChildRun {
+ child: string;
+ hits: AskHit[];
+ /** The child's top-hit idf-weighted matched share — a RAW, cross-child-
+ * comparable magnitude (NOT per-child normalized), used for the gate. */
+ coverage: number;
}
/**
@@ -190,10 +201,26 @@ export function federateAsk(
): AskResult {
const wg = loadWorkspaceGraphs(root, override);
const limit = opts.limit ?? 8;
- const docs: ScopedDoc[] = [];
- const back = new Map<string, { child: string; hit: AskHit }>();
+ // `--in` scopes to a single child (and, past the first segment, a sub-scope
+ // within it). A prefix naming no known child at all is a caller mistake.
+ let onlyChild: string | undefined;
+ let childIn: string | undefined;
+ if (opts.in) {
+ const prefix = opts.in.replace(/\/+$/, "");
+ const [name, ...rest] = prefix.split("/");
+ const allChildren = [...wg.loaded.map((l) => l.child), ...wg.missing].sort();
+ if (!allChildren.includes(name)) {
+ throw new Error(`no workspace repo "${name}" - repos: ${allChildren.join(", ")}`);
+ }
+ onlyChild = name;
+ childIn = rest.length ? rest.join("/") : undefined;
+ }
+
+ // Pass 1: run each child's ask; keep its hits + RAW top-hit coverage.
+ const runs: ChildRun[] = [];
for (const { child } of wg.loaded) {
+ if (onlyChild && child !== onlyChild) continue;
let r: AskResult;
try {
// Over-fetch per child so cross-child fusion has enough candidates to
@@ -203,13 +230,38 @@ export function federateAsk(
source: opts.source,
full: opts.full,
graphRank: opts.graphRank,
+ in: childIn,
});
} catch {
- continue; // a corrupt/odd child never sinks the whole federated query
+ continue; // corrupt child, or a sub-scope --in matching nothing here
}
- r.hits.forEach((hit, i) => {
+ if (r.hits.length === 0) continue;
+ runs.push({ child, hits: r.hits, coverage: r.coverage ?? 0 });
+ }
+
+ // Cross-child participation gate on RAW coverage: per-child scores are each
+ // normalized (top ~1.0 everywhere), which makes fuseScopes's own gate vacuous
+ // across repos. coverage (the top hit's idf-weighted matched share) is NOT
+ // per-child normalized and IS comparable across corpora, so a child below
+ // 0.25x the best is reported in alsoMatched, not fused — this keeps a junk
+ // body-token collision in one repo out of another repo's genuine ranking.
+ const bestCoverage = runs.reduce((m, r) => Math.max(m, r.coverage), 0);
+ const gate = PARTICIPATION_RATIO * bestCoverage;
+ const gatedOut: { scope: string; bestId: string }[] = [];
+ const survivors: ChildRun[] = [];
+ for (const run of runs) {
+ if (run.coverage >= gate) survivors.push(run);
+ else gatedOut.push({ scope: run.child, bestId: prefixPointer(run.child, run.hits[0].pointer) });
+ }
+
+ // Fuse the survivors' scope lists (within-child fusion is left untouched —
+ // each child already ran its own per-scope RRF).
+ const docs: ScopedDoc[] = [];
+ const back = new Map<string, { child: string; hit: AskHit }>();
+ for (const { child, hits } of survivors) {
+ hits.forEach((hit, i) => {
const scope = hit.scope ? `${child}/${hit.scope}` : child;
- const id = `${child}${i}`;
+ const id = `${child} ${i}`;
docs.push({ id, scope, score: hit.score });
back.set(id, { child, hit });
});
@@ -221,19 +273,13 @@ export function federateAsk(
return { ...hit, score: rd.score, scope: rd.scope, pointer: prefixPointer(child, hit.pointer) };
});
+ const alsoMatched = [...fused.alsoMatched, ...gatedOut];
const note = coverageNote(wg);
- const result: AskResult = {
- query,
- mode: hits.length ? "lexical" : "empty",
- hits,
- };
- if (hits.length && (fused.federated.length > 1 || fused.alsoMatched.length > 0)) {
- result.scopes = { federated: fused.federated, alsoMatched: fused.alsoMatched };
- } else if (hits.length) {
- // Single contributing scope still deserves its `<child>/` label.
- result.scopes = { federated: [...new Set(hits.map((h) => h.scope!))], alsoMatched: [] };
- }
- if (!hits.length) {
+ const result: AskResult = { query, mode: hits.length ? "lexical" : "empty", hits };
+ if (hits.length) {
+ const federated = fused.federated.length ? fused.federated : [...new Set(hits.map((h) => h.scope!))];
+ result.scopes = { federated, alsoMatched };
+ } else {
result.note = `no matching nodes across ${wg.loaded.length} workspace repo(s) — try different words, or \`graft build\` at a child`;
}
if (note) result.note = result.note ? `${result.note}\n${note}` : note;
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 8a0162d6..2eee807b 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -158,7 +158,8 @@ function callWorkspaceTool(
const query = String(args.query ?? '');
if (!query) return { text: 'graft_ask requires a query', isError: true };
const limit = typeof args.limit === 'number' ? args.limit : 5;
- const r = federateAsk(root, dirOverride, query, { limit, source: true, full: args.full === true });
+ const inArg = typeof args.in === 'string' && args.in ? args.in : undefined;
+ const r = federateAsk(root, dirOverride, query, { limit, source: true, full: args.full === true, in: inArg });
return { text: formatAsk(r), isError: false };
}
case 'graft_callers': {
diff --git a/test/workspace.test.ts b/test/workspace.test.ts
index d16ac42c..cff762bd 100644
--- a/test/workspace.test.ts
+++ b/test/workspace.test.ts
@@ -188,6 +188,49 @@ test("one unbuilt child is surfaced, not silently skipped", async () => {
rmSync(p, { recursive: true, force: true });
});
+const JUNK = {
+ repoA: { "a.ts": "export function invoiceTotalTaxBreakdown() { return sumLineItems(); }\nfunction sumLineItems() { return 0; }\n" },
+ repoB: { "b.ts": "export function renderPanel() { const total = 0; return total; }\nfunction helper() { return 1; }\n" },
+};
+
+test("federated ask: a junk-body-token child is gated out of the ranking, into alsoMatched", async () => {
+ const p = workspaceFx(JUNK);
+ await buildWorkspace(p);
+ // repoA genuinely matches all query terms (coverage 1.0); repoB matches only
+ // the incidental body token "total" (coverage ~0.19) → below 0.25×best.
+ const r = federateAsk(p, undefined, "invoice total tax breakdown", { limit: 8 });
+ const titles = r.hits.map((h) => h.title);
+ assert.ok(titles.some((t) => t.startsWith("invoiceTotalTaxBreakdown")), "repoA genuine hit federates");
+ assert.ok(!titles.some((t) => t.startsWith("renderPanel")), `junk hit must NOT federate:\n${titles.join("\n")}`);
+ assert.ok(r.hits.every((h) => h.scope!.startsWith("repoA")), "only repoA federates");
+ assert.deepEqual(r.scopes?.alsoMatched.map((m) => m.scope), ["repoB"], "junk child reported in alsoMatched");
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("federated ask: a genuinely-shared query still federates both children", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const r = federateAsk(p, undefined, "handler", { limit: 8 });
+ const scopeSet = new Set(r.hits.map((h) => h.scope!.split("/")[0]));
+ assert.ok(scopeSet.has("repoA") && scopeSet.has("repoB"), "both children federate a shared term");
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("federated ask: --in <child> narrows to that child; --in <unknown> errors listing repos", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const scoped = federateAsk(p, undefined, "handler", { limit: 8, in: "repoA" });
+ assert.ok(scoped.hits.length > 0);
+ assert.ok(scoped.hits.every((h) => h.scope!.startsWith("repoA")), "--in repoA excludes repoB");
+ // trailing slash tolerated, same as single-repo --in
+ assert.ok(federateAsk(p, undefined, "handler", { in: "repoA/" }).hits.every((h) => h.scope!.startsWith("repoA")));
+ assert.throws(
+ () => federateAsk(p, undefined, "handler", { in: "nope" }),
+ /no workspace repo "nope".*repoA.*repoB/s,
+ );
+ rmSync(p, { recursive: true, force: true });
+});
+
test("readWorkspace: rejects foreign/invalid json as not-a-workspace", () => {
const p = mkdtempSync(join(tmpdir(), "ws-"));
mkdirSync(contextDirFor(p), { recursive: true });