Files
gbrain/docs/architecture/frontmatter-scan-incremental.md
T
3de06b6c29 v0.38.2.0 fix(doctor): bounded frontmatter scan + partial-state surfacing (supersedes #1287) (#1297)
* 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>
2026-05-22 09:29:59 -07:00

8.2 KiB

Frontmatter scan: DB-backed incremental state (Phase 2 design sketch)

Status: Designed, not built. Captured here as the starting point for the follow-up PR after v0.38.2.0.

Why this exists

v0.38.2.0 fixed the load-bearing bug class that caused gbrain doctor to hang on large brains: the disk walker descended into node_modules/, .git/, and other vendor trees on every tick. After that fix doctor completes in seconds on most brains, and bounded wall-clock (default 30s, with honest partial-state surfacing) on any brain.

But the steady-state cost of frontmatter_integrity is still O(N) in real syncable pages: every doctor tick re-walks the filesystem and re-parses every .md file. For users with 200K+ pages the steady-state cost is in the seconds even after Fix 1. For sub-second steady-state doctor (the right shape for cron-monitored health checks), the scan needs to become incremental.

This document captures the Phase 2 design before the follow-up PR starts, so the implementer doesn't have to re-derive it.

Goal

Doctor's frontmatter_integrity check completes in O(1) SQL queries regardless of brain size, with the same per-source breakdown and partial- state semantics as v0.38.2.0's bounded-walk approach. Incremental refresh runs as a sync-side write + an autopilot cycle phase, so the steady-state work is amortized across the workflow that already touches each file.

Schema

New table:

CREATE TABLE frontmatter_scan_state (
  source_id    TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
  path         TEXT NOT NULL,  -- relative to source.local_path
  mtime_ms     BIGINT NOT NULL,
  content_hash TEXT NOT NULL,  -- sha256 of file content at scan time
  codes        JSONB NOT NULL DEFAULT '[]'::jsonb,  -- ParseValidationCode[]
  last_scanned_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (source_id, path)
);

CREATE INDEX frontmatter_scan_state_has_issues_idx
  ON frontmatter_scan_state (source_id)
  WHERE codes != '[]'::jsonb;

Why these columns:

  • mtime_ms + content_hash: incremental check picks one. mtime is faster (no read); content_hash is the truth (defeats touch-without-change cases). The incremental walker uses mtime as a fast gate and content_hash as the fallback when mtime suggests change.
  • codes JSONB: per-row error code list, NULL/[] means clean. Doctor aggregates with jsonb_array_length(codes) > 0.
  • Partial index on WHERE codes != '[]'::jsonb: doctor's aggregate query only walks rows with issues, which is a small fraction of pages.

This follows the canonical applyForwardReferenceBootstrap pattern in src/core/pglite-engine.ts (and postgres-engine.ts) — the new column / table additions go into the bootstrap probe set per CLAUDE.md so old brains walking forward through the schema chain don't wedge on the table not existing.

Migration shape

// src/core/migrate.ts — append after the v80 entry
const migrations = [
  // ...existing v1-v80...
  {
    version: 81,
    name: 'frontmatter_scan_state',
    sql: `
      CREATE TABLE IF NOT EXISTS frontmatter_scan_state (...);
      CREATE INDEX IF NOT EXISTS frontmatter_scan_state_has_issues_idx ...;
    `,
  },
];

Plus the forward-reference probe entries in both engine bootstraps. Plus the REQUIRED_BOOTSTRAP_COVERAGE extension in test/schema-bootstrap-coverage.test.ts.

Writers

Two paths write rows:

  1. Sync-side write (canonical). src/core/sync.ts:performSync already parses every file it touches. After the existing parseMarkdown call, UPSERT into frontmatter_scan_state with the file's path / mtime / content_hash / codes. Cost: one row per file synced. Zero extra parse work — the parse already happened.

  2. Incremental scan (gbrain frontmatter scan --incremental). Walks the disk via walkBrainTree, for each file checks mtime > last_scanned_at OR content_hash != stored, only re-parses changed files. Most ticks: zero work after the first full backfill. Also exposed as an autopilot cycle phase (frontmatter_scan) so it runs alongside the other periodic maintenance phases.

The incremental walker handles two cases sync misses:

  • Files edited outside sync (user opens an editor, saves, never git commits).
  • Sources whose local_path isn't a git repo (sync only sees git-touched files).

Doctor reader

// src/commands/doctor.ts:frontmatter_integrity (Phase 2 shape)
const rows = await engine.executeRaw<{ source_id: string; issues: number }>(
  `SELECT source_id, count(*) FILTER (WHERE jsonb_array_length(codes) > 0)::int AS issues
   FROM frontmatter_scan_state
   GROUP BY source_id`,
);

One SQL query, constant time regardless of brain size. The partial-state surfacing from v0.38.2.0 stays — when frontmatter_scan_state is stale (no rows for a registered source, or last_scanned_at >24h old for any source), doctor warns about freshness rather than reporting potentially- stale data as authoritative.

Sequencing concerns

  1. First-ever scan. A fresh upgrade has no rows in frontmatter_scan_state. Two options:

    • Lazy: doctor reports "no scan state yet; run gbrain frontmatter scan --incremental once" (operator-driven).
    • Eager: the migration that creates the table also enqueues an autopilot cycle job to do the first full scan.

    Recommendation: lazy, with a clear hint. The autopilot path is heavier surface (must add the new frontmatter_scan phase to the existing cycle.ts machinery + the doctor-routed background job system).

  2. Source archival / deletion. frontmatter_scan_state has ON DELETE CASCADE on sources(id), so soft-delete + 72h TTL + purge already clean it up. No additional logic needed.

  3. Path renames inside a source. Sync would DELETE the old row by path (via a periodic reconcile step) and INSERT the new row. Without that step, the table accumulates stale path rows. Either:

    • A reconcile step in the incremental scanner: any path-row not seen during the walk gets deleted.
    • Or: doctor reports "N stale rows in frontmatter_scan_state" as a freshness signal, with gbrain frontmatter scan --reconcile as the remediation.

Cost estimate

  • One UPSERT per file synced. Negligible vs the parse + DB write that sync already does.
  • Incremental refresh runtime: dominated by mtime stats. ~ms per 1000 files on SSD.
  • Doctor read: one indexed SQL query. Sub-100ms on any brain size.

What this design deliberately does NOT do

  • Replace v0.38.2.0's bounded-walk safety net. Phase 2 makes the steady-state cheap, but the disk walker (with its deadline check) stays as the source-of-truth fallback for sources whose scan state is missing or stale. Belt-and-suspenders.
  • Introduce a separate frontmatter validation rule set. Reuses parseMarkdown(..., {validate: true}) and the existing ParseValidationCode enum. Single source of truth.
  • Add a new background daemon. Wires into the existing autopilot-cycle Minion handler as a new phase, alongside sync / extract / embed / etc.

Open questions for the implementer

  1. Path normalization. pages.source_path and the disk walker's relative path computation are similar but not identical (slashes, leading ./, etc.). The incremental scanner needs to match what sync stores so UPSERTs key correctly. Audit before writing.
  2. Soft-delete interaction. A page that gets soft-deleted in the DB (v0.26.5) still has a file on disk. Should the incremental scan continue to track its frontmatter state? Probably yes (so a future restore_page doesn't surprise with stale frontmatter), but worth confirming with the soft-delete owner.
  3. Two-phase rollout. Land the table + writes first, let it backfill for a release cycle, then switch the doctor reader. Avoids the "Phase 2 ships but the table is empty" case where doctor regresses to reporting "no scan state."

TODO file entry

- [ ] Implement Phase 2: DB-backed frontmatter scan state.
      Design lives at docs/architecture/frontmatter-scan-incremental.md.
      Schema migration v81 + sync-side UPSERT + incremental scan command
      + autopilot cycle phase + doctor reader. Two-phase rollout: ship
      table + writes first; flip the reader one release later.