Skip to content

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

feat(workspace): multi-repo parents federate per-child graphs — auto-split replaces mega-graphs

Shrish Dwivedidf64981b6c8f
diff --git a/src/cli.ts b/src/cli.ts
index 3ae14a4d..6ee86eef 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1,20 +1,8 @@
#!/usr/bin/env node
/**
- * `graft` CLI. Commands:
- *
- * build build graft/ from your code (structural graph; --deep adds LLM summaries).
- * ask query the graph ($0, no LLM).
- * check fail if graft/ has drifted from the code — for CI.
- * viz serve the interactive graph viewer.
- * mcp serve the graph over MCP (stdio) for coding agents.
- * callers precise graph traversal for a symbol ($0, no LLM); --direction out = callees, --depth N = blast radius.
- * skeleton signatures-only view of one file ($0, no LLM).
- * grep regex search over indexed files, grouped by enclosing symbol, ranked by coupling ($0, no LLM).
- * map token-budgeted repo orientation — dir clusters, hubs, hotspots ($0, no LLM).
- * init set up the Claude Code integration (.claude/ statusline + hooks + MCP) in this repo.
- *
- * Git is the sync: commit graft/ and anyone who clones the repo has the
- * graph, with no setup.
+ * `graft` CLI. Commands: build, ask, check, viz, mcp, callers, skeleton, grep,
+ * map, init. Git is the sync: commit graft/ and a clone has the graph. A
+ * workspace parent (≥2 git children) federates query commands across children.
*/
import "dotenv/config";
import { Command } from "commander";
@@ -30,6 +18,15 @@ import { runHostsInit } from "./hosts/init.js";
import { hostIds } from "./hosts/registry.js";
import { contextDirFor } from "./context/node-file.js";
import { loadGraphCached } from "./graph/load.js";
+import { isWorkspaceBuildRoot, readWorkspace } from "./graph/workspace.js";
+import {
+ runWorkspaceAsk,
+ runWorkspaceBuild,
+ runWorkspaceCallers,
+ runWorkspaceCheck,
+ runWorkspaceGrep,
+ runWorkspaceMap,
+} from "./graph/workspace-cli.js";
import { formatInitEpilogue } from "./cli-epilogue.js";
import { formatUpgradeReport, formatVersionReport, getNpmViewVersion, readCurrentVersion, runUpgrade } from "./cli-meta.js";
@@ -66,10 +63,7 @@ function cliConfig(): EngineConfig {
};
}
-function engineFrom(): Graft {
- return new Graft(cliConfig());
-}
-
+const engineFrom = (): Graft => new Graft(cliConfig());
program
.command("version")
.description("Print the installed version and the latest published on npm")
@@ -110,8 +104,7 @@ program
.map(([k, n]) => `${n} ${k}`)
.join(", ");
- // --deep needs a key; without one, degrade to the $0 structural build
- // rather than failing — the wiring graph is still worth having.
+ // --deep needs a key; without one, degrade to the $0 structural build.
let deep = opts.deep;
const resolved = resolveConfig(cliConfig());
if (deep && !resolved.apiKey) {
@@ -128,8 +121,21 @@ program
);
}
- // --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.
+ // Workspace parent: build each child into its OWN graft/ + a workspace index.
+ const buildRoot = resolve(dir);
+ const buildGlobalDir = program.opts<GlobalOpts>().dir;
+ if (isWorkspaceBuildRoot(buildRoot, buildGlobalDir)) {
+ await runWorkspaceBuild(buildRoot, {
+ deep: !!deep,
+ extensions: opts.extensions,
+ concurrency,
+ childConfig: cliConfig(),
+ override: buildGlobalDir,
+ });
+ return;
+ }
+
+ // --deep: concept nodes first, then the wiring graph links cards up to them.
if (deep) {
const c = await engine.init(dir, {
extensions: opts.extensions,
@@ -145,7 +151,7 @@ program
for (const e of c.errors) console.error(`✗ ${e}`);
}
- // Wiring graph (Tier-2 cards + Tier-3 wiring.json) — always. LLM meaning only with --deep.
+ // Wiring graph — always; LLM meaning only with --deep.
const g = await engine.graph(dir, {
llm: deep,
concurrency,
@@ -178,6 +184,13 @@ program
.option("--in <path>", "narrow to nodes under this path prefix, filtered before scoring (segment-aware, like scopeOf)")
.option("--json", "output the result as JSON")
.action(async (query: string, dir: string, opts: { limit: string; source?: boolean; full?: boolean; in?: string; json?: boolean }) => {
+ 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,
+ });
+ return;
+ }
const engine = engineFrom();
let r;
try {
@@ -216,15 +229,18 @@ program
.option("-e, --extensions <exts...>", "code extensions to include")
.option("--json", "output the drift as JSON")
.action((dir: string, opts: { extensions?: string[]; json?: boolean }) => {
+ const checkGlobalDir = program.opts<GlobalOpts>().dir;
+ if (readWorkspace(resolve(dir), checkGlobalDir)) {
+ runWorkspaceCheck(resolve(dir), checkGlobalDir);
+ return;
+ }
const engine = engineFrom();
const r = engine.check(dir, { extensions: opts.extensions });
const g = engine.checkGraph(dir); // graph.json is only judged when it exists
- // Neither layer has ever been built → nothing to check.
+ // A layer that IS present must be in sync; a never-built layer (keyless
+ // build skips the markdown layer) is informational, not a failure.
const bothMissing = r.missing && g.missing;
- // A layer that IS present must be in sync; a layer that was never built
- // (keyless `graft build` skips the markdown/concept layer) is informational,
- // not a failure — the wiring graph stands on its own.
const markdownFail = !r.missing && !r.ok;
const wiringFail = !g.missing && !g.ok;
@@ -267,8 +283,7 @@ program
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)
- const viewerDir = fileURLToPath(new URL("./viewer/", import.meta.url));
+ const viewerDir = fileURLToPath(new URL("./viewer/", import.meta.url)); // prebuilt
const srv = await startVizServer({
contextDir,
viewerDir,
@@ -310,8 +325,16 @@ program
dir: string,
opts: { direction?: string; depth?: string; in?: string; json?: boolean },
) => {
- const { runCallersCommand } = await import("./graph/traverse-cli.js");
const globalOpts = program.opts<{ dir?: string }>();
+ if (!opts.json && readWorkspace(resolve(dir), globalOpts.dir)) {
+ runWorkspaceCallers(resolve(dir), globalOpts.dir, symbol, {
+ direction: opts.direction === "out" ? "out" : "in",
+ depth: opts.depth ? Number(opts.depth) : undefined,
+ in: opts.in,
+ });
+ return;
+ }
+ const { runCallersCommand } = await import("./graph/traverse-cli.js");
runCallersCommand(symbol, dir, {
direction: opts.direction,
depth: opts.depth,
@@ -337,8 +360,14 @@ program
dir: string,
opts: { ignoreCase?: boolean; fixed?: boolean; in?: string; json?: boolean },
) => {
- const { runGrepCommand } = await import("./search/grep-cli.js");
const globalOpts = program.opts<{ dir?: string }>();
+ if (readWorkspace(resolve(dir), globalOpts.dir)) {
+ runWorkspaceGrep(resolve(dir), globalOpts.dir, pattern, {
+ ignoreCase: opts.ignoreCase, fixed: opts.fixed, json: opts.json,
+ });
+ return;
+ }
+ const { runGrepCommand } = await import("./search/grep-cli.js");
runGrepCommand(pattern, dir, {
ignoreCase: opts.ignoreCase,
fixed: opts.fixed,
@@ -358,17 +387,9 @@ program
.option("--max-dirs <n>", "max directory entries shown, rest counted into dropped (default 16)")
.option("--json", "output as JSON")
.action(async (dir: string, opts: { json?: boolean; maxDirs?: string }) => {
- const { buildRepoMap, formatRepoMap } = await import("./graph/map.js");
const root = resolve(dir);
const globalOpts = program.opts<{ dir?: string }>();
- const contextDir = contextDirFor(root, globalOpts.dir);
- const graph = loadGraphCached(contextDir);
- if (!graph) {
- console.error("✗ no graph — run graft build first");
- process.exit(1);
- return;
- }
- let maxDirs: number | undefined;
+ let maxDirsW: number | undefined;
if (opts.maxDirs !== undefined) {
const n = parseInt(opts.maxDirs, 10);
if (!Number.isFinite(n) || n <= 0) {
@@ -376,9 +397,21 @@ program
process.exit(1);
return;
}
- maxDirs = n;
+ maxDirsW = n;
+ }
+ if (!opts.json && readWorkspace(root, globalOpts.dir)) {
+ runWorkspaceMap(root, globalOpts.dir, { maxDirs: maxDirsW });
+ return;
+ }
+ const { buildRepoMap, formatRepoMap } = await import("./graph/map.js");
+ const contextDir = contextDirFor(root, globalOpts.dir);
+ const graph = loadGraphCached(contextDir);
+ if (!graph) {
+ console.error("✗ no graph — run graft build first");
+ process.exit(1);
+ return;
}
- const map = buildRepoMap(graph, { maxDirs });
+ const map = buildRepoMap(graph, { maxDirs: maxDirsW });
if (opts.json) {
console.log(JSON.stringify(map, null, 2));
return;
@@ -443,7 +476,6 @@ program
for (const w of r.written) console.error(`✓ ${w.id}: ${w.path} (${w.action})`);
if (!explicit && !opts.allAgents && r.written.length === 0)
console.error("· no other agents detected (see --list-agents / --all-agents)");
- // r.unknown is always empty here — ids are validated above, before any writes.
for (const m of r.mcp) console.error(`✓ mcp ${m.id}: ${m.path} (${m.action})`);
for (const h of r.hooks) console.error(`✓ hook ${h.id}: ${h.path} (${h.action})`);
}
diff --git a/src/graph/workspace-cli.ts b/src/graph/workspace-cli.ts
new file mode 100644
index 00000000..8e065126
--- /dev/null
+++ b/src/graph/workspace-cli.ts
@@ -0,0 +1,115 @@
+/**
+ * CLI print/exit wrappers + per-child build orchestration for workspace
+ * federation. Kept out of both `cli.ts` (so routing there stays a one-liner
+ * per command) and `workspace.ts` (so the core stays free of process/exit and
+ * engine dependencies). The federated command bodies live in `workspace.ts`;
+ * this file only renders them and wires the child builds through the engine.
+ */
+import { Graft } from "../engine.js";
+import type { EngineConfig } from "../ai/providers.js";
+import { formatAsk } from "../ask/ask.js";
+import type { Direction } from "./traverse.js";
+import {
+ federateAsk,
+ federateCallers,
+ federateCheck,
+ federateGrep,
+ federateMap,
+ formatGrepResult,
+ migrationNote,
+ splitWorkspace,
+ zeroHitNote,
+} from "./workspace.js";
+
+export interface WorkspaceBuildOptions {
+ deep: boolean;
+ extensions?: string[];
+ concurrency?: number;
+ /** Provider/model/key config for child builds — WITHOUT any contextDir
+ * override, so each child writes to its own `<child>/graft/`. */
+ childConfig: EngineConfig;
+ override?: string;
+}
+
+/** Build every git child into its own committable `graft/`, then replace the
+ * parent's `graft/` with `workspace.json`. Prints the one-time split warning
+ * first when migrating away from a mega-graph. */
+export async function runWorkspaceBuild(root: string, opts: WorkspaceBuildOptions): Promise<void> {
+ const buildChild = async (childDir: string, childName: string): Promise<void> => {
+ const engine = new Graft({ ...opts.childConfig, contextDir: undefined });
+ if (opts.deep) await engine.init(childDir, { extensions: opts.extensions });
+ const g = await engine.graph(childDir, { llm: opts.deep, concurrency: opts.concurrency });
+ console.log(`✓ ${childName}/: ${g.nodes} nodes, ${g.edges} edges, ${g.cards} cards [${g.languages.join(", ")}]`);
+ for (const e of g.errors) console.error(`✗ ${childName}/: ${e}`);
+ };
+
+ const { children } = await splitWorkspace(
+ root,
+ opts.override,
+ buildChild,
+ ({ children, migrated }) => {
+ if (migrated) console.error(migrationNote(children));
+ console.error(`building ${children.length} workspace repos: ${children.join(", ")}`);
+ },
+ );
+ console.log(`✓ workspace: ${children.length} repos federated → graft/workspace.json`);
+ console.log(` commit each repo's graft/ and this folder's graft/workspace.json.`);
+}
+
+export function runWorkspaceAsk(
+ root: string,
+ override: string | undefined,
+ query: string,
+ opts: { limit?: number; source?: boolean; full?: boolean; json?: boolean },
+): void {
+ const r = federateAsk(root, override, query, { limit: opts.limit, source: opts.source, full: opts.full });
+ if (opts.json) console.log(JSON.stringify(r, null, 2));
+ else process.stdout.write(formatAsk(r));
+}
+
+export function runWorkspaceGrep(
+ root: string,
+ override: string | undefined,
+ pattern: string,
+ opts: { ignoreCase?: boolean; fixed?: boolean; json?: boolean },
+): void {
+ const { result, coverage } = federateGrep(root, override, pattern, { ignoreCase: opts.ignoreCase, fixed: opts.fixed });
+ if (opts.json) {
+ console.log(JSON.stringify(result, null, 2));
+ return;
+ }
+ if (result.totalHits === 0) {
+ console.error(coverage ? `${zeroHitNote(result)}\n${coverage}` : zeroHitNote(result));
+ return;
+ }
+ process.stdout.write(formatGrepResult(result));
+ if (coverage) console.log(coverage);
+}
+
+export function runWorkspaceMap(
+ root: string,
+ override: string | undefined,
+ opts: { maxDirs?: number },
+): void {
+ process.stdout.write(federateMap(root, override, { maxDirs: opts.maxDirs }));
+}
+
+export function runWorkspaceCheck(root: string, override?: string): void {
+ const { text, ok } = federateCheck(root, override);
+ process.stdout.write(text);
+ if (!ok) process.exit(1);
+}
+
+export function runWorkspaceCallers(
+ root: string,
+ override: string | undefined,
+ symbol: string,
+ opts: { direction?: Direction; depth?: number; in?: string },
+): void {
+ const { text, found } = federateCallers(root, override, symbol, opts);
+ if (!found) {
+ console.error(`✗ ${text}`);
+ process.exit(1);
+ }
+ process.stdout.write(text + "\n");
+}
diff --git a/src/graph/workspace.ts b/src/graph/workspace.ts
new file mode 100644
index 00000000..3a2eda64
--- /dev/null
+++ b/src/graph/workspace.ts
@@ -0,0 +1,407 @@
+/**
+ * Workspace federation — a "workspace" is a parent directory that holds two or
+ * more immediate git-repo children and has no source graph of its own. Instead
+ * of one mega-graph pooling every repo, each child keeps its OWN committable
+ * `graft/` (byte-identical to building that child standalone), and the parent
+ * holds a single `graft/workspace.json` index:
+ *
+ * { "version": 1, "children": ["repoA", "repoB"] }
+ *
+ * Queries run at the parent federate across the children: `ask` fuses every
+ * child's ranked hits with the same RRF `fuseScopes` used inside a single
+ * multi-scope repo (so the big repo can't drown the small one), `grep`/`map`/
+ * `check`/`callers` run per child and merge, always labeled `<child>/`.
+ *
+ * This module owns the pure/core pieces (the format, its readers/writers, graph
+ * loading, and the federated command bodies that return renderable data). The
+ * CLI print/exit wrappers and the per-child build orchestration live in
+ * `workspace-cli.ts`; `mcp/tools.ts` calls the federate* functions directly.
+ */
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { contextDirFor } from "../context/node-file.js";
+import { checkGraph } from "./check.js";
+import { loadGraphCached } from "./load.js";
+import { buildRepoMap, formatRepoMap } from "./map.js";
+import { discoverWorkspaceChildren } from "./scopes.js";
+import {
+ callersSavings,
+ headerOf,
+ hitLine,
+ looseNoteFor,
+} from "./traverse-cli.js";
+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 { 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";
+
+/** The parent index written to `<parent>/graft/workspace.json`. Nodes/edges
+ * never live at the parent — they live in each child's own `graft/`. */
+export interface WorkspaceV1 {
+ version: 1;
+ /** Immediate child dir names that are git repos, sorted. */
+ children: string[];
+}
+
+const WORKSPACE_FILE = "workspace.json";
+
+/** Absolute path to the workspace index for a parent root (`<dir>/graft/workspace.json`). */
+export function workspacePath(root: string, override?: string): string {
+ return join(contextDirFor(root, override), WORKSPACE_FILE);
+}
+
+/** Read the workspace index, or null when the parent has none (not a workspace,
+ * or unparseable/foreign json — treated the same as absent). */
+export function readWorkspace(root: string, override?: string): WorkspaceV1 | null {
+ const path = workspacePath(root, override);
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<WorkspaceV1>;
+ if (parsed.version !== 1 || !Array.isArray(parsed.children)) return null;
+ return { version: 1, children: parsed.children.map(String) };
+ } catch {
+ return null;
+ }
+}
+
+/** Write the workspace index, sorting children for a stable, minimal git diff. */
+export function writeWorkspace(root: string, ws: WorkspaceV1, override?: string): string {
+ const dir = contextDirFor(root, override);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, WORKSPACE_FILE);
+ const sorted: WorkspaceV1 = { version: 1, children: [...ws.children].sort() };
+ writeFileSync(path, JSON.stringify(sorted, null, 2) + "\n");
+ return path;
+}
+
+/** A parent is a workspace BUILD target when it has no own `.git` and ≥2 git
+ * children — or it was already split (a `workspace.json` is present). The
+ * no-own-`.git` guard keeps a normal repo with git submodules from being
+ * mistaken for a workspace. */
+export function isWorkspaceBuildRoot(root: string, override?: string): boolean {
+ if (readWorkspace(root, override)) return true;
+ if (existsSync(join(root, ".git"))) return false;
+ return discoverWorkspaceChildren(root).length >= 2;
+}
+
+/** True when the parent has a mega-graph from an older single-graph build
+ * (`graft/.graph/wiring.json`) — the thing a workspace build migrates away. */
+export function hasMegaGraph(root: string, override?: string): boolean {
+ return existsSync(wiringPath(contextDirFor(root, override)));
+}
+
+/** The EXACT split warning printed once, when a mega-graph parent is first
+ * built as a workspace. Templated on the child list so it names the real repos. */
+export function migrationNote(children: string[]): string {
+ const dirs = children.map((c) => `${c}/graft/`).join(", ");
+ return (
+ `⚠ this folder contains ${children.length} separate git repos — splitting: ` +
+ `each repo now gets its own committable graft/ (${dirs}); the combined graph ` +
+ `here is replaced by a workspace index. Queries from here now search all repos, fairly.`
+ );
+}
+
+/** Remove the parent's entire `graft/` tree — the mega-graph, its `.cache`, and
+ * any stale cards — so after `writeWorkspace` the parent holds ONLY
+ * workspace.json. Child graphs live in sibling `<child>/graft/`, never under
+ * this dir, so they are untouched. */
+export function clearParentGraft(root: string, override?: string): void {
+ rmSync(contextDirFor(root, override), { recursive: true, force: true });
+}
+
+export interface LoadedChild {
+ child: string;
+ graph: GraphV1;
+}
+
+export interface WorkspaceGraphs {
+ /** Children (from workspace.json when present, else discovered) that have a
+ * built graph, in sorted child order. */
+ loaded: LoadedChild[];
+ /** Listed children with no built graph yet — surfaced, never silently skipped. */
+ missing: string[];
+}
+
+/** Load each child's graph via `loadGraphCached`. Children come from
+ * workspace.json when present, otherwise from live git-child discovery (a
+ * not-yet-built workspace). A child without a built graph is counted into
+ * `missing`, not dropped. */
+export function loadWorkspaceGraphs(root: string, override?: string): WorkspaceGraphs {
+ const ws = readWorkspace(root, override);
+ const children = (ws ? ws.children : discoverWorkspaceChildren(root)).slice().sort();
+ const loaded: LoadedChild[] = [];
+ const missing: string[] = [];
+ for (const child of children) {
+ const graph = loadGraphCached(contextDirFor(join(root, child)));
+ if (graph) loaded.push({ child, graph });
+ else missing.push(child);
+ }
+ return { loaded, missing };
+}
+
+/** "2 of 3 workspace repos have graphs; run graft build to cover repoC" — the
+ * coverage line federated commands append when some listed child is unbuilt.
+ * Empty string when every child has a graph. */
+export function coverageNote(g: WorkspaceGraphs): string {
+ if (g.missing.length === 0) return "";
+ const total = g.loaded.length + g.missing.length;
+ return `${g.loaded.length} of ${total} workspace repos have graphs; run graft build to cover ${g.missing.join(", ")}`;
+}
+
+/** Prefix a hit pointer with its child dir so a `path:span` (or concept path
+ * list) opens correctly from the parent. Leaves free-text fragments alone. */
+function prefixPointer(child: string, pointer: string): string {
+ return pointer
+ .split(",")
+ .map((part) => {
+ const t = part.trim();
+ if (!t || t.includes(" ")) return part;
+ return `${child}/${t}`;
+ })
+ .join(", ");
+}
+
+export interface FederateAskOptions {
+ limit?: number;
+ source?: boolean;
+ full?: boolean;
+ graphRank?: boolean;
+}
+
+/**
+ * Federated `ask` across a workspace: run each child's own per-scope ask
+ * pipeline, then fuse ALL the children's scope lists with the same
+ * `fuseScopes` used inside a single multi-scope repo. Each child contributes
+ * one fusion scope per intra-child scope, labeled `<child>/<scope>` (or just
+ * `<child>` for a child's root scope), so a big repo can't drown a small one —
+ * rank positions are comparable across repos where raw scores are not.
+ *
+ * Returns a normal `AskResult`; `formatAsk` renders it unchanged, labeling each
+ * hit `[<child>/…]` via the standard multi-scope path.
+ */
+export function federateAsk(
+ root: string,
+ override: string | undefined,
+ query: string,
+ opts: FederateAskOptions = {},
+): AskResult {
+ const wg = loadWorkspaceGraphs(root, override);
+ const limit = opts.limit ?? 8;
+ const docs: ScopedDoc[] = [];
+ const back = new Map<string, { child: string; hit: AskHit }>();
+
+ for (const { child } of wg.loaded) {
+ let r: AskResult;
+ try {
+ // Over-fetch per child so cross-child fusion has enough candidates to
+ // rank before the final `limit` slice.
+ r = ask(join(root, child), query, {
+ limit: Math.max(limit * 4, 20),
+ source: opts.source,
+ full: opts.full,
+ graphRank: opts.graphRank,
+ });
+ } catch {
+ continue; // a corrupt/odd child never sinks the whole federated query
+ }
+ r.hits.forEach((hit, i) => {
+ const scope = hit.scope ? `${child}/${hit.scope}` : child;
+ const id = `${child}${i}`;
+ docs.push({ id, scope, score: hit.score });
+ back.set(id, { child, hit });
+ });
+ }
+
+ const fused = fuseScopes(docs);
+ const hits: AskHit[] = fused.ranked.slice(0, limit).map((rd) => {
+ const { child, hit } = back.get(rd.id)!;
+ return { ...hit, score: rd.score, scope: rd.scope, pointer: prefixPointer(child, hit.pointer) };
+ });
+
+ 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) {
+ 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;
+ return result;
+}
+
+/** Merge every child's `GrepResult` into one, prefixing group paths with the
+ * child dir and re-sorting by coupling (inDegree desc, path asc) across repos.
+ * In-degree stays each child's own — it comes from that child's graph. */
+export function federateGrep(
+ root: string,
+ override: string | undefined,
+ pattern: string,
+ opts: { ignoreCase?: boolean; fixed?: boolean } = {},
+): { result: GrepResult; coverage: string } {
+ const wg = loadWorkspaceGraphs(root, override);
+ const groups: GrepGroup[] = [];
+ let filesSearched = 0;
+ let totalHits = 0;
+ const truncated = { files: 0, hits: 0 };
+ let savedFiles = 0;
+ let savedChars = 0;
+
+ for (const { child, graph } of wg.loaded) {
+ const r = grepGraph(graph, join(root, child), pattern, {
+ ignoreCase: opts.ignoreCase,
+ fixed: opts.fixed,
+ });
+ filesSearched += r.filesSearched;
+ totalHits += r.totalHits;
+ truncated.files += r.truncated.files;
+ truncated.hits += r.truncated.hits;
+ if (r.saved) {
+ savedFiles += r.saved.files;
+ savedChars += r.saved.baselineChars;
+ }
+ for (const g of r.groups) {
+ groups.push({
+ ...g,
+ path: `${child}/${g.path}`,
+ symbol: g.symbol ? { ...g.symbol, path: `${child}/${g.symbol.path}` } : null,
+ });
+ }
+ }
+
+ groups.sort((a, b) => b.inDegree - a.inDegree || a.path.localeCompare(b.path));
+ const saved: Savings | undefined = savedChars > 0 ? { files: savedFiles, baselineChars: savedChars } : undefined;
+ const result: GrepResult = { pattern, filesSearched, totalHits, groups, truncated, saved };
+ return { result, coverage: coverageNote(wg) };
+}
+
+/** One `graft map` section per child (each child's own map, budget split evenly
+ * across the loaded children), joined under `<child>/` headers. */
+export function federateMap(
+ root: string,
+ override: string | undefined,
+ opts: { maxDirs?: number } = {},
+): string {
+ const wg = loadWorkspaceGraphs(root, override);
+ const perChild = opts.maxDirs !== undefined && wg.loaded.length > 0
+ ? Math.max(1, Math.floor(opts.maxDirs / wg.loaded.length))
+ : undefined;
+
+ const sections = wg.loaded.map(({ child, graph }) => {
+ const map = buildRepoMap(graph, perChild !== undefined ? { maxDirs: perChild } : {});
+ return `## ${child}/\n${formatRepoMap(map).trimEnd()}`;
+ });
+ const head = `workspace map — ${wg.loaded.length} repo(s)`;
+ const parts = [head, "", sections.join("\n\n")];
+ const cov = coverageNote(wg);
+ if (cov) parts.push("", cov);
+ return parts.join("\n") + "\n";
+}
+
+/** Per-child drift status. `ok` is false when any BUILT child is stale — an
+ * unbuilt child is surfaced (coverage), never a failure. */
+export function federateCheck(
+ root: string,
+ override?: string,
+): { text: string; ok: boolean } {
+ const wg = loadWorkspaceGraphs(root, override);
+ const lines = [`workspace check — ${wg.loaded.length + wg.missing.length} repo(s)`, ""];
+ let ok = true;
+ for (const { child } of wg.loaded) {
+ const g = checkGraph(join(root, child));
+ if (g.ok) {
+ lines.push(`${child}/: OK`);
+ } else {
+ ok = false;
+ const bits: string[] = [];
+ if (g.added.length) bits.push(`${g.added.length} added`);
+ if (g.removed.length) bits.push(`${g.removed.length} removed`);
+ if (g.changed.length) bits.push(`${g.changed.length} changed`);
+ if (g.stale.length) bits.push(`${g.stale.length} stale`);
+ lines.push(`${child}/: STALE (${bits.join(", ")})`);
+ }
+ }
+ for (const child of wg.missing) lines.push(`${child}/: not built (run graft build)`);
+ const cov = coverageNote(wg);
+ if (cov) lines.push("", cov);
+ return { text: lines.join("\n") + "\n", ok };
+}
+
+/** Resolve a symbol across every child, grouped per child. Reuses the shared
+ * traverse-cli formatters so each block reads exactly like `graft callers`. */
+export function federateCallers(
+ root: string,
+ override: string | undefined,
+ symbol: string,
+ opts: { direction?: Direction; depth?: number; in?: string } = {},
+): { text: string; found: boolean } {
+ const wg = loadWorkspaceGraphs(root, override);
+ const direction: Direction = opts.direction ?? "in";
+ const depth = opts.depth && opts.depth >= 1 ? Math.floor(opts.depth) : 1;
+ const showDepth = depth > 1;
+
+ const blocks: string[] = [];
+ let found = false;
+ for (const { child, graph } of wg.loaded) {
+ const matches = resolveSymbol(graph, symbol, opts.in ? { in: opts.in } : {});
+ if (matches.length === 0) continue;
+ found = true;
+ const results = matches.map((m) => ({ symbol: m, hits: edgeWalk(graph, m, direction, depth) }));
+ const lines = [`## ${child}/`];
+ for (const { symbol: sym, hits } of results) {
+ lines.push(headerOf(sym));
+ if (hits.length === 0) lines.push(looseNoteFor(direction, sym.name));
+ else for (const h of hits) lines.push(hitLine(direction, h, showDepth));
+ }
+ const body = lines.join("\n");
+ blocks.push(body + savingsFooter(body, callersSavings(graph, results)));
+ }
+
+ const cov = coverageNote(wg);
+ if (!found) {
+ const base = `no symbol "${symbol}" in any of the ${wg.loaded.length} workspace repo(s) — check spelling or run graft build`;
+ return { text: cov ? `${base}\n${cov}` : base, found: false };
+ }
+ let text = blocks.join("\n\n");
+ if (cov) text += `\n\n${cov}`;
+ return { text, found: true };
+}
+
+/**
+ * Split a parent into a workspace: build each git child (via the supplied
+ * `buildChild` callback, so this stays free of any engine/LLM dependency),
+ * then REPLACE the parent's `graft/` with just `workspace.json`. `onStart`
+ * fires once — before any child is built — carrying whether this build is a
+ * mega-graph migration, so the caller can print the one-time split warning
+ * first, exactly as the spec requires.
+ *
+ * The child build writes into `<child>/graft/` and is byte-identical to
+ * building that child standalone (`buildChild` is just `buildGraph(childDir)`),
+ * because nothing about the parent path enters the child's build.
+ */
+export async function splitWorkspace(
+ root: string,
+ override: string | undefined,
+ buildChild: (childDir: string, childName: string) => Promise<void>,
+ onStart?: (info: { children: string[]; migrated: boolean }) => void,
+): Promise<{ children: string[]; migrated: boolean }> {
+ const children = discoverWorkspaceChildren(root).slice().sort();
+ const migrated = hasMegaGraph(root, override);
+ onStart?.({ children, migrated });
+ for (const child of children) await buildChild(join(root, child), child);
+ clearParentGraft(root, override); // drop the mega-graph/.cache/cards…
+ writeWorkspace(root, { version: 1, children }, override); // …leaving ONLY workspace.json
+ return { children, migrated };
+}
+
+export { formatGrepResult, zeroHitNote };
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 8b954c68..8a0162d6 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -14,6 +14,14 @@ import { savingsFooter } from '../context/savings.js';
import { grepGraph } from '../search/grep.js';
import { formatGrepResult, zeroHitNote } from '../search/grep-cli.js';
import { buildRepoMap, formatRepoMap } from '../graph/map.js';
+import {
+ federateAsk,
+ federateCallers,
+ federateCheck,
+ federateGrep,
+ federateMap,
+ readWorkspace,
+} from '../graph/workspace.js';
import type { NodeV1 } from '../graph/types.js';
export interface ToolDef {
@@ -135,6 +143,57 @@ function renderMatches(
.join('\n\n');
}
+/** When the MCP server is rooted at a workspace parent, the ask/callers/grep/
+ * map/check tools federate across the children — identical to the CLI. Returns
+ * null for tools that don't federate (skeleton is per-file), so the caller
+ * falls through to the normal single-graph path. */
+function callWorkspaceTool(
+ root: string,
+ dirOverride: string | undefined,
+ name: string,
+ args: Record<string, unknown>,
+): { text: string; isError: boolean } | null {
+ switch (name) {
+ case 'graft_ask': {
+ 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 });
+ return { text: formatAsk(r), isError: false };
+ }
+ case 'graft_callers': {
+ const symbol = String(args.symbol ?? args.file ?? '');
+ if (!symbol) return { text: 'graft_callers requires a symbol', isError: true };
+ const { text, found } = federateCallers(root, dirOverride, symbol, {
+ direction: args.direction === 'out' ? 'out' : 'in',
+ depth: typeof args.depth === 'number' && Number.isFinite(args.depth) ? args.depth : undefined,
+ in: typeof args.in === 'string' && args.in ? args.in : undefined,
+ });
+ return { text, isError: !found };
+ }
+ case 'graft_grep': {
+ const pattern = String(args.pattern ?? '');
+ if (!pattern) return { text: 'graft_grep requires a pattern', isError: true };
+ const { result, coverage } = federateGrep(root, dirOverride, pattern, {
+ ignoreCase: typeof args.ignore_case === 'boolean' ? args.ignore_case : undefined,
+ fixed: typeof args.fixed === 'boolean' ? args.fixed : undefined,
+ });
+ const text = result.totalHits === 0 ? zeroHitNote(result) : formatGrepResult(result);
+ return { text: coverage ? `${text}\n${coverage}` : text, isError: false };
+ }
+ case 'graft_map': {
+ const maxDirs = typeof args.max_dirs === 'number' && Number.isFinite(args.max_dirs) && args.max_dirs > 0 ? args.max_dirs : undefined;
+ return { text: federateMap(root, dirOverride, { maxDirs }), isError: false };
+ }
+ case 'graft_check': {
+ const { text } = federateCheck(root, dirOverride);
+ return { text, isError: false };
+ }
+ default:
+ return null;
+ }
+}
+
export function callTool(
root: string,
name: string,
@@ -142,6 +201,10 @@ export function callTool(
dirOverride?: string,
): { text: string; isError: boolean } {
try {
+ if (readWorkspace(root, dirOverride)) {
+ const fed = callWorkspaceTool(root, dirOverride, name, args);
+ if (fed) return fed;
+ }
switch (name) {
case 'graft_ask': {
const query = String(args.query ?? '');
diff --git a/test/workspace.test.ts b/test/workspace.test.ts
new file mode 100644
index 00000000..d16ac42c
--- /dev/null
+++ b/test/workspace.test.ts
@@ -0,0 +1,199 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { buildGraph } from "../src/graph/build.js";
+import { writeGraph, wiringPath } from "../src/graph/write.js";
+import { contextDirFor } from "../src/context/node-file.js";
+import {
+ readWorkspace,
+ writeWorkspace,
+ loadWorkspaceGraphs,
+ coverageNote,
+ migrationNote,
+ splitWorkspace,
+ federateAsk,
+ federateCheck,
+ federateCallers,
+ federateGrep,
+ isWorkspaceBuildRoot,
+} from "../src/graph/workspace.js";
+import { formatAsk } from "../src/ask/ask.js";
+import type { GraphV1 } from "../src/graph/types.js";
+
+/** A parent dir with git children (each a `.git` dir + one source file). */
+function workspaceFx(children: Record<string, Record<string, string>>): string {
+ const parent = mkdtempSync(join(tmpdir(), "ws-"));
+ for (const [child, files] of Object.entries(children)) {
+ mkdirSync(join(parent, child, ".git"), { recursive: true });
+ for (const [name, content] of Object.entries(files)) {
+ writeFileSync(join(parent, child, name), content);
+ }
+ }
+ return parent;
+}
+
+/** Build every git child into its own graft/, then write the workspace index. */
+async function buildWorkspace(parent: string): Promise<{ children: string[]; migrated: boolean }> {
+ return splitWorkspace(parent, undefined, async (childDir) => {
+ await buildGraph(childDir);
+ });
+}
+
+const REPOS = {
+ repoA: { "a.ts": "export function alphaHandler() { return helperThing(); }\nfunction helperThing() { return 1; }\n" },
+ repoB: { "b.ts": "export function betaHandler() { return 2; }\n" },
+};
+
+test("isWorkspaceBuildRoot: ≥2 git children, no own .git → workspace", () => {
+ const p = workspaceFx(REPOS);
+ assert.equal(isWorkspaceBuildRoot(p), true);
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("isWorkspaceBuildRoot: own .git (submodules) → NOT a workspace", () => {
+ const p = workspaceFx(REPOS);
+ mkdirSync(join(p, ".git"), { recursive: true });
+ assert.equal(isWorkspaceBuildRoot(p), false);
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("child built via parent is byte-identical to building it standalone", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const childGraft = contextDirFor(join(p, "repoA"));
+ const viaParent = readFileSync(wiringPath(childGraft), "utf8");
+
+ // Rebuild the same child standalone — deterministic writer, same source.
+ rmSync(childGraft, { recursive: true, force: true });
+ await buildGraph(join(p, "repoA"));
+ const standalone = readFileSync(wiringPath(childGraft), "utf8");
+
+ assert.equal(viaParent, standalone);
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("workspace.json lists both children; parent holds no mega-graph", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const ws = readWorkspace(p);
+ assert.deepEqual(ws, { version: 1, children: ["repoA", "repoB"] });
+ // Parent graft holds ONLY workspace.json — no .graph/wiring.json.
+ assert.equal(existsSync(wiringPath(contextDirFor(p))), false);
+ assert.equal(existsSync(join(contextDirFor(p), "workspace.json")), true);
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("ask at the parent federates hits from both children, labeled <child>/", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const r = federateAsk(p, undefined, "handler", { limit: 8 });
+ const text = formatAsk(r);
+ assert.ok(text.includes("[repoA/]"), `expected repoA label:\n${text}`);
+ assert.ok(text.includes("[repoB/]"), `expected repoB label:\n${text}`);
+ // Pointers are child-prefixed so they open from the parent.
+ assert.ok(r.hits.some((h) => h.pointer.startsWith("repoA/")));
+ assert.ok(r.hits.some((h) => h.pointer.startsWith("repoB/")));
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("ask inside a single child = standalone (no federation scopes)", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const { ask } = await import("../src/ask/ask.js");
+ const r = ask(join(p, "repoA"), "handler", {});
+ assert.equal(r.scopes, undefined); // single-scope repo → no scope labels
+ assert.ok(r.hits.length > 0);
+ assert.ok(!r.hits.some((h) => h.pointer.startsWith("repoA/"))); // paths are child-relative
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("migration: mega-graph parent split → .graph removed, workspace.json written, exact note", async () => {
+ const p = workspaceFx(REPOS);
+ // Pre-seed a hand-built combined mega-graph at the parent.
+ const mega: GraphV1 = {
+ meta: { version: 1, nodeCount: 0, edgeCount: 0, languages: [] },
+ nodes: [],
+ edges: [],
+ };
+ writeGraph(mega, contextDirFor(p));
+ assert.equal(existsSync(wiringPath(contextDirFor(p))), true);
+
+ const { migrated } = await buildWorkspace(p);
+ assert.equal(migrated, true);
+ assert.equal(existsSync(wiringPath(contextDirFor(p))), false); // mega-graph gone
+ assert.equal(existsSync(join(contextDirFor(p), "workspace.json")), true);
+
+ assert.equal(
+ migrationNote(["repoA", "repoB"]),
+ "⚠ this folder contains 2 separate git repos — splitting: each repo now gets its own committable graft/ (repoA/graft/, repoB/graft/); the combined graph here is replaced by a workspace index. Queries from here now search all repos, fairly.",
+ );
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("check federation: OK when all in sync, STALE + not-ok when a child drifts", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+
+ const fresh = federateCheck(p);
+ assert.equal(fresh.ok, true);
+ assert.ok(fresh.text.includes("repoA/: OK"));
+ assert.ok(fresh.text.includes("repoB/: OK"));
+
+ // Change repoA's code WITHOUT rebuilding → present-and-stale.
+ writeFileSync(join(p, "repoA", "a.ts"), "export function alphaHandler() { return 99; }\nexport function newlyAdded() { return 0; }\n");
+ const drifted = federateCheck(p);
+ assert.equal(drifted.ok, false);
+ assert.ok(drifted.text.includes("repoA/: STALE"));
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("callers federation resolves a symbol per child, grouped", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const { text, found } = federateCallers(p, undefined, "helperThing", {});
+ assert.equal(found, true);
+ assert.ok(text.includes("## repoA/"));
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("grep federation merges groups across children with child-prefixed paths", async () => {
+ const p = workspaceFx(REPOS);
+ await buildWorkspace(p);
+ const { result } = federateGrep(p, undefined, "Handler", { ignoreCase: true });
+ assert.ok(result.totalHits >= 2);
+ const paths = result.groups.map((g) => g.path);
+ assert.ok(paths.some((p) => p.startsWith("repoA/")));
+ assert.ok(paths.some((p) => p.startsWith("repoB/")));
+ rmSync(p, { recursive: true, force: true });
+});
+
+test("one unbuilt child is surfaced, not silently skipped", async () => {
+ const p = workspaceFx({
+ ...REPOS,
+ repoC: { "c.ts": "export function gammaHandler() { return 3; }\n" },
+ });
+ await buildWorkspace(p);
+ // Simulate repoC never having been built.
+ rmSync(contextDirFor(join(p, "repoC")), { recursive: true, force: true });
+
+ const wg = loadWorkspaceGraphs(p);
+ assert.deepEqual(wg.loaded.map((l) => l.child), ["repoA", "repoB"]);
+ assert.deepEqual(wg.missing, ["repoC"]);
+ assert.equal(
+ coverageNote(wg),
+ "2 of 3 workspace repos have graphs; run graft build to cover repoC",
+ );
+ 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 });
+ writeFileSync(join(contextDirFor(p), "workspace.json"), "{}");
+ assert.equal(readWorkspace(p), null);
+ writeWorkspace(p, { version: 1, children: ["x", "a"] });
+ assert.deepEqual(readWorkspace(p), { version: 1, children: ["a", "x"] });
+ rmSync(p, { recursive: true, force: true });
+});