Skip to content

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

feat: add opt-in indexing of nested git clones (#232)

Thibault Poignonec54dcfb37d2bc
diff --git a/README.md b/README.md
index 06d7a11b..b5c4ecef 100644
--- a/README.md
+++ b/README.md
@@ -337,6 +337,8 @@ graft build --extensions .ts .py # only include these code extensions
graft build --no-reuse # re-parse every file instead of replaying unchanged ones from cache
graft build --follow-submodules # include initialized submodules; persist the choice for builds + MCP refresh
graft build --no-follow-submodules # exclude submodules again and persist that choice (the default)
+graft build --follow-nested-repos # include nested git clones the index doesn't track; persist the choice
+graft build --no-follow-nested-repos # exclude nested clones again and persist that choice (the default)
graft ask "<task>" [dir] # query the graph — ranked nodes + exact file:line (no LLM, no key)
graft ask "<task>" --json # machine-readable result
@@ -455,6 +457,7 @@ Graft supports these layouts:
is saved in `.graft/config.json`, so later no-flag builds and MCP automatic
refreshes behave the same way. Run `graft build --no-follow-submodules` to
restore and persist the default boundary.
+- **A git repo with other repos cloned inside it** (no gitlink, no index entry) — the shape multi-repo manifest tools like `west`, `repo`, `gclient` and `tsrc` check dependencies out into, and the shape you get by cloning an upstream into the tree to patch it locally. `--follow-submodules` cannot reach these: they have no `160000` index entry to follow. Run `graft build --follow-nested-repos` to fold them into one graph, prefixing child paths (for example, `external/parser/src/index.ts`) while honoring each clone's own Git ignore rules. A clone at a git-ignored path stays absent, since Git never reports it. The choice is saved in `.graft/config.json` and is independent of `--follow-submodules` — neither flag implies the other. Run `graft build --no-follow-nested-repos` to restore and persist the default boundary. Prefer this over the multi-repo split below when the nested repos import from each other and you want those edges in one graph; prefer the split when you want each repo scored and refreshed on its own.
- **A folder of separate git repos** (no `.git` at the top) — `graft build`
auto-splits: each child gets its own (git-ignored) `graft/`, and the parent
gets a `graft/workspace.json` index. Queries from the parent federate across
diff --git a/src/cli.ts b/src/cli.ts
index 9c58253a..e7d1e694 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -313,6 +313,15 @@ program
"--no-follow-submodules",
"exclude Git submodules; persisted for later builds and automatic refreshes (default)",
)
+ .option(
+ "--follow-nested-repos",
+ "include nested Git clones the index does not track (a multi-repo manifest checkout, or any repo cloned into the tree) " +
+ "as ONE graph, so imports across them resolve; persisted for later builds and automatic refreshes",
+ )
+ .option(
+ "--no-follow-nested-repos",
+ "exclude untracked nested Git clones; persisted for later builds and automatic refreshes (default)",
+ )
.option(
"--include-dir <name>",
"override SKIP_DIRS for this repo's walks — repeatable (e.g. --include-dir build --include-dir tools); " +
@@ -341,6 +350,7 @@ program
includeDir?: string[];
onlyDir?: string[];
followSubmodules?: boolean;
+ followNestedRepos?: boolean;
gitignore?: boolean;
ignore?: boolean;
},
@@ -398,6 +408,10 @@ program
if (followSubmodulesWasExplicit && typeof opts.followSubmodules === "boolean") {
buildConfigPatch.followSubmodules = opts.followSubmodules;
}
+ const followNestedReposWasExplicit = command.getOptionValueSource("followNestedRepos") === "cli";
+ if (followNestedReposWasExplicit && typeof opts.followNestedRepos === "boolean") {
+ buildConfigPatch.followNestedRepos = opts.followNestedRepos;
+ }
if (Object.keys(buildConfigPatch).length > 0) {
patchBuildConfig(resolve(dir), buildConfigPatch);
}
@@ -437,6 +451,7 @@ program
override: buildGlobalDir,
includeDirs: opts.includeDir,
followSubmodules: followSubmodulesWasExplicit ? opts.followSubmodules : undefined,
+ followNestedRepos: followNestedReposWasExplicit ? opts.followNestedRepos : undefined,
});
return;
}
diff --git a/src/context/build.ts b/src/context/build.ts
index 1bfd1625..ff2a9d0d 100644
--- a/src/context/build.ts
+++ b/src/context/build.ts
@@ -17,7 +17,7 @@ import { walkDir } from "../ingest/fs.js";
import { contentHash } from "../util/id.js";
import { relPosix } from "../util/paths.js";
import { readSourceFile } from "../util/source.js";
-import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";
+import { readFollowNestedRepos, readFollowSubmodules, readIncludeDirs } from "../util/state.js";
import type { Summarizer } from "../ai/summarize.js";
import { LlmFailureGate } from "../ai/failure.js";
import type { FileSummary, SynthNode, Synthesizer } from "../ai/synthesize.js";
@@ -116,6 +116,7 @@ export async function buildContext(dir: string, opts: BuildOptions): Promise<Bui
// Tier-2 concept pipeline sees exactly the same directories and submodules.
const files = walkDir(root, readIncludeDirs(root), {
followSubmodules: readFollowSubmodules(root),
+ followNestedRepos: readFollowNestedRepos(root),
})
.filter((f) => exts.some((e) => f.toLowerCase().endsWith(e)))
.filter((f) => !f.startsWith(outDir));
diff --git a/src/context/check.ts b/src/context/check.ts
index d446f8d9..3784eb5d 100644
--- a/src/context/check.ts
+++ b/src/context/check.ts
@@ -18,7 +18,7 @@ import { walkDir } from "../ingest/fs.js";
import { contentHash } from "../util/id.js";
import { relPosix } from "../util/paths.js";
import { readSourceFile } from "../util/source.js";
-import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";
+import { readFollowNestedRepos, readFollowSubmodules, readIncludeDirs } from "../util/state.js";
import { CODE_EXTENSIONS } from "./build.js";
import { contextDirFor, readManifest, readNodes } from "./node-file.js";
@@ -63,6 +63,7 @@ export function checkContext(dir: string, opts: CheckOptions = {}): CheckResult
const current = new Map<string, string>(); // rel → hash
for (const file of walkDir(root, readIncludeDirs(root), {
followSubmodules: readFollowSubmodules(root),
+ followNestedRepos: readFollowNestedRepos(root),
})) {
if (file.startsWith(outDir)) continue;
if (!exts.some((e) => file.toLowerCase().endsWith(e))) continue;
diff --git a/src/graph/build.ts b/src/graph/build.ts
index 0ea1ca0c..b3094051 100644
--- a/src/graph/build.ts
+++ b/src/graph/build.ts
@@ -23,7 +23,7 @@ import { containerLangOf, extractContainer, warmContainerGrammars } from "./cont
import { contentHash } from "../util/id.js";
import { relPosix } from "../util/paths.js";
import { readSourceFile } from "../util/source.js";
-import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";
+import { readFollowNestedRepos, readFollowSubmodules, readIncludeDirs } from "../util/state.js";
import {
emptyExtractCache,
readExtractCache,
@@ -159,6 +159,7 @@ export async function buildGraph(
// including the repo's persisted directory and submodule choices.
const walked = walkDir(root, readIncludeDirs(root), {
followSubmodules: readFollowSubmodules(root),
+ followNestedRepos: readFollowNestedRepos(root),
});
const onlyDirs = opts.onlyDirs && opts.onlyDirs.length > 0 ? new Set(opts.onlyDirs) : undefined;
const repoFiles = filterByOnlyDirs(walked, root, onlyDirs);
diff --git a/src/graph/scopes.ts b/src/graph/scopes.ts
index 915aa188..e69a0713 100644
--- a/src/graph/scopes.ts
+++ b/src/graph/scopes.ts
@@ -25,7 +25,7 @@ import { existsSync, readdirSync, readFileSync, type Dirent } from "node:fs";
import { join, resolve } from "node:path";
import { shouldSkipDir, walkDir } from "../ingest/fs.js";
import { relPosix } from "../util/paths.js";
-import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";
+import { readFollowNestedRepos, readFollowSubmodules, readIncludeDirs } from "../util/state.js";
import type { GraphV1, ScopeV1 } from "./types.js";
/** Project-marker files, checked in this order (also the order `markers` is built in). */
@@ -134,6 +134,7 @@ export function discoverScopes(
root: string,
repoFiles: string[] = walkDir(root, readIncludeDirs(resolve(root)), {
followSubmodules: readFollowSubmodules(resolve(root)),
+ followNestedRepos: readFollowNestedRepos(resolve(root)),
}),
): ScopeV1[] {
const absRoot = resolve(root);
diff --git a/src/graph/source-files.ts b/src/graph/source-files.ts
index 11fa81db..b5d7c338 100644
--- a/src/graph/source-files.ts
+++ b/src/graph/source-files.ts
@@ -10,7 +10,7 @@ import { statSync } from "node:fs";
import { resolve } from "node:path";
import { walkDir } from "../ingest/fs.js";
import { relPosix } from "../util/paths.js";
-import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";
+import { readFollowNestedRepos, readFollowSubmodules, readIncludeDirs } from "../util/state.js";
import { languageOf, depthExtensions } from "./extract.js";
import { genericLangOf, genericExtensions } from "./generic.js";
import { containerLangOf, containerExtensions } from "./container.js";
@@ -66,6 +66,7 @@ export function listSourceFiles(
outDir: string,
repoFiles: string[] = walkDir(root, readIncludeDirs(resolve(root)), {
followSubmodules: readFollowSubmodules(resolve(root)),
+ followNestedRepos: readFollowNestedRepos(resolve(root)),
}),
onlyDirs?: ReadonlySet<string>,
): string[] {
diff --git a/src/graph/workspace-cli.ts b/src/graph/workspace-cli.ts
index efb23727..f6dc57e8 100644
--- a/src/graph/workspace-cli.ts
+++ b/src/graph/workspace-cli.ts
@@ -38,6 +38,8 @@ export interface WorkspaceBuildOptions {
includeDirs?: string[];
/** An explicit CLI submodule choice to persist into every child repo. */
followSubmodules?: boolean;
+ /** An explicit CLI nested-clone choice to persist into every child repo. */
+ followNestedRepos?: boolean;
}
/** Build every git child into its own committable `graft/`, then replace the
@@ -54,6 +56,9 @@ export async function runWorkspaceBuild(root: string, opts: WorkspaceBuildOption
if (opts.followSubmodules !== undefined) {
childConfigPatch.followSubmodules = opts.followSubmodules;
}
+ if (opts.followNestedRepos !== undefined) {
+ childConfigPatch.followNestedRepos = opts.followNestedRepos;
+ }
if (Object.keys(childConfigPatch).length > 0) {
patchBuildConfig(childDir, childConfigPatch);
}
diff --git a/src/ingest/fs.ts b/src/ingest/fs.ts
index 83048f55..940ff3a0 100644
--- a/src/ingest/fs.ts
+++ b/src/ingest/fs.ts
@@ -59,17 +59,31 @@ export function shouldSkipDir(name: string, includes?: ReadonlySet<string>): boo
* `includes`, and files over 1 MB.
* In a Git worktree, tracked files plus untracked, non-ignored files come from
* `git ls-files`; this gives indexing exactly Git's nested `.gitignore`,
- * negation, and global-exclude semantics. Initialized submodules are enumerated
- * recursively only when `followSubmodules` is true; the default preserves the
- * historical superproject boundary. Each child keeps its own ignore rules, and
- * uninitialized submodules remain absent. Non-Git directories retain the plain
+ * negation, and global-exclude semantics. Non-Git directories retain the plain
* filesystem walk. `includes` lifts only the built-in skip list — it never
* overrides Git's ignore rules (un-ignore or `git add -f` a directory to
* index it, the same contract as tracked-but-ignored files).
+ *
+ * Two INDEPENDENT opt-ins cross the repository boundary, because Git models two
+ * different relationships and only one of them is a dependency the parent pins:
+ *
+ * - `followSubmodules` follows a GITLINK — an index entry with mode `160000`,
+ * a commit the superproject versions.
+ * - `followNestedRepos` follows a nested clone the parent's index knows
+ * nothing about. Manifest-driven multi-repo tools (west, repo, gclient,
+ * tsrc, mr, …) all check dependencies out this way, and so does anyone who
+ * clones an upstream into the tree to patch it locally.
+ *
+ * Both default to false, preserving the historical superproject boundary. Each
+ * child keeps its own ignore rules; uninitialized submodules and gitignored
+ * nested clones remain absent either way (`--exclude-standard` never emits
+ * them, so there is nothing to follow).
*/
export interface WalkOptions {
- /** Include initialized Git submodules recursively. Default false. */
+ /** Include initialized Git submodules (gitlinks) recursively. Default false. */
followSubmodules?: boolean;
+ /** Include nested Git clones the parent index does not track. Default false. */
+ followNestedRepos?: boolean;
}
export function walkDir(
@@ -77,7 +91,7 @@ export function walkDir(
includes?: ReadonlySet<string>,
opts: WalkOptions = {},
): string[] {
- return gitVisibleFiles(dir, includes, opts.followSubmodules === true) ?? walkFilesystem(dir, includes);
+ return gitVisibleFiles(dir, includes, opts) ?? walkFilesystem(dir, includes);
}
/** Git's canonical working-tree file set, relative to `dir`. Tracked files are
@@ -86,11 +100,16 @@ export function walkDir(
function gitVisibleFiles(
dir: string,
includes?: ReadonlySet<string>,
- followSubmodules = false,
+ opts: WalkOptions = {},
traversal?: { topRoot: string; activeRoots: Set<string> },
): string[] | null {
const root = resolve(dir);
- if (!followSubmodules) return gitVisibleFilesShallow(root, includes);
+ // The recursive path costs an extra `-t --stage` classification, so take it
+ // only when at least one boundary-crossing opt-in is on. With both off the
+ // walk is byte-for-byte the historical one.
+ if (opts.followSubmodules !== true && opts.followNestedRepos !== true) {
+ return gitVisibleFilesShallow(root, includes);
+ }
const state = traversal ?? { topRoot: root, activeRoots: new Set<string>() };
const rootKey = process.platform === "win32" ? root.toLowerCase() : root;
@@ -115,8 +134,9 @@ function gitVisibleFiles(
}
// A path can have multiple stage records during a merge. Collapse those
- // records and remember if any of them identifies the path as a gitlink.
- const entries = new Map<string, { gitlink: boolean }>();
+ // records and remember if any of them identifies the path as a gitlink or as
+ // a nested-clone boundary.
+ const entries = new Map<string, { gitlink: boolean; nested: boolean }>();
for (const record of result.stdout.split("\0")) {
if (!record) continue;
if (record.length < 2 || record[1] !== " ") continue;
@@ -125,8 +145,17 @@ function gitVisibleFiles(
const body = record.slice(2);
let rel: string;
let gitlink = false;
+ let nested = false;
if (tag === "?") {
rel = body;
+ // Git refuses to descend into a repository it does not own, so `--others`
+ // collapses a nested clone to ONE trailing-slash directory entry while
+ // every other untracked directory is expanded file by file. That slash is
+ // the boundary marker — free, since this is the enumeration we already ran.
+ if (rel.endsWith("/")) {
+ nested = true;
+ rel = rel.slice(0, -1);
+ }
} else {
const tab = body.indexOf("\t");
if (tab === -1) continue;
@@ -135,7 +164,10 @@ function gitVisibleFiles(
}
if (!rel) continue;
const prior = entries.get(rel);
- entries.set(rel, { gitlink: gitlink || prior?.gitlink === true });
+ entries.set(rel, {
+ gitlink: gitlink || prior?.gitlink === true,
+ nested: nested || prior?.nested === true,
+ });
}
const out = new Set<string>();
@@ -146,12 +178,16 @@ function gitVisibleFiles(
// recursion resets its relative root.
if (skippedPath(relative(state.topRoot, abs), includes)) continue;
- if (entry.gitlink) {
+ const followChild =
+ (entry.gitlink && opts.followSubmodules === true) ||
+ (entry.nested && opts.followNestedRepos === true);
+ if (followChild) {
// A deinitialized gitlink can resolve upward to the superproject when Git
- // runs inside it. Requiring the child's own .git prevents duplicate,
- // mis-prefixed parent files and recursive loops.
+ // runs inside it, and a nested-looking directory may have no repo at all.
+ // Requiring the child's own .git prevents duplicate, mis-prefixed parent
+ // files and recursive loops.
if (!existsSync(join(abs, ".git"))) continue;
- let childFiles = gitVisibleFiles(abs, includes, true, state);
+ let childFiles = gitVisibleFiles(abs, includes, opts, state);
if (childFiles === null) {
// Do not let one broken child recreate a "healthy but incomplete"
// graph. Match the top-level fail-soft contract locally: fall back to
diff --git a/src/util/state.ts b/src/util/state.ts
index 24888710..ae0d7105 100644
--- a/src/util/state.ts
+++ b/src/util/state.ts
@@ -91,9 +91,17 @@ export interface BuildConfig {
* no-flag build — and the fingerprint/refresh path, which never sees CLI
* flags at all — behave identically to the invocation that set it. */
includeDirs?: string[];
- /** Whether initialized Git submodules are folded into this repo's graph.
- * Absent/false keeps the historical boundary at the superproject. */
+ /** Whether initialized Git submodules (gitlinks) are folded into this repo's
+ * graph. Absent/false keeps the historical boundary at the superproject. */
followSubmodules?: boolean;
+ /** Whether nested Git clones the index does not track — how manifest-driven
+ * multi-repo tools check dependencies out, and how an ad-hoc local clone lands
+ * in the tree — are folded into this repo's graph. Deliberately SEPARATE from
+ * `followSubmodules`: a submodule is a dependency the parent pins, a nested
+ * clone is invisible to the parent's index and may equally be a scratch
+ * checkout someone parked in the tree. Absent/false keeps the historical
+ * boundary. */
+ followNestedRepos?: boolean;
}
/** Local, Git-ignored repository configuration. Kept outside generated
@@ -145,6 +153,11 @@ export function readIncludeDirs(d: string): Set<string> | undefined {
export function readFollowSubmodules(d: string): boolean {
return readBuildConfig(d)?.followSubmodules === true;
}
+
+/** Missing and explicit false both retain the backwards-compatible default. */
+export function readFollowNestedRepos(d: string): boolean {
+ return readBuildConfig(d)?.followNestedRepos === true;
+}
// Best-effort read-modify-write; not atomic across concurrent processes, but acceptable
// for episodic hook writes (worst case is a lost update, not corruption).
export function patchStats(d: string, patch: Partial<Stats>): Stats {
diff --git a/test/graph-follow-nested-repos.test.ts b/test/graph-follow-nested-repos.test.ts
new file mode 100644
index 00000000..b9eb52d3
--- /dev/null
+++ b/test/graph-follow-nested-repos.test.ts
@@ -0,0 +1,193 @@
+import { execFileSync } from "node:child_process";
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { isClean, probeDrift } from "../src/graph/fingerprint.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+import { readBuildConfig } from "../src/util/state.js";
+import type { GraphV1 } from "../src/graph/types.js";
+import { runCli, tmpRepo } from "./helpers.js";
+
+function gitRun(root: string, args: string[]): void {
+ execFileSync("git", args, { cwd: root, stdio: "ignore" });
+}
+
+function commitAll(root: string, message: string): void {
+ gitRun(root, ["add", "-A"]);
+ gitRun(root, [
+ "-c", "user.name=Graft Tests",
+ "commit", "-qm", message,
+ ]);
+}
+
+function graphOf(root: string): GraphV1 {
+ const graph = readGraph(wiringPath(join(root, "graft")));
+ assert.ok(graph, `expected a graph for ${root}`);
+ return graph;
+}
+
+function expectCliOk(args: string[]): void {
+ const result = runCli(args);
+ assert.equal(result.status, 0, result.describe());
+}
+
+function write(root: string, rel: string, body: string): void {
+ const abs = join(root, rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, body);
+}
+
+/**
+ * A multi-repo manifest checkout clones dependencies into the parent tree as
+ * ORDINARY repos, with no gitlink and no index entry — so `followSubmodules`
+ * can never reach them. Built here with a plain `git init` inside the parent.
+ */
+test("follow-nested-repos is opt-in, persisted, reversible, and does not mistake a plain untracked dir for a repo", () => {
+ const parent = tmpRepo("follow-nested-parent");
+ try {
+ gitRun(parent, ["init", "-q"]);
+ write(parent, "src/root.ts", "export const rootValue = 1;\n");
+ // A plain untracked directory: git expands it file by file, so it must NOT
+ // trip the trailing-slash heuristic. This is the regression guard.
+ write(parent, "plain/a.ts", "export const plainValue = 1;\n");
+ write(parent, "plain/deep/b.ts", "export const deepPlainValue = 1;\n");
+ // A directory that looks like a checkout but has no .git — must be skipped,
+ // not recursed. Git expands it too (it is not a repo), so its files land in
+ // the graph the ordinary way.
+ write(parent, "external/not_a_repo/c.ts", "export const notARepoValue = 1;\n");
+ commitAll(parent, "parent fixture");
+
+ // Two nested clones, the second importing from the first — the cross-repo
+ // edge is the whole point of folding them into ONE graph rather than
+ // federating them into N disjoint ones.
+ const depA = join(parent, "external", "dep_a");
+ mkdirSync(depA, { recursive: true });
+ gitRun(depA, ["init", "-q"]);
+ write(depA, "src/api.ts", "export function depAValue(): number { return 1; }\n");
+ write(depA, "build/generated.ts", "export const generatedValue = 1;\n");
+ commitAll(depA, "dep_a fixture");
+
+ const depB = join(parent, "external", "dep_b");
+ mkdirSync(depB, { recursive: true });
+ gitRun(depB, ["init", "-q"]);
+ write(
+ depB,
+ "src/consumer.ts",
+ 'import { depAValue } from "../../dep_a/src/api.js";\n' +
+ "export function depBValue(): number { return depAValue(); }\n",
+ );
+ commitAll(depB, "dep_b fixture");
+
+ // 1. Default build excludes both nested clones and keeps everything else.
+ expectCliOk(["build", parent]);
+ const def = graphOf(parent);
+ assert.ok(def.nodes.some((n) => n.path === "src/root.ts"));
+ assert.ok(def.nodes.some((n) => n.path === "plain/a.ts"), "a plain untracked dir must still be expanded");
+ assert.ok(def.nodes.some((n) => n.path === "plain/deep/b.ts"));
+ assert.ok(def.nodes.some((n) => n.path === "external/not_a_repo/c.ts"));
+ assert.ok(!def.nodes.some((n) => n.path.startsWith("external/dep_a/")));
+ assert.ok(!def.nodes.some((n) => n.path.startsWith("external/dep_b/")));
+ assert.equal(
+ existsSync(join(parent, ".graft", "config.json")),
+ false,
+ "an implicit default must not create local config",
+ );
+
+ // 2. Opt in: both clones are indexed, into the SAME graph, and the choice
+ // is persisted. SKIP_DIRS still applies inside the child (build/).
+ expectCliOk(["build", parent, "--follow-nested-repos"]);
+ const enabled = graphOf(parent);
+ assert.ok(enabled.nodes.some((n) => n.id === "external/dep_a/src/api.ts#depAValue"));
+ assert.ok(enabled.nodes.some((n) => n.id === "external/dep_b/src/consumer.ts#depBValue"));
+ assert.ok(
+ !enabled.nodes.some((n) => n.path.startsWith("external/dep_a/build/")),
+ "SKIP_DIRS must still apply inside a followed nested repo",
+ );
+ assert.deepEqual(readBuildConfig(parent), { followNestedRepos: true });
+ assert.ok(isClean(probeDrift(parent, join(parent, "graft"))!));
+
+ // 3. The cross-repo edge: one graph, so dep_b's import resolves into dep_a.
+ assert.ok(
+ enabled.edges.some(
+ (e) =>
+ e.relation === "imports" &&
+ e.source === "external/dep_b/src/consumer.ts" &&
+ e.target === "external/dep_a/src/api.ts",
+ ),
+ "an import crossing two nested repos must resolve to an in-graph edge",
+ );
+
+ // 4. A later no-flag rebuild retains the opt-in — the contract the
+ // fingerprint probe and the MCP refresh path depend on.
+ expectCliOk(["build", parent]);
+ assert.ok(
+ graphOf(parent).nodes.some((n) => n.id === "external/dep_a/src/api.ts#depAValue"),
+ "a no-flag build must retain the persisted opt-in",
+ );
+
+ // 5. Explicitly reversible, and likewise persisted.
+ expectCliOk(["build", parent, "--no-follow-nested-repos"]);
+ assert.ok(!graphOf(parent).nodes.some((n) => n.path.startsWith("external/dep_a/")));
+ assert.deepEqual(readBuildConfig(parent), { followNestedRepos: false });
+ assert.ok(isClean(probeDrift(parent, join(parent, "graft"))!));
+
+ expectCliOk(["build", parent]);
+ assert.ok(!graphOf(parent).nodes.some((n) => n.path.startsWith("external/dep_a/")));
+ assert.deepEqual(readBuildConfig(parent), { followNestedRepos: false });
+ } finally {
+ rmSync(parent, { recursive: true, force: true });
+ }
+});
+
+/** The two opt-ins are independent: neither implies the other. */
+test("follow-nested-repos and follow-submodules are independent switches", () => {
+ const parent = tmpRepo("follow-nested-mixed-parent");
+ const sub = tmpRepo("follow-nested-mixed-sub");
+ try {
+ gitRun(sub, ["init", "-q"]);
+ write(sub, "src/sub.ts", "export function subValue(): number { return 1; }\n");
+ commitAll(sub, "submodule fixture");
+
+ gitRun(parent, ["init", "-q"]);
+ write(parent, "src/root.ts", "export const rootValue = 1;\n");
+ commitAll(parent, "parent fixture");
+ gitRun(parent, [
+ "-c", "protocol.file.allow=always",
+ "submodule", "add", "-q", sub.replace(/\\/g, "/"), "modules/sub",
+ ]);
+ commitAll(parent, "add submodule");
+
+ const nested = join(parent, "external", "dep");
+ mkdirSync(nested, { recursive: true });
+ gitRun(nested, ["init", "-q"]);
+ write(nested, "src/dep.ts", "export function depValue(): number { return 1; }\n");
+ commitAll(nested, "nested fixture");
+
+ // Nested only: the gitlink stays outside the boundary.
+ expectCliOk(["build", parent, "--follow-nested-repos"]);
+ const nestedOnly = graphOf(parent);
+ assert.ok(nestedOnly.nodes.some((n) => n.id === "external/dep/src/dep.ts#depValue"));
+ assert.ok(!nestedOnly.nodes.some((n) => n.path.startsWith("modules/sub/")));
+
+ // Submodules only: the nested clone stays outside the boundary.
+ expectCliOk(["build", parent, "--no-follow-nested-repos", "--follow-submodules"]);
+ const g = graphOf(parent);
+ assert.ok(g.nodes.some((n) => n.id === "modules/sub/src/sub.ts#subValue"));
+ assert.ok(!g.nodes.some((n) => n.path.startsWith("external/dep/")));
+ assert.deepEqual(readBuildConfig(parent), {
+ followNestedRepos: false,
+ followSubmodules: true,
+ });
+
+ // Both: one graph spanning both kinds of boundary.
+ expectCliOk(["build", parent, "--follow-nested-repos"]);
+ const both = graphOf(parent);
+ assert.ok(both.nodes.some((n) => n.id === "modules/sub/src/sub.ts#subValue"));
+ assert.ok(both.nodes.some((n) => n.id === "external/dep/src/dep.ts#depValue"));
+ } finally {
+ rmSync(parent, { recursive: true, force: true });
+ rmSync(sub, { recursive: true, force: true });
+ }
+});