mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* fix(frontmatter): prune vendor dirs at descent + bounded wall-clock with partial-state surfacing Two production-grade fixes for the v0.38.2.0 wave (supersedes PR #1287). Root cause Fix 1 (the bug that hung gbrain doctor on 216K-page brains): both brain-writer.ts:walkDir and frontmatter.ts:collectFiles recursed into every subdirectory without calling pruneDir, the canonical descent-time pruner used by sync/extract/transcript-discovery since v0.35.5.0. On brains that double as code workspaces, the walkers stat'd hundreds of thousands of entries under node_modules / .git / .obsidian / *.raw / ops that isSyncable filtered out at the leaf — paying the IO cost for nothing. Wiring pruneDir at descent (with the v0.37.7.0 #1169 submodule-gitfile check) eliminates the bulk of the wall-clock pain. Fix 2 (codex outside-voice C1): AbortSignal.timeout cannot interrupt the synchronous walker — readdirSync / lstatSync / readFileSync block the event loop, so timer callbacks never fire mid-walk. The load-bearing wall-clock bound is now a deadline check inside scanOneSource's visit callback (Date.now() > opts.deadline). AbortSignal still works at source boundaries. Shape changes (codex C2 + C4): - ScanOpts: + deadline?: number, + dbPageCountForSource hook, + visitDir test seam - PerSourceReport: + status: 'scanned' | 'partial' | 'skipped', + files_scanned, + db_page_count - AuditReport: + partial: boolean, + aborted_at_source: string | null - ok = grandTotal === 0 && !partial (a clean prefix from a timed-out scan no longer falsely reports clean) walkDir + collectFiles now exported with an optional visitDir callback for the regression suite. Production callers don't pass it. Tests: - test/brain-writer-walk-prune.test.ts (new, 12 cases): visitDir-based descent-time pruning assertions for both walkers. Pins the property output-based tests can't catch (isSyncable rejects vendor files at the leaf — so a test checking only output passes under the original bug). - test/brain-writer-partial-scan.test.ts (new, 5 cases): deadline + partial state + ok-after-abort + numerator/denominator coverage. Uses deadline, NOT AbortSignal, since codex C1 proved abort can't interrupt sync. - test/brain-writer.test.ts: existing "abort mid-scan" test refit to the new partial-state contract (per_source has 'skipped' entries instead of being empty — gives doctor visibility into which sources weren't checked). - test/migrations-v0_22_4.test.ts: AuditReport fixture extended with the new required fields. Plan + cross-model review: ~/.claude/plans/system-instruction-you-are-working-hidden-lollipop.md Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(doctor): wire deadline + partial-state into frontmatter_integrity check Adopts the v0.38.2.0 ScanBrainSources surface in doctor's frontmatter_integrity check. - AbortSignal.timeout(fmTimeoutMs) for between-source bound. - deadline = Date.now() + fmTimeoutMs (the load-bearing mid-walk bound — codex C1 caught that AbortSignal alone can't fire inside the sync walker). - GBRAIN_DOCTOR_FM_TIMEOUT_MS env override (default 30000ms; invalid values fall back to default rather than crash). - Per-source DB denominator via SELECT COUNT(*) FROM pages WHERE source_id = $1 AND deleted_at IS NULL (codex C3: deleted_at filter so soft-deleted pages don't inflate the count). - Honest partial-render: "PARTIAL — scanned ~N files (source has ~M pages in DB), K issue(s) so far" instead of "scanned ~N of M pages" (codex C3 — the two populations are overlapping but not identical sets). - "NOT SCANNED (timeout — run gbrain frontmatter validate <id>)" per skipped source so the user knows which sources didn't get checked. - Catch block simplified to "unexpected error only" (codex D4 — the AbortError special case from PR #1287 was unreachable in a sync walker). Tests: test/doctor-frontmatter-partial.test.ts (new, 11 cases) — structural source-grep pins on every load-bearing render string plus the simplified- catch contract. Behavioral coverage is deferred to the heavy script (tests/heavy/frontmatter_scan_wallclock.sh, T6) because runDoctor calls process.exit unconditionally and can't be driven from bun:test directly; refactoring runDoctor to return rather than exit is a separate TODO. Plan + cross-model review: ~/.claude/plans/system-instruction-you-are-working-hidden-lollipop.md Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: v0.38.2.0 release notes, Phase 2 design sketch, heavy wall-clock smoke - CHANGELOG.md: ELI10-lead-first release entry per CLAUDE.md voice rules. Names the user-visible behavior change, the per-source partial render, the performance numbers table, the "things to watch" caveats. Credits @garrytan-agents for PR #1287's diagnosis. - VERSION + package.json: 0.37.11.0 -> 0.38.2.0. - docs/architecture/frontmatter-scan-incremental.md: Phase 2 design sketch for DB-backed scan state. Schema, migration shape, writer paths (sync-side UPSERT + incremental scan + autopilot cycle phase), doctor reader, sequencing concerns, two-phase rollout plan. Starting point for the follow-up PR — sub-second steady-state doctor needs incremental state, but the schema migration carries its own contract surface (forward-reference bootstrap, schema-drift E2E, PGLite-vs-Postgres parity) that deserves its own focused PR. - tests/heavy/frontmatter_scan_wallclock.sh (new, manual / nightly per tests/heavy/README.md): seeds a synthetic 60K-file brain (10K real + 50K under node_modules/) and asserts gbrain doctor completes in <15s with frontmatter_integrity: ok. Codex C7 caught that the original plan's 1500-file budget was too small to be a meaningful guard — at that scale the test passes BEFORE AND AFTER the fix, proving nothing. 60K is the minimum that catches the descent-into-vendor-trees regression. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: adversarial review followups — CLI hint, deadline-vs-await race, between-source breadcrumb Codex adversarial review caught 4 real bugs in the v0.38.2.0 wave. All four fixed before ship. #1 (user-facing): `gbrain frontmatter validate` takes a filesystem PATH, not a source id. Pre-fix the NOT SCANNED hint pointed users at `gbrain frontmatter validate src-a` — which would fail with "no such directory", breaking the very remediation this PR ships to give them. Fix: render `src.source_path` instead. #2 (correctness): between sources, `await dbPageCountForSource(src.id)` ran unchecked. A slow query could blow past the deadline, then scanOneSource was still called and returned `status='partial'` with `files_scanned=0` — misleading ("partial scan" when actually zero files were scanned). Fix: add a post-await deadline re-check; mark source + remainder as 'skipped' if the budget already burned. #3 (UX): when the outer-loop deadline check fired BETWEEN sources, `aborted_at_source` stayed null and the doctor message said "PARTIAL SCAN" with no source name. Fix: stamp `aborted_at_source` with the source we were about to start. #4 (correctness): the COUNT query had no per-call deadline. A wedged Postgres pool could make a single COUNT hang past the budget and defeat the wall-clock guarantee. Fix: Promise.race against the remaining deadline; on timeout, resolve null and the post-await re-check (#2) marks the source skipped. Tests: 3 new regression cases in brain-writer-partial-scan.test.ts pinning the fixed contracts (skipped-vs-partial under slow COUNT, hanging COUNT within deadline, aborted_at_source before any source starts). 8648 pass / 0 fail across the full suite. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(README): refresh production-brain stats — 8.2x pages, 5.6x people, 7.4x companies Pre-update line (months stale): "17,888 pages, 4,383 people, 723 companies, 21 cron jobs running autonomously, built in 12 days." Fresh counts from ~/git/brain (the wintermute production brain): - pages: 17,888 → 146,646 (8.2x) - people: 4,383 → 24,585 (5.6x) - companies: 723 → 5,339 (7.4x) - cron jobs running: 21 → 66 (113 total, 66 enabled per ~/git/wintermute/workspace/ops/cron-snapshot.json) Dropped "built in 12 days" — at 146K pages the initial-velocity claim is stale narrative that no longer matches the current scale story. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
151 lines
7.2 KiB
TypeScript
151 lines
7.2 KiB
TypeScript
/**
|
|
* v0.38.2.0 — descent-time pruning regression suite.
|
|
*
|
|
* The original bug (PR #1287 reported, this PR fixes): `gbrain doctor` hung
|
|
* indefinitely on a 216K-page brain because the frontmatter walker descended
|
|
* into every node_modules / .git / .obsidian / *.raw / ops subtree on disk
|
|
* and let `isSyncable` filter at the leaf — paying the IO cost of stat'ing
|
|
* hundreds of thousands of vendor entries that were never going to be parsed.
|
|
*
|
|
* Why output-based tests don't catch this: `isSyncable` rejects the
|
|
* vendor-tree files at the leaf, so a test that just asserts "no bad
|
|
* markdown reported" passes BOTH before and after Fix 1 (codex outside-voice
|
|
* C6). The load-bearing assertion is `walker did NOT DESCEND` — fired by
|
|
* the new `visitDir` test seam.
|
|
*
|
|
* This file covers both walkers that were missing pruneDir:
|
|
* - brain-writer.ts:walkDir (driven by scanBrainSources / doctor)
|
|
* - frontmatter.ts:collectFiles (driven by `gbrain frontmatter validate`)
|
|
*/
|
|
import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
|
|
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
|
|
import { join } from 'path';
|
|
import { tmpdir } from 'os';
|
|
import { walkDir } from '../src/core/brain-writer.ts';
|
|
import { collectFiles } from '../src/commands/frontmatter.ts';
|
|
|
|
let root: string;
|
|
|
|
beforeAll(() => {
|
|
root = mkdtempSync(join(tmpdir(), 'walk-prune-'));
|
|
// Real syncable files under regular dirs — walker MUST descend here.
|
|
mkdirSync(join(root, 'people'), { recursive: true });
|
|
writeFileSync(join(root, 'people', 'alice.md'), '---\ntitle: Alice\n---\n\nbody\n');
|
|
mkdirSync(join(root, 'concepts', 'subdir'), { recursive: true });
|
|
writeFileSync(join(root, 'concepts', 'subdir', 'thing.md'), '---\ntitle: Thing\n---\n\nbody\n');
|
|
// Vendor / hidden / generated trees — walker MUST NOT descend.
|
|
mkdirSync(join(root, 'node_modules', 'fake-pkg'), { recursive: true });
|
|
writeFileSync(join(root, 'node_modules', 'fake-pkg', 'README.md'), '# Should not be visited\n');
|
|
mkdirSync(join(root, '.git', 'objects'), { recursive: true });
|
|
writeFileSync(join(root, '.git', 'config'), '[core]\n');
|
|
mkdirSync(join(root, '.obsidian'), { recursive: true });
|
|
writeFileSync(join(root, '.obsidian', 'workspace.json'), '{}');
|
|
mkdirSync(join(root, 'people', 'pedro.raw'), { recursive: true });
|
|
writeFileSync(join(root, 'people', 'pedro.raw', 'source.md'), '---\ntitle: should not visit\n---\n');
|
|
mkdirSync(join(root, 'ops', 'logs'), { recursive: true });
|
|
writeFileSync(join(root, 'ops', 'logs', 'run.md'), '# nope\n');
|
|
// Nested node_modules — must also be pruned, not just at the root.
|
|
mkdirSync(join(root, 'people', 'tools', 'node_modules', 'inner'), { recursive: true });
|
|
writeFileSync(join(root, 'people', 'tools', 'node_modules', 'inner', 'a.md'), '---\ntitle: nope\n---\n');
|
|
// Git-submodule pattern: a dir containing `.git` as a FILE (gitfile).
|
|
mkdirSync(join(root, 'people', 'submod'), { recursive: true });
|
|
writeFileSync(join(root, 'people', 'submod', '.git'), 'gitdir: ../../.git/modules/submod\n');
|
|
writeFileSync(join(root, 'people', 'submod', 'README.md'), '---\ntitle: submod page\n---\n');
|
|
});
|
|
|
|
afterAll(() => {
|
|
rmSync(root, { recursive: true, force: true });
|
|
});
|
|
|
|
describe('walkDir (brain-writer.ts) — descent-time pruning', () => {
|
|
test('does NOT descend into node_modules at any depth', () => {
|
|
const visited: string[] = [];
|
|
walkDir(root, () => {}, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.includes('/node_modules'))).toBe(false);
|
|
});
|
|
|
|
test('does NOT descend into .git', () => {
|
|
const visited: string[] = [];
|
|
walkDir(root, () => {}, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.endsWith('/.git') || d.includes('/.git/'))).toBe(false);
|
|
});
|
|
|
|
test('does NOT descend into .obsidian (dot-prefix heuristic)', () => {
|
|
const visited: string[] = [];
|
|
walkDir(root, () => {}, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.includes('/.obsidian'))).toBe(false);
|
|
});
|
|
|
|
test('does NOT descend into *.raw sidecar dirs', () => {
|
|
const visited: string[] = [];
|
|
walkDir(root, () => {}, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.endsWith('.raw'))).toBe(false);
|
|
});
|
|
|
|
test('does NOT descend into git submodule directories (.git as FILE)', () => {
|
|
const visited: string[] = [];
|
|
walkDir(root, () => {}, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.endsWith('/people/submod'))).toBe(false);
|
|
});
|
|
|
|
test('DOES descend into regular subdirs and visits .md files there', () => {
|
|
const visited: string[] = [];
|
|
const files: string[] = [];
|
|
walkDir(root, (f) => { files.push(f); }, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.endsWith('/people'))).toBe(true);
|
|
expect(visited.some(d => d.endsWith('/concepts/subdir'))).toBe(true);
|
|
expect(files.some(f => f.endsWith('/people/alice.md'))).toBe(true);
|
|
expect(files.some(f => f.endsWith('/concepts/subdir/thing.md'))).toBe(true);
|
|
// And explicitly does NOT visit the file under node_modules.
|
|
expect(files.some(f => f.includes('/node_modules/'))).toBe(false);
|
|
});
|
|
|
|
test('regression: pre-v0.38.2.0 walker would have descended into node_modules and stat\'d every entry', () => {
|
|
// This is the load-bearing assertion. If a future contributor removes
|
|
// the `pruneDir(name, dir)` gate in walkDir, this test fails because
|
|
// visitDir would be called with node_modules paths.
|
|
const descents: string[] = [];
|
|
walkDir(root, () => {}, (d) => descents.push(d));
|
|
const vendor = descents.filter(d => /\/(node_modules|\.git|\.obsidian|ops)(\/|$)/.test(d) || /\.raw$/.test(d));
|
|
expect(vendor).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('collectFiles (frontmatter.ts) — descent-time pruning parity', () => {
|
|
test('does NOT descend into node_modules at any depth', () => {
|
|
const visited: string[] = [];
|
|
collectFiles(root, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.includes('/node_modules'))).toBe(false);
|
|
});
|
|
|
|
test('does NOT descend into .git, .obsidian, *.raw, or ops', () => {
|
|
const visited: string[] = [];
|
|
collectFiles(root, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.includes('/.git'))).toBe(false);
|
|
expect(visited.some(d => d.includes('/.obsidian'))).toBe(false);
|
|
expect(visited.some(d => d.endsWith('.raw'))).toBe(false);
|
|
expect(visited.some(d => d.endsWith('/ops') || d.includes('/ops/'))).toBe(false);
|
|
});
|
|
|
|
test('does NOT descend into git submodule directories', () => {
|
|
const visited: string[] = [];
|
|
collectFiles(root, (dir) => visited.push(dir));
|
|
expect(visited.some(d => d.endsWith('/people/submod'))).toBe(false);
|
|
});
|
|
|
|
test('DOES collect .md files under regular subdirs', () => {
|
|
const files = collectFiles(root);
|
|
expect(files.some(f => f.endsWith('/people/alice.md'))).toBe(true);
|
|
expect(files.some(f => f.endsWith('/concepts/subdir/thing.md'))).toBe(true);
|
|
expect(files.some(f => f.includes('/node_modules/'))).toBe(false);
|
|
expect(files.some(f => f.includes('/.git/'))).toBe(false);
|
|
expect(files.some(f => f.includes('.raw/'))).toBe(false);
|
|
});
|
|
|
|
test('single-file target returns that file unchanged (no walk)', () => {
|
|
const target = join(root, 'people', 'alice.md');
|
|
const files = collectFiles(target);
|
|
expect(files).toEqual([target]);
|
|
});
|
|
});
|