Skip to content

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

feat: wire every workspace child on init, and find graft/ from subdirs (#82)

anirudhkumar-nanonetse74e9d723fa6
diff --git a/README.md b/README.md
index 118d2641..c5f72811 100644
--- a/README.md
+++ b/README.md
@@ -406,6 +406,15 @@ Graft handles two shapes without any config:
Either way, narrow to one sub-project with `graft ask "<task>" --in <scope>/`
once you know where you're working.
+`graft init` at the parent of a multi-repo folder wires **every child repo too**,
+not just the parent — an agent session opens at a repo root and reads its
+instruction files from there, so each child needs its own. A session started in
+the parent gets the federated view; one started in a child sees that repo alone.
+
+Commands also find the graph from a subdirectory: with no `[dir]` argument they
+walk up to the nearest `graft/`, so `graft ask` works from `src/deep/inside/`
+without a `cd` to the repo root.
+
## Visualize it (`graft viz`)
`graft viz` opens a local, interactive view of both graphs — no install, no dev
diff --git a/src/claude/init.ts b/src/claude/init.ts
index ced30568..258c8fae 100644
--- a/src/claude/init.ts
+++ b/src/claude/init.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, writeFileSync, readFileSync, existsSync, chmodSync } from 'node:fs';
+import { mkdirSync, writeFileSync, readFileSync, chmodSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { execFileSync } from 'node:child_process';
import { mergeGraftSettings } from './settings-merge.js';
@@ -6,6 +6,7 @@ import { statuslineShim, hooksShim } from './shim-template.js';
import { skillTemplate } from './skill-template.js';
import { claudeDistDir } from './paths.js';
import { mergeJsonKey, serverEntry, type McpWrite } from '../hosts/mcp-config.js';
+import { hasGraftIndex } from '../graph/root.js';
import type { PlannedWrite } from '../hosts/plan.js';
/**
@@ -33,8 +34,10 @@ export function claudeTargets(dir: string): PlannedWrite[] {
* Best-effort; the user can always run `graft build` (the epilogue says so).
*/
export function buildGraphIfMissing(dir: string, opts: { build?: boolean; cliPath?: string }): boolean {
- const wiring = join(dir, 'graft', '.graph', 'wiring.json');
- if (opts.build === false || !opts.cliPath || existsSync(wiring)) return false;
+ // `hasGraftIndex`, not just wiring.json: a workspace parent's graph IS its
+ // `workspace.json` (nodes live in the children), so testing for wiring.json
+ // alone would call it unbuilt and rebuild every child on each init.
+ if (opts.build === false || !opts.cliPath || hasGraftIndex(dir)) return false;
try {
execFileSync(process.execPath, [opts.cliPath, 'build', '.'], { cwd: dir, stdio: 'inherit', timeout: 300000 });
return true;
diff --git a/src/cli.ts b/src/cli.ts
index da5ad539..ce2c14cf 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -6,7 +6,7 @@
*/
import "dotenv/config";
import { Command } from "commander";
-import { relative, resolve } from "node:path";
+import { join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Graft } from "./engine.js";
import { resolveConfig, type EngineConfig } from "./ai/providers.js";
@@ -20,6 +20,8 @@ import { contextDirFor } from "./context/node-file.js";
import { loadGraphCached } from "./graph/load.js";
import { ensureFreshChildren, ensureFreshGraph, refreshNote } from "./graph/refresh.js";
import { isWorkspaceBuildRoot, readWorkspace } from "./graph/workspace.js";
+import { nearestGraftRoot } from "./graph/root.js";
+import { discoverWorkspaceChildren } from "./graph/scopes.js";
import {
runWorkspaceAsk,
runWorkspaceBuild,
@@ -70,6 +72,22 @@ function cliConfig(): EngineConfig {
const engineFrom = (): Graft => new Graft(cliConfig());
+/** Text for the omitted-`[dir]` case, shared by every query command's help. */
+const DIR_ARG = ["[dir]", "repository root (default: nearest ancestor with a graft/ index)"] as const;
+
+/**
+ * The root a query runs against: the dir the user named, else the nearest
+ * ancestor holding a graft index (`graph/root.ts`) so a shell or agent session
+ * in a subdirectory still finds the graph. The walk is announced on stderr —
+ * answering from an ancestor's graph must never be silent.
+ */
+function queryRoot(dir?: string): string {
+ if (dir !== undefined) return resolve(dir);
+ const { root, levels } = nearestGraftRoot(process.cwd(), program.opts<GlobalOpts>().dir);
+ if (levels > 0) console.error(`[graft] no graft/ here — answering from ${root}/graft`);
+ return root;
+}
+
/**
* Bring the graph up to date with the working tree before a query answers from it
* — the same gate the MCP tools run (see `graph/refresh.ts`). Cheap when nothing
@@ -239,18 +257,19 @@ program
.command("ask")
.description("Query the graft/ graph — returns ranked nodes + exact file:line, routed to prose or wiring ($0, no key)")
.argument("<query>", "what you want to understand, in plain words")
- .argument("[dir]", "repository root", ".")
+ .argument(...DIR_ARG)
.option("-n, --limit <n>", "max results", "8")
.option("--source", "inline the source at each file:line hit (retriever mode — the pack IS the answer, no need to re-open files)")
.option("--full", "with --source: inline whole definition spans instead of the default ≤8-line crux excerpts")
.option("--in <path>", "narrow to nodes under this path prefix, filtered before scoring (segment-aware, like scopeOf)")
.option("--json", "output the result as JSON")
.option(...NO_REFRESH_FLAG)
- .action(async (query: string, dir: string, opts: { limit: string; source?: boolean; full?: boolean; in?: string; json?: boolean; refresh?: boolean }) => {
+ .action(async (query: string, dirArg: string | undefined, opts: { limit: string; source?: boolean; full?: boolean; in?: string; json?: boolean; refresh?: boolean }) => {
+ const dir = queryRoot(dirArg);
await refreshBefore(dir, opts);
const askGlobalDir = program.opts<GlobalOpts>().dir;
- if (readWorkspace(resolve(dir), askGlobalDir)) {
- runWorkspaceAsk(resolve(dir), askGlobalDir, query, {
+ if (readWorkspace(dir, askGlobalDir)) {
+ runWorkspaceAsk(dir, askGlobalDir, query, {
limit: Number(opts.limit), source: opts.source, full: opts.full, in: opts.in, json: opts.json,
});
return;
@@ -276,10 +295,11 @@ program
.command("skeleton")
.description("Signatures-only view of one file from the wiring graph — the cheapest way to see a file's API surface")
.argument("<file>", "repo-relative path (or unique basename) of the file")
- .argument("[dir]", "repository root", ".")
+ .argument(...DIR_ARG)
.option("--json", "output the result as JSON")
.option(...NO_REFRESH_FLAG)
- .action(async (file: string, dir: string, opts: { json?: boolean; refresh?: boolean }) => {
+ .action(async (file: string, dirArg: string | undefined, opts: { json?: boolean; refresh?: boolean }) => {
+ const dir = queryRoot(dirArg);
await refreshBefore(dir, opts);
const { skeleton, formatSkeleton } = await import("./ask/ask.js");
const globalOpts = program.opts<{ dir?: string }>();
@@ -291,13 +311,14 @@ program
program
.command("check")
.description("Fail if graft/ is stale relative to the code (for CI)")
- .argument("[dir]", "repository root", ".")
+ .argument(...DIR_ARG)
.option("-e, --extensions <exts...>", "code extensions to include")
.option("--json", "output the drift as JSON")
- .action((dir: string, opts: { extensions?: string[]; json?: boolean }) => {
+ .action((dirArg: string | undefined, opts: { extensions?: string[]; json?: boolean }) => {
+ const dir = queryRoot(dirArg);
const checkGlobalDir = program.opts<GlobalOpts>().dir;
- if (readWorkspace(resolve(dir), checkGlobalDir)) {
- runWorkspaceCheck(resolve(dir), checkGlobalDir);
+ if (readWorkspace(dir, checkGlobalDir)) {
+ runWorkspaceCheck(dir, checkGlobalDir);
return;
}
const engine = engineFrom();
@@ -331,10 +352,11 @@ program
program
.command("viz")
.description("Serve an interactive visualization of the context graph (and graph.json when present)")
- .argument("[dir]", "repository root", ".")
+ .argument(...DIR_ARG)
.option("-p, --port <port>", "port to serve on", "4400")
.option("--no-open", "don't open the browser")
- .action(async (dir: string, opts: { port: string; open: boolean }) => {
+ .action(async (dirArg: string | undefined, opts: { port: string; open: boolean }) => {
+ const dir = queryRoot(dirArg);
const { existsSync } = await import("node:fs");
const { resolve, basename } = await import("node:path");
const { spawn } = await import("node:child_process");
@@ -366,12 +388,12 @@ program
program
.command("mcp")
.description("Serve the graph over MCP (stdio) — exposes graft_find_code, graft_trace_calls, graft_find_all, graft_file_api, graft_repo_map and graft_check_freshness as tools")
- .argument("[dir]", "repository root", ".")
- .action(async (dir: string) => {
- const { resolve } = await import("node:path");
+ .argument(...DIR_ARG)
+ .action(async (dirArg: string | undefined) => {
+ const dir = queryRoot(dirArg);
const { startMcpServer } = await import("./mcp/server.js");
const globalOpts = program.opts<{ dir?: string }>();
- startMcpServer(resolve(dir), globalOpts.dir, currentVersion);
+ startMcpServer(dir, globalOpts.dir, currentVersion);
});
program
@@ -380,7 +402,7 @@ program
"Who calls/references a symbol ($0, no LLM). --direction out gives callees (what it calls); --depth N (or all) walks transitively for full blast radius",
)
.argument("<symbol>", "bare name, qualified (Class.method), or package-qualified (pkg.Fn)")
- .argument("[dir]", "repository root", ".")
+ .argument(...DIR_ARG)
.option("--direction <in|out>", 'edge direction: "in" = callers (default), "out" = callees')
.option("-d, --depth <n>", 'walk transitively up to N hops for blast radius, or "all" for the full connected closure (default 1)')
.option("--in <path>", "narrow matches to nodes at or under this path prefix")
@@ -389,13 +411,14 @@ program
.action(
async (
symbol: string,
- dir: string,
+ dirArg: string | undefined,
opts: { direction?: string; depth?: string; in?: string; json?: boolean; refresh?: boolean },
) => {
+ const dir = queryRoot(dirArg);
await refreshBefore(dir, opts);
const globalOpts = program.opts<{ dir?: string }>();
- if (!opts.json && readWorkspace(resolve(dir), globalOpts.dir)) {
- runWorkspaceCallers(resolve(dir), globalOpts.dir, symbol, {
+ if (!opts.json && readWorkspace(dir, globalOpts.dir)) {
+ runWorkspaceCallers(dir, globalOpts.dir, symbol, {
direction: opts.direction === "out" ? "out" : "in",
depth: opts.depth
? (/^(all|full|max)$/i.test(opts.depth) ? Number.POSITIVE_INFINITY : Number(opts.depth))
@@ -419,7 +442,7 @@ program
.command("grep")
.description("Regex search over indexed files, hits grouped by enclosing symbol and ranked by coupling ($0, no LLM)")
.argument("<pattern>", "regex pattern (or literal string with --fixed)")
- .argument("[dir]", "repository root", ".")
+ .argument(...DIR_ARG)
.option("-i, --ignore-case", "case-insensitive match")
.option("--fixed", "treat pattern as a literal string, not a regex")
.option("--in <path>", "narrow to files at or under this path prefix")
@@ -428,13 +451,14 @@ program
.action(
async (
pattern: string,
- dir: string,
+ dirArg: string | undefined,
opts: { ignoreCase?: boolean; fixed?: boolean; in?: string; json?: boolean; refresh?: boolean },
) => {
+ const dir = queryRoot(dirArg);
await refreshBefore(dir, opts);
const globalOpts = program.opts<{ dir?: string }>();
- if (readWorkspace(resolve(dir), globalOpts.dir)) {
- runWorkspaceGrep(resolve(dir), globalOpts.dir, pattern, {
+ if (readWorkspace(dir, globalOpts.dir)) {
+ runWorkspaceGrep(dir, globalOpts.dir, pattern, {
ignoreCase: opts.ignoreCase, fixed: opts.fixed, json: opts.json,
});
return;
@@ -455,11 +479,12 @@ program
.description(
"Token-budgeted repo orientation — directory clusters, per-directory hubs, and global hotspots from the wiring graph ($0, no LLM)",
)
- .argument("[dir]", "repository root", ".")
+ .argument(...DIR_ARG)
.option("--max-dirs <n>", "max directory entries shown, rest counted into dropped (default 16)")
.option("--json", "output as JSON")
.option(...NO_REFRESH_FLAG)
- .action(async (dir: string, opts: { json?: boolean; maxDirs?: string; refresh?: boolean }) => {
+ .action(async (dirArg: string | undefined, opts: { json?: boolean; maxDirs?: string; refresh?: boolean }) => {
+ const dir = queryRoot(dirArg);
const root = resolve(dir);
const globalOpts = program.opts<{ dir?: string }>();
let maxDirsW: number | undefined;
@@ -550,8 +575,21 @@ program
return;
}
+ // Workspace parent: every child repo gets its OWN wiring too. A session
+ // opens at a repo root, not at the parent, and reads `.claude/` from there —
+ // wiring only the parent leaves each child with no skill, hooks, or MCP.
+ // The parent's own wiring stays (queries there federate across children).
+ const children = isWorkspaceBuildRoot(repo, program.opts<GlobalOpts>().dir)
+ ? discoverWorkspaceChildren(repo)
+ : [];
+ // Parent FIRST: its build is the workspace build, which builds every child's
+ // graph, so each child's own `buildGraphIfMissing` then finds one and no-ops.
+ const targets = [repo, ...children.map((c) => join(repo, c))];
+
if (opts.dryRun) {
console.error(formatPlan(plan, ids, repo, home));
+ for (const child of children)
+ console.error(`\n— ${child}/ (workspace child)\n` + formatPlan(planInit(join(repo, child), { home }), ids, join(repo, child), home));
return;
}
if (ids.length === 0) {
@@ -562,6 +600,44 @@ program
const wantClaude = ids.includes("claude");
const cliPath = fileURLToPath(import.meta.url);
+ if (children.length)
+ console.error(`· workspace: wiring ${repo} and ${children.length} child repo(s) — ${children.join(", ")}`);
+
+ for (const target of targets) {
+ if (target !== repo) console.error(`\n— ${relative(repo, target)}/`);
+ wireTarget(target, ids, { home, cliPath, plan, opts, wantClaude });
+ }
+
+ // One epilogue for the whole run. A workspace parent holds no nodes of its
+ // own, so the totals come from the children — the graph the user actually got.
+ const globalDir = program.opts<GlobalOpts>().dir;
+ const graphs = (children.length ? children.map((c) => join(repo, c)) : [repo])
+ .map((d) => loadGraphCached(contextDirFor(d, children.length ? undefined : globalDir)))
+ .filter((g): g is NonNullable<typeof g> => g !== null);
+ console.error(
+ "\n" +
+ formatInitEpilogue({
+ graphBuilt: graphs.length > 0,
+ nodes: graphs.reduce((n, g) => n + g.meta.nodeCount, 0),
+ edges: graphs.reduce((n, g) => n + g.meta.edgeCount, 0),
+ }),
+ );
+ });
+
+/** One repo's worth of `init` writes — the parent, then each workspace child. */
+function wireTarget(
+ repo: string,
+ ids: string[],
+ ctx: {
+ home: string;
+ cliPath: string;
+ plan: ReturnType<typeof planInit>;
+ wantClaude: boolean;
+ opts: { build?: boolean; mcp?: boolean; hooks?: boolean; global?: boolean };
+ },
+): void {
+ const { home, cliPath, plan, wantClaude, opts } = ctx;
+
if (wantClaude) {
const res = runInit(repo, { build: opts.build, cliPath });
console.error(`✓ wrote ${res.settingsPath}`);
@@ -606,18 +682,7 @@ program
);
}
- const globalOpts = program.opts<{ dir?: string }>();
- const outDir = contextDirFor(repo, globalOpts.dir);
- const graph = loadGraphCached(outDir);
- console.error(
- "\n" +
- formatInitEpilogue({
- graphBuilt: graph !== null,
- nodes: graph?.meta.nodeCount,
- edges: graph?.meta.edgeCount,
- }),
- );
- });
+}
program.parseAsync().catch((err) => {
console.error(err instanceof Error ? err.message : err);
diff --git a/src/graph/root.ts b/src/graph/root.ts
new file mode 100644
index 00000000..e80faed4
--- /dev/null
+++ b/src/graph/root.ts
@@ -0,0 +1,45 @@
+/**
+ * Where "here" is when a query names no directory. An agent session — or a plain
+ * shell — started in a subdirectory of an indexed repo should still find the
+ * graph, so the implicit root is the nearest ANCESTOR holding a graft index:
+ * either a repo's own wiring graph (`graft/.graph/wiring.json`) or a workspace
+ * parent's children index (`graft/workspace.json`). Nothing indexed anywhere
+ * above → the start dir itself, so `graft build` in a fresh repo still means
+ * "here" and no command silently retargets a sibling tree.
+ *
+ * Only the IMPLICIT case walks. An explicit `[dir]` argument is taken at face
+ * value, and a `--dir` override short-circuits entirely: `contextDirFor` returns
+ * an override verbatim and ignores the root it is handed, so every ancestor
+ * would report the same context dir and the walk would answer "level 0" for a
+ * dir that isn't the repo.
+ */
+import { existsSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { contextDirFor } from "../context/node-file.js";
+import { wiringPath } from "./write.js";
+import { workspacePath } from "./workspace.js";
+
+/** True when `dir` is a graft root of either shape — a built repo or a workspace parent. */
+export function hasGraftIndex(dir: string): boolean {
+ return existsSync(wiringPath(contextDirFor(dir))) || existsSync(workspacePath(dir));
+}
+
+export interface RootResolution {
+ /** Absolute dir to run the command against. */
+ root: string;
+ /** Directory levels walked up; 0 when the start dir was already the root (the common case). */
+ levels: number;
+}
+
+/** The nearest ancestor of `start` (inclusive) that holds a graft index, else `start`. */
+export function nearestGraftRoot(start: string, override?: string): RootResolution {
+ const from = resolve(start);
+ if (override) return { root: from, levels: 0 };
+ let dir = from;
+ for (let levels = 0; ; levels++) {
+ if (hasGraftIndex(dir)) return { root: dir, levels };
+ const up = dirname(dir);
+ if (up === dir) return { root: from, levels: 0 }; // hit the filesystem root, nothing indexed
+ dir = up;
+ }
+}
diff --git a/test/claude-init-workspace.test.ts b/test/claude-init-workspace.test.ts
new file mode 100644
index 00000000..2c0ebe57
--- /dev/null
+++ b/test/claude-init-workspace.test.ts
@@ -0,0 +1,115 @@
+/**
+ * Workspace `init` fan-out + the subdirectory root walk, end to end.
+ *
+ * The gap both close: with two sibling repos under one parent, `graft init
+ * <parent>` wired only the parent. But an agent session opens at a REPO root and
+ * reads `.claude/` from its own cwd, so every child was left with no skill, no
+ * hooks and no MCP — graft was invisible exactly where the work happens. And a
+ * session opened one level deeper (`<child>/src`) found no `graft/` at all.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import { createRequire } from "node:module";
+import { join, resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { runCli, tmpRepo, homeEnv } from "./helpers.js";
+
+const CLI = resolve(process.cwd(), "src/cli.ts");
+// Absolute: these runs have a scratch dir as their cwd, so a bare `--import tsx`
+// would resolve against the temp dir and find no such package. As a file:// URL
+// because `--import` goes through the ESM loader, and a bare Windows absolute
+// path parses as the URL scheme `d:` (ERR_UNSUPPORTED_ESM_URL_SCHEME).
+const TSX = pathToFileURL(createRequire(join(process.cwd(), "x.js")).resolve("tsx")).href;
+
+/** A parent holding two git-repo children — the shape `isWorkspaceBuildRoot` detects. */
+function workspace(tag: string): string {
+ const parent = tmpRepo(tag);
+ for (const child of ["assign", "app.nanonets"]) {
+ mkdirSync(join(parent, child, ".git"), { recursive: true });
+ mkdirSync(join(parent, child, "src"), { recursive: true });
+ writeFileSync(join(parent, child, "src", "main.ts"), `export function ${child.replace(/\W/g, "")}Main(): number {\n return 1;\n}\n`);
+ }
+ return parent;
+}
+
+/** The CLI in a chosen cwd — `runCli` always runs in the project dir, and cwd is the point here. */
+function cliIn(cwd: string, args: string[], home: string) {
+ return spawnSync(process.execPath, ["--import", TSX, CLI, ...args], {
+ cwd,
+ encoding: "utf8",
+ timeout: 120_000,
+ env: homeEnv(home),
+ });
+}
+
+test("init at a workspace parent wires every child repo, not just the parent", () => {
+ const parent = workspace("init-ws");
+ const home = tmpRepo("init-ws-home");
+
+ const r = runCli(["init", parent, "--agents", "claude", "--no-build"], { home });
+ assert.equal(r.status, 0, r.describe());
+
+ for (const dir of [parent, join(parent, "assign"), join(parent, "app.nanonets")]) {
+ assert.ok(existsSync(join(dir, ".claude", "settings.json")), `${dir} settings.json`);
+ assert.ok(existsSync(join(dir, ".claude", "skills", "graft", "SKILL.md")), `${dir} skill`);
+ assert.ok(existsSync(join(dir, ".claude", "helpers", "graft-hooks.cjs")), `${dir} hooks shim`);
+ const mcp = JSON.parse(readFileSync(join(dir, ".mcp.json"), "utf8"));
+ assert.ok(mcp.mcpServers?.graft, `${dir} .mcp.json registers graft`);
+ }
+ assert.match(r.stderr, /workspace: wiring/, "must say it fanned out");
+});
+
+test("a plain repo is untouched by the fan-out — no child wiring, no workspace claims", () => {
+ const repo = tmpRepo("init-plain");
+ mkdirSync(join(repo, ".git"), { recursive: true });
+ mkdirSync(join(repo, "sub", ".git"), { recursive: true }); // a nested repo, but the parent has its OWN .git
+ const home = tmpRepo("init-plain-home");
+
+ const r = runCli(["init", repo, "--agents", "claude", "--no-build"], { home });
+ assert.equal(r.status, 0, r.describe());
+ assert.ok(existsSync(join(repo, ".claude", "settings.json")));
+ assert.ok(!existsSync(join(repo, "sub", ".claude")), "a submodule-shaped child must not be wired");
+ assert.doesNotMatch(r.stderr, /workspace: wiring/);
+});
+
+test("--dry-run lists the child repos' writes and writes nothing", () => {
+ const parent = workspace("init-ws-dry");
+ const home = tmpRepo("init-ws-dry-home");
+
+ const r = runCli(["init", parent, "--agents", "claude", "--dry-run"], { home });
+ assert.equal(r.status, 0, r.describe());
+ assert.match(r.stderr, /assign\/ \(workspace child\)/);
+ assert.match(r.stderr, /app\.nanonets\/ \(workspace child\)/);
+ assert.ok(!existsSync(join(parent, ".claude")), "--dry-run must not write");
+ assert.ok(!existsSync(join(parent, "assign", ".claude")), "--dry-run must not write to children");
+});
+
+test("a query from a subdirectory answers from the repo's graph one level up", () => {
+ const parent = workspace("walk-e2e");
+ const home = tmpRepo("walk-e2e-home");
+ const child = join(parent, "assign");
+
+ const built = runCli(["build", child], { home });
+ assert.equal(built.status, 0, built.describe());
+
+ const r = cliIn(join(child, "src"), ["map"], home);
+ assert.equal(r.status, 0, r.stderr);
+ assert.match(r.stderr, /no graft\/ here — answering from/, "the walk must announce itself");
+ assert.match(r.stdout + r.stderr, /main\.ts/, "must actually answer from the child's graph");
+});
+
+test("a query from the workspace parent still federates across children", () => {
+ const parent = workspace("walk-parent");
+ const home = tmpRepo("walk-parent-home");
+
+ const built = runCli(["build", parent], { home });
+ assert.equal(built.status, 0, built.describe());
+ assert.ok(existsSync(join(parent, "graft", "workspace.json")), "parent holds the children index");
+
+ const r = cliIn(parent, ["map"], home);
+ assert.equal(r.status, 0, r.stderr);
+ assert.doesNotMatch(r.stderr, /no graft\/ here/, "the parent IS a root — no walk");
+ assert.match(r.stdout, /assign\//, "federated output labels each child");
+});
diff --git a/test/graph-root.test.ts b/test/graph-root.test.ts
new file mode 100644
index 00000000..3a116e2a
--- /dev/null
+++ b/test/graph-root.test.ts
@@ -0,0 +1,74 @@
+/**
+ * `nearestGraftRoot` — the implicit root for a query that names no directory.
+ *
+ * The case that motivates it: an agent session (or a shell) opens in
+ * `<repo>/src/foo/`, where there is no `graft/`. Before the walk, every query
+ * resolved the context dir as `<cwd>/graft`, found nothing, and reported "no
+ * graph — run graft build" while the repo's graph sat two levels up.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { nearestGraftRoot, hasGraftIndex } from "../src/graph/root.js";
+import { tmpRepo } from "./helpers.js";
+
+/** A repo root with a wiring graph — the `graft build` shape. */
+function builtRepo(root: string): string {
+ mkdirSync(join(root, "graft", ".graph"), { recursive: true });
+ writeFileSync(join(root, "graft", ".graph", "wiring.json"), '{"version":1,"nodes":[],"edges":[]}\n');
+ return root;
+}
+
+/** A workspace parent — children index, no nodes/edges of its own. */
+function workspaceParent(root: string, children: string[]): string {
+ mkdirSync(join(root, "graft"), { recursive: true });
+ writeFileSync(join(root, "graft", "workspace.json"), JSON.stringify({ version: 1, children }) + "\n");
+ return root;
+}
+
+test("a subdirectory of a built repo resolves up to the repo root", () => {
+ const repo = builtRepo(tmpRepo("root-walk"));
+ const deep = join(repo, "src", "foo", "bar");
+ mkdirSync(deep, { recursive: true });
+
+ assert.deepEqual(nearestGraftRoot(deep), { root: repo, levels: 3 });
+ assert.deepEqual(nearestGraftRoot(repo), { root: repo, levels: 0 }, "the root itself must not walk");
+});
+
+test("a workspace parent counts as a root — workspace.json, no wiring.json", () => {
+ const parent = workspaceParent(tmpRepo("root-ws"), ["repoA", "repoB"]);
+ const scratch = join(parent, "scratch");
+ mkdirSync(scratch, { recursive: true });
+
+ assert.ok(hasGraftIndex(parent), "workspace.json alone makes a graft root");
+ assert.deepEqual(nearestGraftRoot(scratch), { root: parent, levels: 1 });
+});
+
+test("the NEAREST root wins — a built child inside a workspace parent, not the parent", () => {
+ const parent = workspaceParent(tmpRepo("root-nearest"), ["child"]);
+ const child = builtRepo(join(parent, "child"));
+ const deep = join(child, "src");
+ mkdirSync(deep, { recursive: true });
+
+ assert.deepEqual(nearestGraftRoot(deep), { root: child, levels: 1 }, "must stop at the child, not federate at the parent");
+});
+
+test("nothing indexed anywhere above → the start dir, so `build` in a fresh repo still means here", () => {
+ const fresh = tmpRepo("root-none");
+ const deep = join(fresh, "a", "b");
+ mkdirSync(deep, { recursive: true });
+
+ assert.deepEqual(nearestGraftRoot(deep), { root: deep, levels: 0 });
+});
+
+test("an explicit --dir override short-circuits the walk", () => {
+ const repo = builtRepo(tmpRepo("root-override"));
+ const deep = join(repo, "src");
+ mkdirSync(deep, { recursive: true });
+
+ // `contextDirFor` returns an override verbatim and ignores the root it is
+ // handed, so every ancestor would look equally indexed — the walk can only
+ // mislead here.
+ assert.deepEqual(nearestGraftRoot(deep, join(repo, "graft")), { root: deep, levels: 0 });
+});