Skip to content

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

fix(check): root source file cards must not collide with concept slugs (#261) (#263)

Frankie-Xu6fa46e383358
diff --git a/src/context/node-file.ts b/src/context/node-file.ts
index 90b6ba69..3162069d 100644
--- a/src/context/node-file.ts
+++ b/src/context/node-file.ts
@@ -266,6 +266,10 @@ export interface ParsedNode {
* for source files in the repo root. Those cards share a directory with concept
* nodes (`graft/<stem>.md`) but are recorded in `manifest.files`, not
* `manifest.nodes`. Nested file cards live in subdirs and are never scanned here.
+ *
+ * Incomplete on its own (#261): the graph can write a root card for a source
+ * that the concept pipeline never recorded (different extension lists), so the
+ * stem is absent from `manifest.files`. Combined with isRootFileCard().
*/
function rootFileCardStems(dir: string): Set<string> {
const manifest = readManifest(dir);
@@ -278,20 +282,53 @@ function rootFileCardStems(dir: string): Set<string> {
return stems;
}
+function hasConceptSlug(fm: Record<string, unknown>): boolean {
+ return fm.slug != null && String(fm.slug).length > 0;
+}
+
+/** `writeCovers` used to stamp `covers: []` onto slug-less root file cards. */
+function isCoversOnlyFileCard(fm: Record<string, unknown>): boolean {
+ if (hasConceptSlug(fm) || !("covers" in fm)) return false;
+ return fm.name == null && fm.type == null && fm.sources == null;
+}
+
+/** Wiring cards start with `# <source path with extension>`, optionally followed
+ * by ` · [[slug]]` up-links. A hand-dropped `notes.md` does not. */
+function isWiringCardHeading(content: string): boolean {
+ const line = content.trimStart().split(/\r?\n/, 1)[0] ?? "";
+ return /^# [^\s#]+\.[A-Za-z0-9]{1,12}(?:\s|$)/.test(line);
+}
+
+/**
+ * A top-level `.md` that is a per-file wiring card, not a concept node.
+ * Real concepts always carry `slug` in frontmatter and are never skipped.
+ * A hand-dropped `notes.md` has no slug, no `covers`, and no file-path heading,
+ * so it still surfaces as indexDrift (#215 / #261).
+ */
+function isRootFileCard(
+ stem: string,
+ fm: Record<string, unknown>,
+ content: string,
+ fileCardStems: Set<string>,
+): boolean {
+ if (hasConceptSlug(fm)) return false;
+ if (fileCardStems.has(stem)) return true;
+ if (isCoversOnlyFileCard(fm)) return true;
+ return isWiringCardHeading(content);
+}
+
/** Read and parse every concept-node `.md` in a context dir (skips INDEX.md
- * and root-level per-file cards already recorded in `manifest.files`). */
+ * and root-level per-file cards). */
export function readNodes(dir: string): ParsedNode[] {
if (!existsSync(dir)) return [];
const fileCardStems = rootFileCardStems(dir);
const out: ParsedNode[] = [];
for (const entry of readdirSync(dir)) {
if (!entry.endsWith(".md") || entry === "INDEX.md") continue;
- const fm = matter(readFileSync(join(dir, entry), "utf8")).data as Record<string, unknown>;
+ const parsed = matter(readFileSync(join(dir, entry), "utf8"));
+ const fm = parsed.data as Record<string, unknown>;
const fallbackSlug = entry.replace(/\.md$/, "");
- // A root-level file card has no concept `slug` and its stem matches a
- // recorded source file. Skipping it here (instead of all slug-less `.md`)
- // keeps a hand-dropped notes.md visible to check's indexDrift detector.
- if (fileCardStems.has(fallbackSlug) && fm.slug == null) continue;
+ if (isRootFileCard(fallbackSlug, fm, parsed.content, fileCardStems)) continue;
out.push({
slug: String(fm.slug ?? fallbackSlug),
name: String(fm.name ?? ""),
diff --git a/src/graph/cards.ts b/src/graph/cards.ts
index ccface79..cb4b6a3e 100644
--- a/src/graph/cards.ts
+++ b/src/graph/cards.ts
@@ -23,6 +23,9 @@ import { CACHE_DIR, readNodes } from "../context/node-file.js";
import { GRAPH_DIR } from "./write.js";
const INDEX_FILE = "INDEX.md";
+/** Where a root-level file card goes when `graft/<stem>.md` is already a concept
+ * node (same stem as a slug — Laravel `server.php` vs a "Server" concept). */
+const ROOT_CARD_DIR = "_root";
export interface CardFileInfo {
/** Card path relative to the context dir, e.g. "src/ai/providers.md". */
@@ -38,10 +41,26 @@ export interface CardStats {
files: CardFileInfo[];
}
-/** The card path for a source path: mirror the tree, swap the extension for .md. */
+/** True when `path` is an existing concept node (frontmatter carries `slug`). */
+function isConceptNodeFile(path: string): boolean {
+ if (!existsSync(path)) return false;
+ try {
+ const fm = matter(readFileSync(path, "utf8")).data as Record<string, unknown>;
+ return fm.slug != null && String(fm.slug).length > 0;
+ } catch {
+ return false;
+ }
+}
+
+/** The card path for a source path: mirror the tree, swap the extension for .md.
+ * Root-level sources share `graft/` with concept nodes. If that filename is
+ * already a concept, park the file card under `_root/` instead of clobbering it. */
function cardPathFor(outDir: string, sourcePath: string): string {
const md = sourcePath.replace(/\.[^./]+$/, "") + ".md";
- return join(outDir, md);
+ const primary = join(outDir, md);
+ if (sourcePath.includes("/")) return primary;
+ if (isConceptNodeFile(primary)) return join(outDir, ROOT_CARD_DIR, md);
+ return primary;
}
/** Starting line of an "L43-L55" span, for stable ordering (0 if unparseable). */
@@ -113,7 +132,8 @@ function listExistingCards(outDir: string): string[] {
}
};
for (const e of readdirSync(outDir, { withFileTypes: true })) {
- // Concept nodes and INDEX.md are top-level files — skip. Cards are in subdirs.
+ // Concept nodes and INDEX.md are top-level files — skip. Cards live in
+ // subdirs (`src/…`, and `_root/` when a root card would collide with a concept).
if (e.isDirectory() && e.name !== CACHE_DIR && e.name !== GRAPH_DIR) {
walk(join(outDir, e.name));
}
@@ -247,9 +267,10 @@ export interface CoverRef {
*
* A surgical frontmatter patch: the generated body and every other key are
* preserved verbatim; only `covers` is added/replaced. Concept nodes are the
- * top-level `.md` files (cards live in subdirs; INDEX.md is skipped). On a $0
- * structure-only build there are no concept nodes, so this is a no-op. Returns
- * the number of nodes enriched.
+ * top-level `.md` files that carry a `slug` (cards live in subdirs, or at the
+ * top level without a slug when they mirror a root source; INDEX.md is skipped).
+ * On a $0 structure-only build there are no concept nodes, so this is a no-op.
+ * Returns the number of nodes enriched.
*/
export function writeCovers(graph: GraphV1, outDir: string): number {
if (!existsSync(outDir)) return 0;
@@ -270,6 +291,9 @@ export function writeCovers(graph: GraphV1, outDir: string): number {
if (!entry.endsWith(".md") || entry === INDEX_FILE) continue;
const full = join(outDir, entry);
const parsed = matter(readFileSync(full, "utf8"));
+ // Root-level file cards have no concept slug; stamping `covers: []` onto
+ // them made readNodes treat them as concept nodes (#261).
+ if (parsed.data.slug == null || String(parsed.data.slug).length === 0) continue;
const sources = Array.isArray(parsed.data.sources)
? (parsed.data.sources as Array<{ path?: string }>)
: [];
diff --git a/test/context.test.ts b/test/context.test.ts
index 2ed88135..cf875040 100644
--- a/test/context.test.ts
+++ b/test/context.test.ts
@@ -133,6 +133,102 @@ test("check: root-level file card is not indexDrift after build (#213)", async (
}
});
+// #261 — same collision as #213, two holes #215's skip does not cover:
+// 1. A concept slug equal to the root file's stem (Laravel `server.php` vs
+// a synthesized "Server" node). writeCards must not clobber the concept.
+// 2. A root file card whose source is not in manifest.files (#215 only
+// skips stems recorded there). Graph-indexed extras (e.g. .lua) still
+// land at graft/<stem>.md and must not become indexDrift.
+test("check: root PHP file card is not indexDrift after build (#261)", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "ctxgraph-root-php-"));
+ try {
+ writeFileSync(join(dir, "server.php"), `<?php\nfunction hi() { return 1; }\n`);
+ mkdirSync(join(dir, "lib"));
+ writeFileSync(join(dir, "lib", "deep.php"), `<?php\nfunction deep() { return 2; }\n`);
+
+ await buildContext(dir, buildOpts());
+ await buildGraph(dir);
+
+ assert.ok(existsSync(join(dir, "graft", "server.md")), "root php source gets a top-level file card");
+ assert.ok(existsSync(join(dir, "graft", "lib", "deep.md")), "nested php card stays in a subdir");
+
+ const r = checkContext(dir);
+ assert.equal(r.ok, true, `expected clean check, got ${JSON.stringify(r)}`);
+ assert.deepEqual(r.indexDrift, []);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("check: root file card must not overwrite a concept with the same slug (#261)", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "ctxgraph-root-collide-"));
+ try {
+ writeFileSync(
+ join(dir, "server.php"),
+ `<?php\n// [[Server]] ==depends_on==> [[Router]]\nfunction hi() { return 1; }\n`,
+ );
+ mkdirSync(join(dir, "lib"));
+ writeFileSync(
+ join(dir, "lib", "router.php"),
+ `<?php\n// [[Router]]\nfunction route() { return 2; }\n`,
+ );
+
+ await buildContext(dir, buildOpts());
+ assert.match(
+ readFileSync(join(dir, "graft", "server.md"), "utf8"),
+ /^slug:\s*server\s*$/m,
+ "context build writes a concept node at graft/server.md",
+ );
+
+ await buildGraph(dir);
+
+ const concept = readFileSync(join(dir, "graft", "server.md"), "utf8");
+ assert.match(concept, /^slug:\s*server\s*$/m, "file card must not clobber the concept node");
+ assert.ok(
+ existsSync(join(dir, "graft", "_root", "server.md")),
+ "root file card relocates to graft/_root/ when the stem is a concept slug",
+ );
+ assert.match(readFileSync(join(dir, "graft", "_root", "server.md"), "utf8"), /^# server\.php/m);
+
+ const r = checkContext(dir);
+ assert.equal(r.ok, true, `expected clean check, got ${JSON.stringify(r)}`);
+ assert.deepEqual(r.indexDrift, []);
+
+ writeFileSync(join(dir, "graft", "notes.md"), "# stray notes\n");
+ const stray = checkContext(dir);
+ assert.equal(stray.ok, false);
+ assert.ok(
+ stray.indexDrift.some((s) => s.startsWith("notes:")),
+ `expected stray notes.md to be indexDrift, got ${JSON.stringify(stray.indexDrift)}`,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("check: root file card not in manifest.files is not indexDrift (#261)", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "ctxgraph-root-extra-"));
+ try {
+ // .lua is graph-indexed but not a context CODE_EXTENSIONS, so the card is
+ // written and the source never appears in manifest.files — #215's skip
+ // keyed on recorded root sources misses it.
+ writeFileSync(join(dir, "server.lua"), `function hi() return 1 end\n`);
+ mkdirSync(join(dir, "lib"));
+ writeFileSync(join(dir, "lib", "deep.ts"), `export function deep() { return 2; }\n`);
+
+ await buildContext(dir, buildOpts());
+ await buildGraph(dir);
+
+ assert.ok(existsSync(join(dir, "graft", "server.md")), "graph still writes a root file card");
+
+ const r = checkContext(dir);
+ assert.equal(r.ok, true, `expected clean check, got ${JSON.stringify(r)}`);
+ assert.deepEqual(r.indexDrift, []);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test("check reports NO GRAPH when init never ran", () => {
const dir = mkdtempSync(join(tmpdir(), "ctxgraph-"));
try {
diff --git a/test/covers.test.ts b/test/covers.test.ts
index 6a9139fa..0d34c8f2 100644
--- a/test/covers.test.ts
+++ b/test/covers.test.ts
@@ -61,6 +61,20 @@ test("patching covers preserves the node's body and other frontmatter", async ()
}
});
+test("writeCovers does not stamp covers onto a root-level file card (#261)", async () => {
+ const dir = makeFixture();
+ try {
+ await buildContext(dir, { model: "fake", ...fakeProviders() });
+ await buildGraph(dir);
+ const card = matter(readFileSync(join(dir, "graft", "auth.md"), "utf8"));
+ assert.equal(card.data.slug, undefined, "file card has no concept slug");
+ assert.ok(!("covers" in card.data), "file cards must not grow concept covers: []");
+ assert.match(card.content.trimStart(), /^# auth\.ts/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test("re-running the wiring build leaves covers byte-stable", async () => {
const dir = makeFixture();
try {