Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(backlinks): stream the gap scan so memory tracks the largest file, not the brain (#6438)
garrytan3ff543d9dca3
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex a9324190eb..716d08817d 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`. `backup create|restore` failures render the agent-operator contract (`storage_error`, fix `gbrain doctor --json`) with the legacy `ok`/`reason`/`message`/`retryable` JSON keys; a message-less thrown value is described only by its bounded name/code/errno (`backupFailureMessage`), never `String(object)`.-- `src/commands/backlinks.ts` — Back-link checker and fixer (enforces Iron Law). `fix` (and `fix --dry-run`) refuses once, before the scan, when the directory is a managed canonical worktree (`isManagedFilesystemPath` from `src/core/persistence/filesystem-guard.ts`, the predicate `assertManagedFilesystemWrite` uses), instead of skipping every page one by one; `check` still runs (#5341). Repair-inserted references land as UNDATED rows (`- Referenced in [Title](../path)`) in a dedicated `## Referenced by` section placed ABOVE the timeline region — retroactively stamping the repair date onto a timeline would forge events that never happened on that date; only live capture writes dated timeline entries. `insertBacklinkEntry(content, bodyStart, entry)` never touches bytes before `bodyStart`, locates the timeline boundary via `findTimelineSplitIndex` (existing timeline sentinels take precedence over bare `## Timeline`/`## History` headings), appends to an existing `## Referenced by` section or creates one above the timeline, and is CRLF-tolerant; `insertTimelineEntry` is an alias for existing import sites. `buildBacklinkEntry(sourceTitle, sourcePath)` takes no date; dir-shaped sources get an extension-less brain-slug link so the next check pass credits the fresh row instead of re-flagging (idempotency).+- `src/commands/backlinks.ts` — Back-link checker and fixer (enforces Iron Law). `fix` (and `fix --dry-run`) refuses once, before the scan, when the directory is a managed canonical worktree (`isManagedFilesystemPath` from `src/core/persistence/filesystem-guard.ts`, the predicate `assertManagedFilesystemWrite` uses), instead of skipping every page one by one; `check` still runs (#5341). Repair-inserted references land as UNDATED rows (`- Referenced in [Title](../path)`) in a dedicated `## Referenced by` section placed ABOVE the timeline region — retroactively stamping the repair date onto a timeline would forge events that never happened on that date; only live capture writes dated timeline entries. `insertBacklinkEntry(content, bodyStart, entry)` never touches bytes before `bodyStart`, locates the timeline boundary via `findTimelineSplitIndex` (existing timeline sentinels take precedence over bare `## Timeline`/`## History` headings), appends to an existing `## Referenced by` section or creates one above the timeline, and is CRLF-tolerant; `insertTimelineEntry` is an alias for existing import sites. `buildBacklinkEntry(sourceTitle, sourcePath)` takes no date; dir-shaped sources get an extension-less brain-slug link so the next check pass credits the fresh row instead of re-flagging (idempotency). `findBacklinkGaps` is a streaming two-pass scan (#6438): pass 1 reads each `.md` once and keeps only its slug, title and candidate `people/`/`companies/` targets (display name included; substrings are detached from the page body so JSC cannot pin it), pass 2 reads each referenced existing target once and records which sources it already credits, pass 3 emits the gaps in the pre-streaming order with the #967 per-source dedupe; the working set is the file being read plus that metadata, never the corpus. `findBacklinkGapsAsync` is the same scan yielding to the event loop every `BACKLINKS_YIELD_EVERY` files so the progress heartbeat and the minion RSS watchdog run mid-scan; `runBacklinksCore` uses it and returns the gap list in `BacklinksResult.gaps`, which the CLI prints instead of walking a second time. Pinned by `test/backlinks-gap-parity.test.ts` (golden captured from the single-pass walker), `test/backlinks-yield.test.ts` and `test/backlinks-memory.slow.test.ts` (isolated-process RSS slope).- `src/commands/book-mirror.ts` — `gbrain book-mirror --chapters-dir <path> --slug <slug> [flags]`. Submits N read-only subagent jobs (one per chapter; `allowed_tools: ['get_page', 'search']`), waits for all via `waitForCompletion`, reads each child's `job.result`, assembles two-column markdown CLI-side, writes a single operator-trust `put_page` to `media/books/<slug>-personalized.md`. Trust narrowing happens at the tool-allowlist layer (subagents can't call put_page) so untrusted EPUB content can't prompt-inject any people page. Asks for consent before submitting (exit 3 with the consent payload without `--yes`/`--max-usd`/a preapproval) and stores the authorization on every chapter job as one spend group (`of` = chapters) whose total the worker enforces; prints the submit summary (group, kept authorizations, reused rows). Per-chapter idempotency keys (`book-mirror:<slug>:ch-<N>`) for retry-friendly re-runs. Final publication captures its page revision and request UUID before providers run; a pending or failed receipt prevents a false written report and preserves the request ID for inspection. Partial-failure: assembles completed chapters + a `## Failed chapters` section. Pinned by `test/book-mirror.test.ts` (9 cases).diff --git a/src/commands/backlinks.ts b/src/commands/backlinks.tsindex 020f967834..e849609472 100644--- a/src/commands/backlinks.ts+++ b/src/commands/backlinks.ts@@ -90,84 +90,155 @@ export function buildBacklinkEntry(sourceTitle: string, sourcePath: string): strreturn `- Referenced in [${sourceTitle}](${linkPath})`;}-/** Scan a brain directory for back-link gaps */-export function findBacklinkGaps(brainDir: string): BacklinkGap[] {- const gaps: BacklinkGap[] = [];-- // Collect all markdown files- const allPages: { path: string; relPath: string; content: string }[] = [];- function walk(dir: string) {- for (const entry of readdirSync(dir)) {- if (entry.startsWith('.')) continue;- const full = join(dir, entry);- if (lstatSync(full).isDirectory()) {- walk(full);- } else if (entry.endsWith('.md') && !entry.startsWith('_')) {- const relPath = relative(brainDir, full);- try {- allPages.push({ path: full, relPath, content: readFileSync(full, 'utf-8') });- } catch { /* skip unreadable */ }+/**+ * Pages the walker visits: every `.md` under `brainDir`, skipping dot+ * entries and `_`-prefixed files, in readdir order (the order the gap list+ * follows). Symlinks are not followed as directories (lstat).+ */+function* walkMarkdownFiles(brainDir: string, dir = brainDir): Generator<{ full: string; relPath: string }> {+ for (const entry of readdirSync(dir)) {+ if (entry.startsWith('.')) continue;+ const full = join(dir, entry);+ if (lstatSync(full).isDirectory()) yield* walkMarkdownFiles(brainDir, full);+ else if (entry.endsWith('.md') && !entry.startsWith('_')) yield { full, relPath: relative(brainDir, full) };+ }+}++/** Files between event-loop yields in the async walker (#6438). */+export const BACKLINKS_YIELD_EVERY = 64;++/**+ * A fresh copy of a string sliced out of a page body. JSC substrings share+ * their parent's buffer, so a title or display name kept from `content`+ * would pin the whole page in memory (the retention #6438 is about); the+ * UTF-8 round trip allocates a new backing store.+ */+function detach(s: string): string {+ return Buffer.from(s, 'utf8').toString('utf8');+}++interface GapCandidate {+ relPath: string;+ sourceSlug: string;+ sourceFilename: string;+ title: string;+ /** Unique targets in first-mention order (#967 dedupe), with the display name of the first mention. */+ refs: Array<{ targetSlug: string; name: string }>;+}++/**+ * The streaming gap scan (#6438). Pass 1 reads each page once and keeps only+ * its slug, title and candidate `people/`/`companies/` targets (never the+ * body); pass 2 reads each referenced existing target once, records which+ * referencing sources it already credits (legacy `<basename>.md` substring+ * or a canonical outgoing ref, #1776) and drops the body; pass 3 emits the+ * gaps in the same order the single-pass walker produced them. The working+ * set is the file currently read plus candidate/index metadata, so a brain's+ * size in bytes no longer bounds the scan. The passes are generators so the+ * sync and async entry points share one implementation; the async one+ * yields to the event loop every BACKLINKS_YIELD_EVERY files, which lets the+ * progress heartbeat and the minion RSS watchdog run mid-scan.+ */+class BacklinkGapScan {+ private readonly existingSlugs = new Set<string>();+ private readonly candidates: GapCandidate[] = [];+ /** target slug -> candidate indexes that mention it */+ private readonly referrers = new Map<string, number[]>();+ /** target slug -> candidate indexes the target already credits */+ private readonly credited = new Map<string, Set<number>>();++ constructor(private readonly brainDir: string) {}++ *pass1(): Generator<void> {+ for (const { full, relPath } of walkMarkdownFiles(this.brainDir)) {+ let content: string;+ try {+ content = readFileSync(full, 'utf-8');+ } catch { continue; /* skip unreadable */ }+ this.existingSlugs.add(relPath.replace('.md', ''));+ const refs = projectPeopleCompaniesRefs(canonicalExtractEntityRefs(content));+ if (refs.length > 0) {+ const seen = new Set<string>();+ const unique: GapCandidate['refs'] = [];+ for (const ref of refs) {+ const targetSlug = detach(`${ref.dir}/${ref.slug}`);+ if (seen.has(targetSlug)) continue;+ seen.add(targetSlug);+ unique.push({ targetSlug, name: detach(ref.name) });+ }+ const index = this.candidates.length;+ this.candidates.push({+ relPath,+ sourceSlug: relPath.replace(/\.md$/, ''),+ sourceFilename: basename(relPath),+ title: detach(extractPageTitle(content)),+ refs: unique,+ });+ for (const { targetSlug } of unique) {+ const list = this.referrers.get(targetSlug);+ if (list) list.push(index);+ else this.referrers.set(targetSlug, [index]);+ }}+ yield;}}- walk(brainDir);-- // Build a lookup of existing pages by directory/slug. #1776: extract each- // page's canonical refs ONCE here — they feed both the gap candidates- // (people/companies projection) and the backlink-credit slug set, so- // extension-less convention links ([Alice](../people/alice),- // [[people/alice]]) count as backlinks even though the legacy- // `<basename>.md` substring check can't see them.- const pagesBySlug = new Map<string, { path: string; content: string }>();- const refsByRelPath = new Map<string, { name: string; slug: string; dir: string }[]>();- const outgoingSlugsBySlug = new Map<string, Set<string>>();- for (const page of allPages) {- const slug = page.relPath.replace('.md', '');- pagesBySlug.set(slug, { path: page.path, content: page.content });- const canonical = canonicalExtractEntityRefs(page.content);- refsByRelPath.set(page.relPath, canonical);- outgoingSlugsBySlug.set(slug, new Set(canonical.map(r => r.slug)));- }- // For each page, check entity references- for (const page of allPages) {- const refs = projectPeopleCompaniesRefs(refsByRelPath.get(page.relPath) ?? []);- const sourceFilename = basename(page.relPath);- const sourceSlug = page.relPath.replace(/\.md$/, '');- // LOCAL PATCH (paolo, 2026-05-12): dedupe (source, target) pairs within- // a single source page. extractEntityRefs returns one EntityRef per- // occurrence, so a source page that mentions the same target N times- // produced N identical gaps → N duplicate "Referenced in" lines on the- // target. The per-ref `hasBacklink(target.content, ...)` check reads a- // stale snapshot (target.content is frozen at this scope), so every- // iteration sees the same "no backlink yet" state and pushes another- // gap. Tracking seen target slugs per source caps gaps at one per pair.- const seen = new Set<string>();-- for (const ref of refs) {- const targetSlug = `${ref.dir}/${ref.slug}`;- if (seen.has(targetSlug)) continue;- seen.add(targetSlug);- const target = pagesBySlug.get(targetSlug);- if (!target) continue; // target page doesn't exist-- // Check if the target already has a back-link to this source page.- // Credited two ways (#1776): the legacy `<basename>.md` substring- // (old fixer rows, explicit .md links) OR the target's canonical- // outgoing refs containing the source slug (extension-less- // convention links and wikilinks the substring check misses).- if (hasBacklink(target.content, sourceFilename)) continue;- if (outgoingSlugsBySlug.get(targetSlug)?.has(sourceSlug)) continue;- gaps.push({- sourcePage: page.relPath,- targetPage: targetSlug + '.md',- entityName: ref.name,- sourceTitle: extractPageTitle(page.content),- });+ *pass2(): Generator<void> {+ for (const [targetSlug, indexes] of this.referrers) {+ if (!this.existingSlugs.has(targetSlug)) continue;+ let content: string;+ try {+ content = readFileSync(join(this.brainDir, `${targetSlug}.md`), 'utf-8');+ } catch { continue; /* vanished since pass 1: not a target */ }+ const outgoing = new Set(canonicalExtractEntityRefs(content).map(r => r.slug));+ const credits = new Set<number>();+ for (const i of indexes) {+ const c = this.candidates[i]!;+ if (hasBacklink(content, c.sourceFilename) || outgoing.has(c.sourceSlug)) credits.add(i);+ }+ this.credited.set(targetSlug, credits);+ yield;}}- return gaps;+ gaps(): BacklinkGap[] {+ const gaps: BacklinkGap[] = [];+ this.candidates.forEach((c, i) => {+ for (const ref of c.refs) {+ const credits = this.credited.get(ref.targetSlug);+ if (!credits) continue; // target page doesn't exist+ if (credits.has(i)) continue;+ gaps.push({ sourcePage: c.relPath, targetPage: ref.targetSlug + '.md', entityName: ref.name, sourceTitle: c.title });+ }+ });+ return gaps;+ }+}++/** Scan a brain directory for back-link gaps (synchronous; see findBacklinkGapsAsync for the yielding form). */+export function findBacklinkGaps(brainDir: string): BacklinkGap[] {+ const scan = new BacklinkGapScan(brainDir);+ for (const _ of scan.pass1()) { /* drain */ }+ for (const _ of scan.pass2()) { /* drain */ }+ return scan.gaps();+}++/**+ * The same scan, yielding to the event loop every BACKLINKS_YIELD_EVERY files+ * so timers (the progress heartbeat, the worker RSS watchdog) run mid-scan.+ */+export async function findBacklinkGapsAsync(brainDir: string): Promise<BacklinkGap[]> {+ const scan = new BacklinkGapScan(brainDir);+ const yieldNow = () => new Promise<void>(resolve => setImmediate(resolve));+ for (const pass of [scan.pass1(), scan.pass2()]) {+ let n = 0;+ for (const _ of pass) {+ if (++n % BACKLINKS_YIELD_EVERY === 0) await yieldNow();+ }+ await yieldNow();+ }+ return scan.gaps();}/** Per-run outcome of the fixer: entries inserted + per-file skip reasons. */@@ -343,6 +414,8 @@ export interface BacklinksResult {/** Pages the fixer refused to touch (invalid frontmatter, lock/write errors). */skipped_invalid?: number;skipped_pages?: Array<{ page: string; reason: string }>;+ /** The gaps the scan found, so the CLI prints them without a second walk (#6438). */+ gaps?: BacklinkGap[];}export interface ParsedBacklinksArgs {@@ -405,14 +478,14 @@ export async function runBacklinksCore(opts: BacklinksOpts): Promise<BacklinksRe}}- // findBacklinkGaps is a sync double-walk of the brain dir. On 50K-page- // brains that can take seconds — heartbeat so agents see we're working.+ // The scan streams the brain dir (#6438) and yields every few files so+ // this heartbeat and the worker's RSS watchdog fire while it runs.const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));progress.start('backlinks.scan');const stopHb = startHeartbeat(progress, 'walking pages for missing back-links…');let gaps: BacklinkGap[];try {- gaps = findBacklinkGaps(opts.dir);+ gaps = await findBacklinkGapsAsync(opts.dir);} finally {stopHb();progress.finish();@@ -440,9 +513,10 @@ export async function runBacklinksCore(opts: BacklinksOpts): Promise<BacklinksRedryRun: !!opts.dryRun,skipped_invalid: fixOutcome.skipped.length,skipped_pages: fixOutcome.skipped,+ gaps,};}- return { action: opts.action, gaps_found: gaps.length, fixed: 0, pages_affected: pagesAffected, dryRun: !!opts.dryRun };+ return { action: opts.action, gaps_found: gaps.length, fixed: 0, pages_affected: pagesAffected, dryRun: !!opts.dryRun, gaps };}export async function runBacklinks(args: string[]) {@@ -475,8 +549,7 @@ export async function runBacklinks(args: string[]) {return;}if (result.action === 'check') {- // Re-walk for user-facing output (core returns counts, CLI shows detail).- const gaps = findBacklinkGaps(brainDir);+ const gaps = result.gaps ?? [];console.log(`Found ${gaps.length} missing back-link(s):\n`);for (const gap of gaps) {console.log(` ${gap.targetPage} <- ${gap.sourcePage}`);diff --git a/test/backlinks-gap-parity.test.ts b/test/backlinks-gap-parity.test.tsnew file mode 100644index 0000000000..72578101c4--- /dev/null+++ b/test/backlinks-gap-parity.test.ts@@ -0,0 +1,46 @@+/**+ * Backlinks gap-list parity (wave 14 P1.1, [R22]).+ *+ * Protects: the streaming two-pass `findBacklinkGaps` returns exactly what+ * the single-pass walker returned: same gaps, same order, same per-source+ * dedupe (#967), same `entityName` (the display name, not the slug) and+ * `sourceTitle`. The golden was captured from master's implementation on+ * the shared fixture; a regression reorders, drops or renames a gap.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { findBacklinkGaps, findBacklinkGapsAsync } from '../src/commands/backlinks.ts';+import { writeBacklinksParityFixture } from './helpers/backlinks-parity-fixture.ts';++const GOLDEN = new URL('./fixtures/backlinks-parity/gaps.golden.json', import.meta.url).pathname;+const roots: string[] = [];+afterEach(() => { while (roots.length) rmSync(roots.pop()!, { recursive: true, force: true }); });++function fixture(): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-backlinks-parity-'));+ roots.push(root);+ writeBacklinksParityFixture(root);+ return root;+}++describe('findBacklinkGaps parity with the pre-streaming walker', () => {+ test('the sync walker matches the golden byte for byte', () => {+ const gaps = findBacklinkGaps(fixture());+ expect(JSON.stringify(gaps, null, 2) + '\n').toBe(readFileSync(GOLDEN, 'utf-8'));+ });++ test('the async walker returns the same list', async () => {+ const gaps = await findBacklinkGapsAsync(fixture());+ expect(JSON.stringify(gaps, null, 2) + '\n').toBe(readFileSync(GOLDEN, 'utf-8'));+ });++ test('the golden has the shapes the fixture was built to pin', () => {+ const gaps = JSON.parse(readFileSync(GOLDEN, 'utf-8')) as Array<Record<string, string>>;+ expect(gaps.some(g => g.entityName === 'Alice again' || g.entityName === 'ACME Inc' || g.entityName === 'Bobby')).toBe(true);+ expect(gaps.filter(g => g.sourcePage === 'meetings/standup.md' && g.targetPage === 'people/alice.md')).toHaveLength(1);+ expect(gaps.some(g => g.targetPage === 'people/ghost.md')).toBe(false);+ expect(gaps.some(g => g.sourcePage.startsWith('notes/_draft') || g.sourcePage.startsWith('.hidden'))).toBe(false);+ });+});diff --git a/test/backlinks-memory.slow.test.ts b/test/backlinks-memory.slow.test.tsnew file mode 100644index 0000000000..746410a45b--- /dev/null+++ b/test/backlinks-memory.slow.test.ts@@ -0,0 +1,45 @@+/**+ * Backlinks scan memory is bounded by the largest file, not the corpus+ * (wave 14 P1.1, #6438, [R22]).+ *+ * Protects: `findBacklinkGaps` on a brain whose non-target pages hold N MiB+ * of markdown keeps its working set at the largest file currently read plus+ * candidate/index metadata. Before the fix every page body was retained+ * (602 MiB of markdown → +2.3 GiB RSS; a 21.7 GiB brain cannot fit), so the+ * RSS delta grew linearly with the corpus. Each measurement runs in its own+ * child process so the parent's heap and other tests cannot skew it.+ * Regression: a map that retains bodies again. No production seam: the+ * child reports process.memoryUsage().rss.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const CHILD = new URL('./helpers/backlinks-rss-child.ts', import.meta.url).pathname;+const SIZES_MIB = [48, 192, 384];+const roots: string[] = [];+afterAll(() => { while (roots.length) rmSync(roots.pop()!, { recursive: true, force: true }); });++function measure(mib: number): { gaps: number; delta_peak_mb: number; heap_retained_mb: number } {+ const root = mkdtempSync(join(tmpdir(), `gbrain-backlinks-rss-${mib}-`));+ roots.push(root);+ const r = Bun.spawnSync(['bun', CHILD, root, String(mib)], { stdout: 'pipe', stderr: 'pipe', timeout: 600_000 });+ if (r.exitCode !== 0) throw new Error(`child failed (${r.exitCode}): ${r.stderr.toString()}`);+ return JSON.parse(r.stdout.toString().trim().split('\n').at(-1)!);+}++describe('findBacklinkGaps RSS slope', () => {+ test('up to 384 MiB of non-target markdown the RSS delta stays under 150 MB, the heap keeps under 48 MB, and the delta does not follow the corpus', () => {+ const runs = SIZES_MIB.map(mib => ({ mib, ...measure(mib) }));+ for (const r of runs) {+ expect(r.gaps).toBe(r.mib);+ // Before the fix the RSS delta was ~3x the corpus (48 MiB → +193 MB, 384 MiB → +1470 MB) and the heap kept every body.+ expect(r.delta_peak_mb).toBeLessThan(150);+ expect(r.heap_retained_mb).toBeLessThan(48);+ }+ const largest = runs.at(-1)!;+ const smallest = runs[0]!;+ expect(largest.delta_peak_mb).toBeLessThan(smallest.delta_peak_mb * 2 + 64);+ }, 900_000);+});diff --git a/test/backlinks-yield.test.ts b/test/backlinks-yield.test.tsnew file mode 100644index 0000000000..91925a20db--- /dev/null+++ b/test/backlinks-yield.test.ts@@ -0,0 +1,84 @@+/**+ * Backlinks scan yields to the event loop (wave 14 P1.1, #6438).+ *+ * Protects: the autopilot `backlinks` phase runs under a heartbeat and the+ * minion RSS watchdog, both timers. A synchronous walk never lets them fire,+ * so on a 350k-page brain the worker grew to 14 GB with no watchdog action.+ * Regression: the async walker stops yielding. Existing coverage asserts+ * gap results, never scheduling. The seam is the global `setImmediate` the+ * walker yields through (spied, not injected).+ */+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import * as fs from 'fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { BACKLINKS_YIELD_EVERY, findBacklinkGapsAsync, runBacklinks, runBacklinksCore } from '../src/commands/backlinks.ts';++const roots: string[] = [];+afterEach(() => { while (roots.length) rmSync(roots.pop()!, { recursive: true, force: true }); });++function corpus(pages: number): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-backlinks-yield-'));+ roots.push(root);+ mkdirSync(join(root, 'people'));+ mkdirSync(join(root, 'notes'));+ writeFileSync(join(root, 'people/alice.md'), '# Alice\n');+ for (let i = 0; i < pages; i++) writeFileSync(join(root, `notes/n${i}.md`), `# Note ${i}\n\n[Alice](../people/alice)\n`);+ return root;+}++describe('findBacklinkGapsAsync yields', () => {+ test('1000 pages yield at least ceil(1000 / N) times and let a timer fire mid-scan', async () => {+ const root = corpus(1000);+ const setImmediateSpy = spyOn(globalThis, 'setImmediate');+ let ticks = 0;+ const timer = setInterval(() => { ticks++; }, 1);+ try {+ const gaps = await findBacklinkGapsAsync(root);+ expect(gaps).toHaveLength(1000);+ expect(setImmediateSpy.mock.calls.length).toBeGreaterThanOrEqual(Math.ceil(1000 / BACKLINKS_YIELD_EVERY));+ expect(ticks).toBeGreaterThan(0);+ } finally {+ clearInterval(timer);+ setImmediateSpy.mockRestore();+ }+ });++ test('runBacklinksCore check runs the yielding walker and reports the gap list once', async () => {+ const root = corpus(300);+ const setImmediateSpy = spyOn(globalThis, 'setImmediate');+ try {+ const result = await runBacklinksCore({ action: 'check', dir: root });+ expect(result.gaps_found).toBe(300);+ expect(result.gaps).toHaveLength(300);+ expect(setImmediateSpy.mock.calls.length).toBeGreaterThanOrEqual(Math.ceil(300 / BACKLINKS_YIELD_EVERY));+ } finally {+ setImmediateSpy.mockRestore();+ }+ });+});++describe('one scan per run (#6438)', () => {+ test('the CLI check path reads each page once in pass 1 and each referenced target once in pass 2, with no second walk', async () => {+ const root = corpus(40);+ const reads = spyOn(fs, 'readFileSync');+ const dirs = spyOn(fs, 'readdirSync');+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runBacklinks(['check', root]);+ const pageReads = reads.mock.calls.map(c => String(c[0])).filter(p => p.startsWith(root));+ const counts = new Map<string, number>();+ for (const p of pageReads) counts.set(p, (counts.get(p) ?? 0) + 1);+ for (let i = 0; i < 40; i++) expect(counts.get(join(root, `notes/n${i}.md`))).toBe(1);+ // alice: once as a page in pass 1, once as the referenced target in pass 2.+ expect(counts.get(join(root, 'people/alice.md'))).toBe(2);+ expect(pageReads).toHaveLength(42);+ // root, notes, people: one directory walk, not two.+ expect(dirs.mock.calls.map(c => String(c[0])).filter(p => p.startsWith(root))).toHaveLength(3);+ expect(log.mock.calls.some(c => String(c[0]).includes('Found 40 missing back-link(s)'))).toBe(true);+ } finally {+ reads.mockRestore(); dirs.mockRestore(); log.mockRestore();+ }+ });+});diff --git a/test/fixtures/backlinks-parity/gaps.golden.json b/test/fixtures/backlinks-parity/gaps.golden.jsonnew file mode 100644index 0000000000..c79f06d91d--- /dev/null+++ b/test/fixtures/backlinks-parity/gaps.golden.json@@ -0,0 +1,32 @@+[+ {+ "sourcePage": "meetings/standup.md",+ "targetPage": "people/alice.md",+ "entityName": "Alice",+ "sourceTitle": "Daily standup"+ },+ {+ "sourcePage": "meetings/standup.md",+ "targetPage": "people/bob.md",+ "entityName": "people/bob",+ "sourceTitle": "Daily standup"+ },+ {+ "sourcePage": "meetings/offsite.md",+ "targetPage": "people/bob.md",+ "entityName": "Bob",+ "sourceTitle": "Offsite"+ },+ {+ "sourcePage": "notes/deep/idea.md",+ "targetPage": "people/bob.md",+ "entityName": "Bobby",+ "sourceTitle": "Idea"+ },+ {+ "sourcePage": "notes/deep/idea.md",+ "targetPage": "companies/acme.md",+ "entityName": "companies/acme",+ "sourceTitle": "Idea"+ }+]diff --git a/test/helpers/backlinks-parity-fixture.ts b/test/helpers/backlinks-parity-fixture.tsnew file mode 100644index 0000000000..5eccb83edc--- /dev/null+++ b/test/helpers/backlinks-parity-fixture.ts@@ -0,0 +1,24 @@+/**+ * The #967 / #1776 fixture for the backlinks gap-list parity golden+ * (wave 14 P1.1): several source dirs, duplicate refs within one page,+ * display names that differ from the slug (`ref.name`), a missing target,+ * extension-less and wikilink credit, an `_`-prefixed and a dot-prefixed+ * entry the walker skips, and an unreadable-looking (non-.md) sibling.+ */+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++export function writeBacklinksParityFixture(root: string): void {+ for (const d of ['people', 'companies', 'meetings', 'notes/deep', '.hidden']) mkdirSync(join(root, d), { recursive: true });+ writeFileSync(join(root, 'people/alice.md'), '---\ntitle: "Alice Example"\n---\n\n# Alice\n\nWorks at [Acme](../companies/acme).\n');+ writeFileSync(join(root, 'people/bob.md'), '# Bob\n\nNo links.\n');+ writeFileSync(join(root, 'companies/acme.md'), '# Acme\n\nFounded by [Alice](../people/alice). Standup notes: standup.md\n');+ writeFileSync(join(root, 'companies/widget-co.md'), '# Widget Co\n\nSee [[meetings/offsite]].\n');+ writeFileSync(join(root, 'meetings/standup.md'),+ '---\ntitle: Daily standup\n---\n\nWe discussed [Alice](../people/alice) and [Alice again](people/alice).\n[[people/bob]] joined. [Acme](../companies/acme) was mentioned twice: [ACME Inc](../companies/acme).\n[Ghost](../people/ghost) does not exist.\n');+ writeFileSync(join(root, 'meetings/offsite.md'), '# Offsite\n\n[Widget Co](../companies/widget-co) hosted; [Bob](../people/bob) spoke.\n');+ writeFileSync(join(root, 'notes/deep/idea.md'), '# Idea\n\n[Bobby](../../people/bob) and [[companies/acme]].\n');+ writeFileSync(join(root, 'notes/_draft.md'), '# Draft\n\n[Alice](../people/alice)\n');+ writeFileSync(join(root, '.hidden/secret.md'), '# Secret\n\n[Alice](../people/alice)\n');+ writeFileSync(join(root, 'notes/readme.txt'), '[Alice](../people/alice)\n');+}diff --git a/test/helpers/backlinks-rss-child.ts b/test/helpers/backlinks-rss-child.tsnew file mode 100644index 0000000000..b48cdb581c--- /dev/null+++ b/test/helpers/backlinks-rss-child.ts@@ -0,0 +1,47 @@+/**+ * Child process for test/backlinks-memory.slow.test.ts (wave 14 P1.1).+ * argv: <corpusRoot> <nonTargetMiB>. Builds the corpus if the root is empty+ * (50 fixed `people/`/`companies/` targets, non-target pages of ~1 MiB each+ * with one sparse ref apiece), runs findBacklinkGaps, prints one JSON line:+ * { gaps, rss_before_mb, rss_peak_mb, delta_peak_mb, heap_retained_mb, largest_file_mb }:+ * the RSS peak is read right after the scan (what the OOM killer sees; RSS+ * never shrinks back), the heap delta after a forced GC is what the scan+ * actually kept alive.+ */+import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { findBacklinkGaps } from '../../src/commands/backlinks.ts';++const [root, mibArg] = process.argv.slice(2);+const mib = Number(mibArg);+if (!root || !Number.isFinite(mib)) throw new Error('usage: backlinks-rss-child <root> <nonTargetMiB>');++const FILE_MIB = 1;+if (!existsSync(join(root, 'people')) || readdirSync(join(root, 'records')).length !== mib / FILE_MIB) {+ mkdirSync(join(root, 'people'), { recursive: true });+ mkdirSync(join(root, 'companies'), { recursive: true });+ mkdirSync(join(root, 'records'), { recursive: true });+ for (let i = 0; i < 25; i++) {+ writeFileSync(join(root, 'people', `person-${i}.md`), `# Person ${i}\n\nA fixed target.\n`);+ writeFileSync(join(root, 'companies', `company-${i}.md`), `# Company ${i}\n\nA fixed target.\n`);+ }+ const filler = 'lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor\n';+ const body = filler.repeat(Math.ceil((FILE_MIB * 1024 * 1024) / filler.length));+ for (let i = 0; i < mib / FILE_MIB; i++) {+ const dir = i % 2 === 0 ? 'people' : 'companies';+ const ref = `[Target ${i}](../${dir}/${dir === 'people' ? 'person' : 'company'}-${i % 25})`;+ writeFileSync(join(root, 'records', `record-${i}.md`), `# Record ${i}\n\n${ref}\n\n${body}`);+ }+}++Bun.gc(true);+const before = process.memoryUsage();+const gaps = findBacklinkGaps(root);+const peak = process.memoryUsage().rss;+Bun.gc(true);+const after = process.memoryUsage();+const mb = (n: number) => Math.round(n / (1024 * 1024));+console.log(JSON.stringify({+ gaps: gaps.length, rss_before_mb: mb(before.rss), rss_peak_mb: mb(peak),+ delta_peak_mb: mb(peak - before.rss), heap_retained_mb: mb(after.heapUsed - before.heapUsed), largest_file_mb: FILE_MIB,+}));