Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(doctor): head-only frontmatter scan, batched timeline reads, census keyset order on the indexed column, outside-repo git memo
time-attack40f96cba31e5
diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.tsindex bcb856bf17..bbb843ca31 100644--- a/src/commands/doctor/checks/content-quality.ts+++ b/src/commands/doctor/checks/content-quality.ts@@ -346,6 +346,7 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {signal: fmAbort,deadline: fmDeadline,dbPageCountForSource,+ frontmatterOnly: true,});if (report.total === 0 && !report.partial) {diff --git a/src/commands/doctor/checks/frontmatter-repairable.ts b/src/commands/doctor/checks/frontmatter-repairable.tsindex f66d24c5a0..ab9901746b 100644--- a/src/commands/doctor/checks/frontmatter-repairable.ts+++ b/src/commands/doctor/checks/frontmatter-repairable.ts@@ -51,6 +51,6 @@ export function frontmatterRepairableFromReport(report: AuditReport, timeoutMs:export async function frontmatterRepairableCheck(engine: BrainEngine, sourceId?: string): Promise<Check> {const { scanBrainSources } = await import('../../../core/brain-writer.ts');const timeoutMs = frontmatterScanTimeoutMs();- const report = await scanBrainSources(engine, { sourceId, deadline: Date.now() + timeoutMs, signal: AbortSignal.timeout(timeoutMs) });+ const report = await scanBrainSources(engine, { sourceId, deadline: Date.now() + timeoutMs, signal: AbortSignal.timeout(timeoutMs), frontmatterOnly: true });return frontmatterRepairableFromReport(report, timeoutMs);}diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.tsindex 7105aea5c2..2825b421eb 100644--- a/src/core/brain-writer.ts+++ b/src/core/brain-writer.ts@@ -602,6 +602,34 @@ export interface ScanOpts {* (post-pruneDir). Production callers don't pass this; the regression* suite uses it to assert descent-time pruning directly. */visitDir?: (dirPath: string) => void;+ /** Parse only each file's frontmatter head (`frontmatterScanHead`) when that+ * provably yields the same findings; the doctor scan sets it. */+ frontmatterOnly?: boolean;+}++/**+ * The prefix of `content` through its closing frontmatter fence line, when+ * validating that prefix yields exactly the errors, warnings, recovery and+ * slug of the whole file; otherwise `content` itself. Proven only for the+ * plain shape every frontmatter reader agrees on: the file starts with a+ * `---` line (no BOM, blank lines or language selector), no line before the+ * first `---` close starts with `---`, the close is a bare `---` line after+ * at least one block line, and the file has no NUL byte (NULL_BYTES reads+ * the whole file). Everything after the close is body, which the findings+ * never read.+ */+export function frontmatterScanHead(content: string): string {+ if (!content.startsWith('---') || content.includes('\0')) return content;+ const first = content.indexOf('\n');+ if (first < 0 || (first !== 3 && content.slice(0, first) !== '---\r')) return content;+ for (let start = first + 1, line = 1; ; line++) {+ const end = content.indexOf('\n', start);+ if (end < 0) return content;+ const text = content.slice(start, end);+ if (text.trim() === '---') return line >= 2 && (text === '---' || text === '---\r') ? content.slice(0, end + 1) : content;+ if (text.startsWith('---')) return content;+ start = end + 1;+ }}/** Timeout-arm winner for the COUNT-vs-deadline race in scanBrainSources.@@ -818,7 +846,7 @@ function scanOneSource(return true; // skip unreadable}const expectedSlug = slugifyPath(relPath);- const parsed = parseMarkdown(content, relPath, { validate: true, expectedSlug });+ const parsed = parseMarkdown(opts.frontmatterOnly ? frontmatterScanHead(content) : content, relPath, { validate: true, expectedSlug });const errs = (parsed.errors ?? []).filter((e) => {if (e.code !== 'MISSING_OPEN') return true;if (opts.strictMissingOpen) return true;diff --git a/src/core/fence-repair/census.ts b/src/core/fence-repair/census.tsindex f35649be79..76d3ffb166 100644--- a/src/core/fence-repair/census.ts+++ b/src/core/fence-repair/census.ts@@ -29,7 +29,7 @@ import { join, relative, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';import { parseMarkdown } from '../markdown.ts';import { screenFenceCtx } from '../import-screen.ts';-import { collectGitVisibleFiles } from '../git-visible-files.ts';+import { collectGitVisibleFiles, knownOutsideGitRepo, noteGitFailure } from '../git-visible-files.ts';import { isFrontmatterScannablePath, walkDir } from '../brain-writer.ts';import { sha256 } from '../persistence/digest.ts';import { readGitSourceHolds, type GitHoldRecord } from '../persistence/sync-holds.ts';@@ -159,7 +159,7 @@ async function scanPages(engine: Exec, source: CensusSource, progress: ScanProgrpages.pass ??= { lower: pages.watermark ?? await passHorizon(engine, opts.lateCommitGraceMs), next: await passHorizon(engine, opts.lateCommitGraceMs), after: null };const pass = pages.pass;const rows = await engine.executeRaw<PageRow>(`SELECT ${PAGE_COLUMNS} FROM pages WHERE source_id=$1 AND updated_at>=$2::timestamptz- AND ($3::timestamptz IS NULL OR (updated_at, id) > ($3::timestamptz, $4::int)) ORDER BY updated_at, id LIMIT $5`,+ AND ($3::timestamptz IS NULL OR (updated_at, id) > ($3::timestamptz, $4::int)) ORDER BY pages.updated_at, pages.id LIMIT $5`,[source.id, pass.lower, pass.after?.at ?? null, pass.after?.id ?? 0, opts.batchSize]);await judgePages(engine, source, rows, opts.now().toISOString());if (rows.length) pass.after = { at: rows[rows.length - 1]!.updated_at, id: Number(rows[rows.length - 1]!.id) };@@ -172,9 +172,11 @@ async function scanPages(engine: Exec, source: CensusSource, progress: ScanProgr}function git(root: string, args: string[]): string | null {+ if (knownOutsideGitRepo(root)) return null;try {- return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });- } catch {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });+ } catch (error) {+ noteGitFailure(root, error);return null;}}diff --git a/src/core/git-visible-files.ts b/src/core/git-visible-files.tsindex 359405d164..836349d1d9 100644--- a/src/core/git-visible-files.ts+++ b/src/core/git-visible-files.ts@@ -1,36 +1,88 @@import { AsyncLocalStorage } from 'node:async_hooks';import { execFileSync } from 'child_process';import { lstatSync } from 'fs';-import { join } from 'path';+import { dirname, join, resolve } from 'path';-const listingCache = new AsyncLocalStorage<Map<string, string | null>>();+interface GitScope {+ /** Successful listings; a failure is not memoized (an outside-repo failure is, below, until a `.git` changes). */+ listings: Map<string, string>;+ /** Directories git reported outside any repository, each with the `.git` markers it saw then. */+ outside: Map<string, string>;+}++const gitScope = new AsyncLocalStorage<GitScope>();/*** Run `fn` with `git ls-files` listings memoized per directory and arguments- * for every `gitLsFiles` call inside it. Doctor wraps its check run in one so- * the checks that each list the same source checkout (frontmatter scan, fence- * census, slug collisions) spawn git once per listing instead of once per- * check; code outside the scope always spawns.+ * for every `gitLsFiles` call inside it, plus the "not a git repository"+ * verdict per directory. Doctor wraps its check run in one so the checks that+ * each list or probe the same source checkout (frontmatter scan, fence census,+ * slug collisions, the frontmatter hook) spawn git once instead of once per+ * check; code outside the scope always spawns. A git command that changes a+ * repository (sync-git.ts) drops the scope's memo (`invalidateGitListingCache`),+ * and an outside-repo verdict lapses as soon as a `.git` appears, changes or+ * goes away in the directory or above it.*/export function withGitListingCache<T>(fn: () => Promise<T>): Promise<T> {- return listingCache.run(new Map(), fn);+ return gitScope.run({ listings: new Map(), outside: new Map() }, fn);+}++/** Drop every listing and verdict memoized in the current scope (no-op outside one): call after changing a checkout inside it. */+export function invalidateGitListingCache(): void {+ const scope = gitScope.getStore();+ scope?.listings.clear();+ scope?.outside.clear();+}++/** The `.git` entries from `dir` up to the filesystem root: what decides whether git finds a repository there. */+function gitMarkers(dir: string): string {+ const seen: string[] = [];+ for (let at = dir; ; at = dirname(at)) {+ try {+ const st = lstatSync(join(at, '.git'));+ seen.push(`${at}\0${st.ino}\0${st.mtimeMs}`);+ } catch { /* no marker here */ }+ if (dirname(at) === at) return seen.join('\n');+ }+}++/** True when the current scope saw git report `dir` outside any repository and no `.git` marker changed since. */+export function knownOutsideGitRepo(dir: string): boolean {+ const scope = gitScope.getStore();+ const key = resolve(dir);+ const markers = scope?.outside.get(key);+ if (markers === undefined) return false;+ if (markers === gitMarkers(key)) return true;+ scope!.outside.delete(key);+ return false;+}++/** Record a failed git command run in `dir`: its stderr saying "not a git repository" is remembered for the current scope. */+export function noteGitFailure(dir: string, error: unknown): void {+ const scope = gitScope.getStore();+ const stderr = (error as { stderr?: unknown } | null)?.stderr;+ if (!scope || !/not a git repository/i.test(String(stderr ?? ''))) return;+ const key = resolve(dir);+ scope.outside.set(key, gitMarkers(key));}/** `git -C <dir> ls-files <args>` stdout, or null when git fails (memoized inside withGitListingCache). */export function gitLsFiles(dir: string, args: string[]): string | null {- const cache = listingCache.getStore();+ const cache = gitScope.getStore()?.listings;const key = `${dir}\0${args.join('\0')}`;- if (cache?.has(key)) return cache.get(key)!;- let stdout: string | null;+ const hit = cache?.get(key);+ if (hit !== undefined) return hit;+ if (knownOutsideGitRepo(dir)) return null;try {- stdout = execFileSync('git', ['-C', dir, 'ls-files', ...args], {- encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'],+ const stdout = execFileSync('git', ['-C', dir, 'ls-files', ...args], {+ encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],});- } catch {- stdout = null;+ cache?.set(key, stdout);+ return stdout;+ } catch (error) {+ noteGitFailure(dir, error);+ return null;}- cache?.set(key, stdout);- return stdout;}/**diff --git a/src/core/repair/timeline.ts b/src/core/repair/timeline.tsindex 64cee71d9f..628cd6a4b0 100644--- a/src/core/repair/timeline.ts+++ b/src/core/repair/timeline.ts@@ -12,7 +12,7 @@ import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';import { pendingTimelineRows } from '../persistence/canonical-projections.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';-import { retractRemovedTimelineEntries } from '../timeline-extract.ts';+import { retractRemovedTimelineEntries, type StoredTimelineTuple } from '../timeline-extract.ts';import { repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';interface TimelinePage { id: number; source_id: string; slug: string; compiled_truth: string; timeline: string | null }@@ -20,13 +20,23 @@ interface TimelinePage { id: number; source_id: string; slug: string; compiled_tconst BATCH = 200;/** Timeline rows of the page that an earlier stored version produced and its current text no longer does. */-async function removedRowIds(engine: BrainEngine, page: TimelinePage): Promise<Set<number>> {- const removed = await retractRemovedTimelineEntries(engine, page.slug, page.source_id, `${page.compiled_truth}\n${page.timeline ?? ''}`, { dryRun: true });+async function removedRowIds(engine: BrainEngine, page: TimelinePage, storedRows?: ReadonlyArray<StoredTimelineTuple>): Promise<Set<number>> {+ const removed = await retractRemovedTimelineEntries(engine, page.slug, page.source_id, `${page.compiled_truth}\n${page.timeline ?? ''}`, { dryRun: true, storedRows });return new Set(removed.map(row => Number(row.id)));}-async function classifyTimelinePage(engine: BrainEngine, page: TimelinePage) {- return pendingTimelineRows(engine, { ...page, timeline: page.timeline ?? '' }, await removedRowIds(engine, page));+/** The non-event timeline rows of each page, read once per batch (the retraction check's own per-page read). */+async function storedRowsByPage(engine: BrainEngine, pages: readonly TimelinePage[]): Promise<Map<number, StoredTimelineTuple[]>> {+ const byPage = new Map<number, StoredTimelineTuple[]>(pages.map(page => [Number(page.id), []]));+ if (!pages.length) return byPage;+ const rows = await engine.executeRaw<StoredTimelineTuple & { page_id: number }>(`SELECT t.page_id, t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary, t.detail+ FROM timeline_entries t WHERE t.page_id = ANY($1::bigint[]) AND t.event_page_id IS NULL`, [pages.map(page => page.id)]);+ for (const { page_id, ...row } of rows) byPage.get(Number(page_id))?.push(row);+ return byPage;+}++async function classifyTimelinePage(engine: BrainEngine, page: TimelinePage, storedRows?: ReadonlyArray<StoredTimelineTuple>) {+ return pendingTimelineRows(engine, { ...page, timeline: page.timeline ?? '' }, await removedRowIds(engine, page, storedRows));}/** Current counts for specific pages (doctor rechecks pages an earlier run of a multi-run pass found). */@@ -34,8 +44,9 @@ export async function recountTimelinePages(engine: BrainEngine, sourceIds: strinif (ids.length === 0) return [];const pages = await engine.executeRaw<TimelinePage>(`SELECT p.id,p.source_id,p.slug,p.compiled_truth,p.timeline FROM pages pWHERE p.id = ANY($1::bigint[]) AND p.source_id=ANY($2::text[]) AND p.deleted_at IS NULL`, [ids, sourceIds]);+ const stored = await storedRowsByPage(engine, pages);const counted = [];- for (const page of pages) counted.push({ id: page.id, ...await classifyTimelinePage(engine, page) });+ for (const page of pages) counted.push({ id: page.id, ...await classifyTimelinePage(engine, page, stored.get(Number(page.id))) });return counted;}@@ -52,6 +63,7 @@ export async function scanTimelineHistory(engine: BrainEngine, sourceIds: stringWHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.id>$2AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id=p.id AND t.event_page_id IS NULL)ORDER BY p.id LIMIT ${BATCH}`, [sourceIds, cursor]);+ const stored = await storedRowsByPage(engine, batch);for (const page of batch) {if ((budget.pages !== undefined && inspected >= budget.pages) || (budget.deadline !== undefined && Date.now() > budget.deadline)) {truncated = true;@@ -59,7 +71,7 @@ export async function scanTimelineHistory(engine: BrainEngine, sourceIds: string}inspected++;cursor = page.id;- const counts = await classifyTimelinePage(engine, page);+ const counts = await classifyTimelinePage(engine, page, stored.get(Number(page.id)));if (counts.materializable || counts.unrenderable) pages.push({ ...page, ...counts });}if (batch.length < BATCH) return { pages, inspected, truncated, cursor };diff --git a/src/core/sync-git.ts b/src/core/sync-git.tsindex 30f40d2063..68a8022131 100644--- a/src/core/sync-git.ts+++ b/src/core/sync-git.ts@@ -9,6 +9,7 @@ import { isAbsolute, join, relative, sep } from 'path';import type { BrainEngine } from './engine.ts';import { resolveSlugForPath, DEFAULT_SOURCE_ID } from './sync.ts';import { DELETE_BATCH_SIZE } from './engine-constants.ts';+import { invalidateGitListingCache, knownOutsideGitRepo, noteGitFailure } from './git-visible-files.ts';import { hasUnresolvedDbOnlyDeclaration, loadStorageConfig } from './storage-config.ts';/**@@ -281,6 +282,14 @@ export function resolveNoEmbed(return args.includes('--no-embed') || cfg?.embedding_disabled === true;}+/** Subcommands that never change a repository; any other one drops the doctor-run git memo (git-visible-files.ts). */+const READ_ONLY_GIT = new Set(['rev-parse', 'ls-files', 'ls-tree', 'cat-file', 'diff', 'log', 'show', 'status', 'rev-list', 'merge-base',+ 'for-each-ref', 'show-ref', 'describe', 'check-ignore', 'name-rev', 'blame', 'grep', 'check-attr', 'var', 'version']);++function noteGitCommand(args: string[]): void {+ if (!READ_ONLY_GIT.has(args[0] ?? '')) invalidateGitListingCache();+}+/*** Shell out to git with a generous maxBuffer.*@@ -307,6 +316,7 @@ export function git(timeoutMs = 30000,{ silenceStderr = false }: { silenceStderr?: boolean } = {},): string {+ noteGitCommand(args);return execFileSync('git', buildGitInvocation(repoPath, args, configs), {encoding: 'utf-8',timeout: timeoutMs,@@ -323,6 +333,7 @@ export function git(* live page was deleted on the corrupted evidence).*/export function gitRawOutput(repoPath: string, args: string[]): string {+ noteGitCommand(args);return execFileSync('git', buildGitInvocation(repoPath, args, []), {encoding: 'utf-8',timeout: 30000,@@ -347,8 +358,10 @@ export function gitRawOutput(repoPath: string, args: string[]): string {*/export function discoverGitRoot(inputPath: string): string {try {+ if (knownOutsideGitRepo(inputPath)) throw new Error('outside a git repository');return git(inputPath, ['rev-parse', '--show-toplevel'], [], 30000, { silenceStderr: true });- } catch {+ } catch (error) {+ noteGitFailure(inputPath, error);throw new Error(`Not inside a git repository: ${inputPath}. GBrain sync requires a git-initialized repo (or a subdirectory of one).`,);diff --git a/test/brain-writer-frontmatter-scan-head.test.ts b/test/brain-writer-frontmatter-scan-head.test.tsnew file mode 100644index 0000000000..80febfbb2b--- /dev/null+++ b/test/brain-writer-frontmatter-scan-head.test.ts@@ -0,0 +1,153 @@+/**+ * GBRA-75 wave 10: the doctor frontmatter scan's head-only parse+ * (`frontmatterScanHead`, `ScanOpts.frontmatterOnly`) must yield exactly the+ * findings of the whole-file parse.+ *+ * Protects: for every validation code, every warning and recovery status, and+ * the shapes the frontmatter readers disagree on (BOM, leading blank lines,+ * language selectors, CRLF, an indented or padded close, a `---x` line, an+ * empty block, a close at end of file, NUL bytes, `---` lines in the body),+ * the head parse gives the same errors, warnings, recovery, slug and import+ * hold as the full parse, and a shape it cannot prove falls back to the full+ * content unchanged. A seeded generator mixes the same fragments into 10,000+ * more documents. `scanBrainSources` with and without `frontmatterOnly`+ * returns the same report on a checkout holding every case.+ * Fails when: the head drops a finding the body carries (NUL bytes), a reader+ * closes the block somewhere else than the head ends, or a fallback case is+ * truncated.+ * Pure CPU plus a temp directory ($0); synthetic content only.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { frontmatterScanHead, scanBrainSources } from '../src/core/brain-writer.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { classifyImportHold, parseMarkdown, type ParseValidationCode } from '../src/core/markdown.ts';+import { slugifyPath } from '../src/core/sync.ts';++const ALL_CODES: ParseValidationCode[] = ['MISSING_OPEN', 'MISSING_CLOSE', 'YAML_PARSE', 'SLUG_MISMATCH', 'NULL_BYTES', 'NESTED_QUOTES', 'NON_STRING_FIELD', 'EMPTY_FRONTMATTER'];+const BODY = '# Heading\n\nBody text with [[a-link]].\n\n---\n\nAfter a thematic break.\n\n## Timeline\n\n- **2024-01-01** | Event\n';++/** [relative path, content, the head is shorter than the content]. */+const CASES: Array<[string, string, boolean]> = [+ ['clean.md', `---\ntitle: Clean\ntype: note\n---\n${BODY}`, true],+ ['crlf.md', `---\r\ntitle: Crlf\r\n---\r\n${BODY.replaceAll('\n', '\r\n')}`, true],+ ['missing-open.md', `No frontmatter.\n${BODY}`, false],+ ['empty-file.md', ' \n', false],+ ['missing-close.md', '---\ntitle: Missing Close\n# Heading\nBody.\n', false],+ ['missing-close-body-break.md', `---\ntitle: Closed By The Body Break\n${BODY}`, true],+ ['missing-close-eof.md', '---\ntitle: Missing Close', false],+ ['empty-frontmatter.md', `---\n---\n${BODY}`, false],+ ['empty-frontmatter-blank.md', `---\n\n---\n${BODY}`, true],+ ['nested-quotes.md', `---\ntitle: "Name "Nick" Last"\n---\n${BODY}`, true],+ ['yaml-unrecoverable.md', `---\ntitle: [unclosed\n---\n${BODY}`, true],+ ['needs-interpretation.md', `---\ntitle: [unclosed\ntags: a: b\n---\n${BODY}`, true],+ ['recoverable-colon.md', `---\ntitle: Ratio: 3:1 split\n---\n${BODY}`, true],+ ['recoverable-yaml.md', `---\ntitle: ok\nsummary: one: two\n three\n---\n${BODY}`, true],+ ['duplicate-key.md', `---\ntitle: One\ntitle: Two\n---\n${BODY}`, true],+ ['protected-dup.md', `---\nslug: a\nslug: b\n---\n${BODY}`, true],+ ['slug-mismatch.md', `---\ntitle: S\nslug: somewhere-else\n---\n${BODY}`, true],+ ['slug-equivalent.md', `---\ntitle: S\nslug: Slug-Equivalent\n---\n${BODY}`, true],+ ['non-string.md', `---\ntitle: 123\ntype: 2024\nslug: 7\n---\n${BODY}`, true],+ ['null-body.md', `---\ntitle: Null\n---\nBody \u0000 here.\n`, false],+ ['null-frontmatter.md', '---\ntitle: Null\u0000 Front\n---\nBody.\n', false],+ ['comment-value.md', `---\ntitle: #hashtag title\n---\n${BODY}`, true],+ ['comment-value-other.md', `---\ntitle: T\nsummary: #not-rescued\n---\n${BODY}`, true],+ ['bom.md', `\uFEFF---\ntitle: Bom\n---\n${BODY}`, false],+ ['leading-blank.md', `\n\n---\ntitle: Leading\n---\n${BODY}`, false],+ ['language-yaml.md', `---yaml\ntitle: Language\n---\n${BODY}`, false],+ ['language-json.md', `---json\n{"title": "Json"}\n---\n${BODY}`, false],+ ['language-other.md', `---toml\ntitle = "x"\n---\n${BODY}`, false],+ ['opener-padded.md', `--- \ntitle: Padded\n---\n${BODY}`, false],+ ['indented-close.md', `---\ntitle: Indented\n ---\nmore: x\n---\n${BODY}`, false],+ ['padded-close.md', `---\ntitle: Padded\n--- \n${BODY}`, false],+ ['tab-close.md', `---\ntitle: Tab\n---\t\n${BODY}`, false],+ ['dash-line.md', `---\ntitle: Dash\n---x\n---\n${BODY}`, false],+ ['four-dash.md', `---\ntitle: Four\n----\n---\n${BODY}`, false],+ ['block-scalar-dash.md', `---\ntitle: T\ndesc: |\n ---\n text\n---\n${BODY}`, false],+ ['close-at-eof.md', '---\ntitle: Eof\n---', false],+ ['close-then-eof.md', '---\ntitle: Eof\n---\n', false],+ ['crlf-close-eof.md', '---\r\ntitle: Eof\r\n---\r\n', false],+ ['mixed-eol.md', `---\r\ntitle: Mixed\n---\n${BODY}`, true],+ ['body-frontmatter.md', `---\ntitle: Twice\n---\n---\ntitle: Embedded\n---\n${BODY}`, true],+ ['body-only-dashes.md', `---\ntitle: T\n---\n---\n---\n---\n`, true],+ ['aliases.md', `---\ntitle: T\na: &a [x]\nb: [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a]\n---\n${BODY}`, true],+ ['array-root.md', `---\n- a\n- b\n---\n${BODY}`, true],+ ['scalar-root.md', `---\njust a string\n---\n${BODY}`, true],+ ['date-title.md', `---\ntitle: 2024-02-30\ntype: 2024-01-01\n---\n${BODY}`, true],+ ['unicode-space-close.md', `---\ntitle: T\n\u00a0---\n---\n${BODY}`, false],+ ['image.md', '---\ntitle: T\n---\n\u0000\u0001binary', false],+];++function verdict(content: string, rel: string) {+ const expectedSlug = slugifyPath(rel);+ const parsed = parseMarkdown(content, rel, { validate: true, expectedSlug });+ return { errors: parsed.errors, warnings: parsed.warnings, recovery: parsed.recovery ?? null, slug: parsed.slug,+ hold: classifyImportHold(parsed, { expectedSlug }) };+}++function expectSameVerdict(rel: string, content: string): boolean {+ const head = frontmatterScanHead(content);+ expect(content.startsWith(head)).toBe(true);+ if (head !== content) expect(verdict(head, rel)).toEqual(verdict(content, rel));+ return head !== content;+}++describe('frontmatterScanHead', () => {+ test('every case: same verdict on the head path, the full content on the fallback path', () => {+ const codes = new Set<string>();+ for (const [rel, content, fast] of CASES) {+ expect({ rel, fast: expectSameVerdict(rel, content) }).toEqual({ rel, fast });+ for (const e of verdict(content, rel).errors ?? []) codes.add(e.code);+ }+ expect([...codes].sort()).toEqual([...ALL_CODES].sort());+ });++ test('every validation code is reached on the head path except those it cannot prove', () => {+ const headCodes = new Set<string>();+ for (const [rel, content, fast] of CASES) if (fast) for (const e of verdict(content, rel).errors ?? []) headCodes.add(e.code);+ // MISSING_OPEN, MISSING_CLOSE and NULL_BYTES need the whole file; EMPTY_FRONTMATTER on `---\n---` too (an empty+ // block lets the colon quoting look past the close), but a blank-line block is still proven.+ expect([...headCodes].sort()).toEqual(['EMPTY_FRONTMATTER', 'NESTED_QUOTES', 'NON_STRING_FIELD', 'SLUG_MISMATCH', 'YAML_PARSE']);+ });++ test('10,000 generated documents: same verdict whenever the head path is taken', () => {+ const FM = ['title: Plain', 'title: Ratio: 3:1', 'title: "a "b" c"', 'title: [open', 'tags: a: b', 'title: 12', 'slug: x/y', 'slug: Other',+ 'type: note', 'summary: #comment', 'desc: |', ' ---', ' text', '---x', '----', ' ---', '--- ', 'k: &a [1]', 'j: *a', '', '# c', 'title: Dup', 'title: Dup',+ 'list:', ' - one', 'bad: : :', '\u0000', 'when: 2024-02-30', 'a: {open', 'title: \'single "q" ok\''];+ const BODY_LINES = ['Body', '---', '----', '# H', '- **2024-01-01** | E', '```', '[[x]]', '', '\u0000', '---\r', 'title: in body'];+ let seed = 42;+ const rand = (n: number) => { seed = (Math.imul(seed, 1103515245) + 12345) >>> 0; return (seed >>> 16) % n; };+ let fast = 0;+ for (let i = 0; i < 10_000; i++) {+ const eol = rand(5) === 0 ? '\r\n' : '\n';+ const fm = Array.from({ length: 1 + rand(5) }, () => FM[rand(FM.length)]!);+ const body = Array.from({ length: 1 + rand(8) }, () => BODY_LINES[rand(BODY_LINES.length)]!);+ const opener = rand(4) ? '---' : ['--- ', '---yaml', '\uFEFF---', '\n---'][rand(4)]!;+ const close = rand(4) ? '---' : [' ---', '--- ', '---\t', ''][rand(4)]!;+ const content = [opener, ...fm, close, ...body].join(eol) + (rand(4) ? eol : '');+ if (expectSameVerdict(`gen/doc-${i}.md`, content)) fast++;+ }+ expect(fast).toBeGreaterThan(1500);+ });+});++describe('scanBrainSources frontmatterOnly', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-fm-scan-head-'));+ afterAll(() => rmSync(root, { recursive: true, force: true }));++ test('the report equals the full-parse report on a checkout holding every case', async () => {+ for (const [rel, content] of CASES) {+ mkdirSync(dirname(join(root, 'cases', rel)), { recursive: true });+ writeFileSync(join(root, 'cases', rel), content);+ }+ const engine = { executeRaw: async () => [{ id: 'fixture', local_path: root }] } as unknown as BrainEngine;+ const strip = ({ scanned_at: _at, ...report }: Awaited<ReturnType<typeof scanBrainSources>>) => report;+ for (const strictMissingOpen of [false, true]) {+ const full = strip(await scanBrainSources(engine, { strictMissingOpen }));+ expect(full.total).toBeGreaterThan(20);+ expect(strip(await scanBrainSources(engine, { strictMissingOpen, frontmatterOnly: true }))).toEqual(full);+ }+ });+});diff --git a/test/fence-census.test.ts b/test/fence-census.test.tsindex 4809bcf4f5..985d9dd98a 100644--- a/test/fence-census.test.ts+++ b/test/fence-census.test.ts@@ -181,6 +181,29 @@ for (const backend of backends) {expect(await s.keys()).toEqual([]);}, 60_000);+ if (backend === 'pglite') {+ // GBRA-75 wave 10: the pass orders by the timestamp its keyset compares, not the text it returns, so small+ // batches never skip a page, even in a session time zone whose text offsets change (a DST fallback hour).+ test('the incremental pass in batches of one reads every page across a DST fallback in the session time zone', async () => {+ const s = await source(null);+ const slugs = ['notes/dst-a', 'notes/dst-b', 'notes/dst-c', 'notes/dst-d'];+ for (const slug of slugs) await s.stored(slug, CLEAN);+ await s.census();+ const [{ zone }] = await engine.executeRaw<{ zone: string }>(`SELECT current_setting('TimeZone') AS zone`);+ try {+ await engine.executeRaw(`SELECT set_config('TimeZone', 'America/New_York', false)`);+ // 01:20-04, 01:40-04, then 01:10-05 and 01:30-05: their text sorts differently from their instants.+ for (const [i, at] of ['2026-11-01T05:20:00Z', '2026-11-01T05:40:00Z', '2026-11-01T06:10:00Z', '2026-11-01T06:30:00Z'].entries()) {+ await engine.executeRaw('UPDATE pages SET compiled_truth=$1, updated_at=$2::timestamptz WHERE source_id=$3 AND slug=$4', [DETERMINISTIC, at, s.id, slugs[i]]);+ }+ await s.census({ batchSize: 1 });+ expect(await s.keys()).toEqual(slugs);+ } finally {+ await engine.executeRaw(`SELECT set_config('TimeZone', $1, false)`, [zone]);+ }+ }, 60_000);+ }+if (backend === 'postgres') {test('a writer transaction open during a pass is read after it commits, with no grace period', async () => {const s = await source(null);diff --git a/test/git-listing-memo.test.ts b/test/git-listing-memo.test.tsnew file mode 100644index 0000000000..b81ae9077f--- /dev/null+++ b/test/git-listing-memo.test.ts@@ -0,0 +1,120 @@+/**+ * GBRA-75 wave 10: the doctor-run git memo (src/core/git-visible-files.ts).+ *+ * Protects: inside one `withGitListingCache` run a directory git reported+ * outside any repository is not probed again (`git ls-files`, `discoverGitRoot`+ * and the census HEAD probe share the verdict), and the memo never hides a+ * change: a git command that changes a repository (sync-git.ts) or an explicit+ * `invalidateGitListingCache()` drops it, so a file added mid-run is listed by+ * the next listing; a repository created mid-run (here by a plain `git init`+ * that no hook sees) is found by the next probe because the verdict lapses+ * when a `.git` marker appears; and nothing outlives the run.+ * Fails when: a listing or verdict survives an in-run write or `git init`, the+ * memo leaks past its scope, or a non-repository directory is probed more than+ * once per run.+ * Temp directories and the system git ($0); synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { collectGitVisibleFiles, invalidateGitListingCache, withGitListingCache } from '../src/core/git-visible-files.ts';+import { discoverGitRoot, git } from '../src/core/sync-git.ts';++const root = mkdtempSync(join(tmpdir(), 'gbrain-git-memo-'));+const log = join(root, 'git.log');+const ENV = { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_CEILING_DIRECTORIES: root };+const saved: Record<string, string | undefined> = {};+let n = 0;++const all = () => true;+const names = (dir: string) => collectGitVisibleFiles(dir, all)?.map(p => p.slice(dir.length + 1)) ?? null;+const spawns = () => (existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean).length : 0);+function freshDir(repo: boolean): string {+ const dir = join(root, `d${n++}`);+ mkdirSync(dir);+ writeFileSync(join(dir, 'a.md'), 'a\n');+ if (repo) {+ execFileSync('git', ['-C', dir, 'init', '-q'], { stdio: 'ignore' });+ execFileSync('git', ['-C', dir, 'add', 'a.md'], { stdio: 'ignore' });+ }+ return dir;+}++beforeAll(() => {+ // A git shim on PATH counts every spawn this process makes.+ const real = execFileSync('which', ['git'], { encoding: 'utf8' }).trim();+ const bin = join(root, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'git'), `#!/bin/sh\necho "$*" >> '${log}'\nexec '${real}' "$@"\n`);+ chmodSync(join(bin, 'git'), 0o755);+ for (const [k, v] of Object.entries({ ...ENV, PATH: `${bin}:${process.env.PATH}` })) {+ saved[k] = process.env[k];+ process.env[k] = v;+ }+});+afterAll(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ rmSync(root, { recursive: true, force: true });+});++describe('withGitListingCache memo', () => {+ test('a non-repository directory is probed once per run by listings, discoverGitRoot and repeats', async () => {+ const dir = freshDir(false);+ const before = spawns();+ await withGitListingCache(async () => {+ expect(names(dir)).toBeNull();+ expect(() => discoverGitRoot(dir)).toThrow(`Not inside a git repository: ${dir}`);+ expect(names(dir)).toBeNull();+ expect(() => discoverGitRoot(dir)).toThrow(`Not inside a git repository: ${dir}`);+ });+ expect(spawns() - before).toBe(1);+ // Outside a run every call spawns, as before.+ expect(names(dir)).toBeNull();+ expect(() => discoverGitRoot(dir)).toThrow(`Not inside a git repository: ${dir}`);+ expect(spawns() - before).toBe(3);+ });++ test('a file added mid-run through a sync-git write is listed by the next listing', async () => {+ const dir = freshDir(true);+ await withGitListingCache(async () => {+ expect(names(dir)).toEqual(['a.md']);+ writeFileSync(join(dir, 'b.md'), 'b\n');+ git(dir, ['add', 'b.md']);+ expect(names(dir)).toEqual(['a.md', 'b.md']);+ });+ });++ test('a file written mid-run is listed after invalidateGitListingCache', async () => {+ const dir = freshDir(true);+ await withGitListingCache(async () => {+ expect(names(dir)).toEqual(['a.md']);+ writeFileSync(join(dir, 'c.md'), 'c\n');+ invalidateGitListingCache();+ expect(names(dir)).toEqual(['a.md', 'c.md']);+ });+ });++ test('a repository created mid-run with no hook is found by the next listing and discoverGitRoot', async () => {+ const dir = freshDir(false);+ await withGitListingCache(async () => {+ expect(names(dir)).toBeNull();+ expect(() => discoverGitRoot(dir)).toThrow('Not inside a git repository');+ execFileSync('/usr/bin/env', ['git', '-C', dir, 'init', '-q'], { stdio: 'ignore' });+ expect(names(dir)).toEqual(['a.md']);+ expect(discoverGitRoot(dir)).toBe(execFileSync('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim());+ });+ });++ test('nothing outlives the run: a repository created after it is seen at once', async () => {+ const dir = freshDir(false);+ await withGitListingCache(async () => { expect(names(dir)).toBeNull(); });+ execFileSync('git', ['-C', dir, 'init', '-q'], { stdio: 'ignore' });+ expect(names(dir)).toEqual(['a.md']);+ await withGitListingCache(async () => { expect(names(dir)).toEqual(['a.md']); });+ });+});diff --git a/test/git-visible-files.test.ts b/test/git-visible-files.test.tsindex fe9fc0efa6..7dd47870ef 100644--- a/test/git-visible-files.test.ts+++ b/test/git-visible-files.test.ts@@ -201,13 +201,16 @@ describe('withGitListingCache — doctor-scoped ls-files memo (GBRA-68)', () =>});});- test('a failed listing is cached as null inside the scope', async () => {+ // GBRA-75 wave 10: the outside-repo verdict is memoized only until a `.git` appears, so a repository created+ // inside the scope is listed by the next call (test/git-listing-memo.test.ts covers the spawn count).+ test('a failed listing is not reused inside the scope once a repository appears', async () => {const dir = mkdtempSync(join(tmpdir(), 'gbrain-f6-cache-nogit-'));cleanups.push(dir);await withGitListingCache(async () => {expect(collectGitVisibleFiles(dir, md)).toBeNull();- git(dir, ['init', '-q', '-b', 'main']);expect(collectGitVisibleFiles(dir, md)).toBeNull();+ git(dir, ['init', '-q', '-b', 'main']);+ expect(collectGitVisibleFiles(dir, md)).toEqual([]);});expect(collectGitVisibleFiles(dir, md)).toEqual([]);});