Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(fence-repair): source-scoped fence census with resumable scans and purge-exempt state (#6188)

garrytan683abc35ceae
diff --git a/src/core/fence-repair/attempts.ts b/src/core/fence-repair/attempts.ts
index 670c3065a5..83309b594a 100644
--- a/src/core/fence-repair/attempts.ts
+++ b/src/core/fence-repair/attempts.ts
@@ -21,10 +21,9 @@
* so it counts a crash, and MAX_CRASHES_PER_MEMO crashes reject the memo.
*
* Records carry location and reason codes only (gate letter, row numbers),
- * never claim text, holder names or cell values. The 7-day op_checkpoints
- * purge (`purgeStaleCheckpoints`) does not yet exempt this op; the record
- * carries `source_id` and `incarnation` so it can join the sync-hold
- * exemption, which keeps a row while its source incarnation lives.
+ * never claim text, holder names or cell values. The record carries
+ * `source_id` and `incarnation`, so the 7-day op_checkpoints purge
+ * (`purgeStaleCheckpoints`) keeps it while its source incarnation lives.
*/
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
diff --git a/src/core/fence-repair/census-store.ts b/src/core/fence-repair/census-store.ts
new file mode 100644
index 0000000000..7956f317c7
--- /dev/null
+++ b/src/core/fence-repair/census-store.ts
@@ -0,0 +1,197 @@
+/**
+ * #6188 durable state of the fence census: what the candidate finder found,
+ * where its scans stopped, and the per-source normalization trend. All of it
+ * lives in `op_checkpoints`, so it needs no schema migration.
+ *
+ * - `fence-candidate`: one row per (source, incarnation, page slug) whose
+ * stored page (`page`) or working-tree file (`file`) fails the coordinated
+ * fence step. Each part is bound to the bytes it judged (sha256, page id,
+ * `updated_at`, file mtime) and carries location and reason codes only.
+ * - `fence-scan`: one row per (source, incarnation): the DB watermark and
+ * one-time backfill cursor, the file-walk cursor and the last census.
+ * - `fence-trend`: what Tier 1 normalized, per source: one row per managed
+ * sync run (replaced as the run's running total grows) and one row per
+ * normalized page write (written once per request, so a replayed
+ * publication never counts twice). Rows carry fix classes and writers
+ * (receipt principal kind or top directory), never a path or cell value.
+ *
+ * Candidate and scan rows survive the 7-day `op_checkpoints` purge while
+ * their source incarnation lives (`purgeStaleCheckpoints`); trend rows age
+ * out with it, which is all a 7-day trend needs.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { FenceSection, FenceKind, FenceTier } from './types.ts';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+export const FENCE_CANDIDATE_OP = 'fence-candidate';
+export const FENCE_SCAN_OP = 'fence-scan';
+export const FENCE_TREND_OP = 'fence-trend';
+
+/** Where a candidate's first issue sits: location only. */
+export interface CandidateLocation { fence: FenceKind; section: FenceSection; rows: number[]; columns: string[]; line: number | null }
+
+/** One judged copy of a page (stored body or working-tree file). */
+export interface CandidateFinding {
+ tier: FenceTier;
+ /** Residual reasons, or the Tier 1 fix classes when the step normalizes it (tier deterministic). */
+ reasons: string[];
+ location: CandidateLocation | null;
+ /** sha256 of the judged sections (pages) or file bytes (files). */
+ sha256: string;
+ checked_at: string;
+}
+export interface PageFinding extends CandidateFinding { page_id: number; updated_at: string; content_hash: string | null; source_path: string | null }
+export interface FileFinding extends CandidateFinding { path: string; mtime_ms: number }
+
+export interface CandidateRecord {
+ version: 1;
+ source_id: string;
+ incarnation: string;
+ /** The page slug the stored page or file maps to. */
+ key: string;
+ page?: PageFinding;
+ file?: FileFinding;
+}
+
+/** The DB scan: incremental pages-updated watermark plus a one-time keyset backfill over `pages.id`. */
+export interface PageScanState {
+ /** Lower bound (timestamptz text) of the next incremental pass; null until the backfill starts it. */
+ watermark: string | null;
+ /** An unfinished incremental pass: rows with `updated_at >= lower`, after `(at, id)`; `next` becomes the watermark when it ends. */
+ pass: { lower: string; next: string; after: { at: string; id: number } | null } | null;
+ backfill: { after_id: number; done: boolean; started_at: string; completed_at?: string };
+}
+
+/** The working-tree walk: a full first walk, then only files changed since the last walked commit (or mtime) plus dirty files. */
+export interface FileScanState {
+ /** An unfinished pass: `full` lists every eligible file, `changed` only what changed since `walked`; `after` is the last path judged. */
+ pass: { mode: 'full' | 'changed'; after: string | null; started_at: string; commit: string | null } | null;
+ /** The last completed pass: HEAD when it started (null outside Git) and its start time (the mtime watermark). */
+ walked: { commit: string | null; at: string } | null;
+}
+
+export interface ScanRecord {
+ version: 1;
+ source_id: string;
+ incarnation: string;
+ /** Fence rules version the stored findings were judged with; a newer one restarts both scans. */
+ rules: string;
+ pages: PageScanState;
+ files: FileScanState | null;
+ /** The last census: complete when the backfill is done, the incremental pass caught up and the file walk finished. */
+ census: { complete: boolean; fresh_at: string | null; checked_at: string };
+}
+
+const candidateFingerprint = (sourceId: string, incarnation: string, key: string) => `${sourceId}:${incarnation}:${key}`;
+const scanFingerprint = (sourceId: string, incarnation: string) => `${sourceId}:${incarnation}`;
+
+export async function readScanRecord(engine: Exec, sourceId: string, incarnation: string): Promise<ScanRecord | null> {
+ const [row] = await engine.executeRaw<{ record: ScanRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
+ [FENCE_SCAN_OP, scanFingerprint(sourceId, incarnation)]);
+ return row?.record ?? null;
+}
+
+export async function writeScanRecord(engine: Exec, record: ScanRecord): Promise<void> {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,now())
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
+ [FENCE_SCAN_OP, scanFingerprint(record.source_id, record.incarnation), JSON.stringify([record])]);
+}
+
+/** Stores one judged part (`page` or `file`) of a candidate, keeping the other part. */
+export async function upsertCandidatePart(engine: Exec, ids: { sourceId: string; incarnation: string; key: string },
+ part: 'page' | 'file', finding: PageFinding | FileFinding): Promise<void> {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)
+ VALUES($1,$2,jsonb_build_array(jsonb_build_object('version',1,'source_id',$3::text,'incarnation',$4::text,'key',$5::text,$6::text,$7::text::jsonb)),now())
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=jsonb_build_array((op_checkpoints.completed_keys->0)||jsonb_build_object($6::text,$7::text::jsonb)),updated_at=now()`,
+ [FENCE_CANDIDATE_OP, candidateFingerprint(ids.sourceId, ids.incarnation, ids.key), ids.sourceId, ids.incarnation, ids.key, part, JSON.stringify(finding)]);
+}
+
+/** Drops the `part` of these candidates (they judged clean); a candidate with no part left is deleted. */
+export async function clearCandidateParts(engine: Exec, ids: { sourceId: string; incarnation: string }, part: 'page' | 'file', keys: readonly string[]): Promise<void> {
+ if (!keys.length) return;
+ const fingerprints = keys.map(key => candidateFingerprint(ids.sourceId, ids.incarnation, key));
+ const other = part === 'page' ? 'file' : 'page';
+ await engine.executeRaw(`DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[]) AND (completed_keys->0->$3::text) IS NULL`,
+ [FENCE_CANDIDATE_OP, fingerprints, other]);
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array((completed_keys->0)-$3::text),updated_at=now()
+ WHERE op=$1 AND fingerprint=ANY($2::text[]) AND (completed_keys->0->$3::text) IS NOT NULL`, [FENCE_CANDIDATE_OP, fingerprints, part]);
+}
+
+/** Candidate records of live source incarnations (optionally one source). */
+export async function readCandidateRecords(engine: Exec, sourceIds?: readonly string[]): Promise<CandidateRecord[]> {
+ const rows = await engine.executeRaw<{ record: CandidateRecord }>(`SELECT c.completed_keys->0 AS record FROM op_checkpoints c
+ JOIN sources s ON s.id=c.completed_keys->0->>'source_id' AND s.incarnation::text=c.completed_keys->0->>'incarnation'
+ WHERE c.op=$1 AND ($2::text[] IS NULL OR s.id=ANY($2::text[])) ORDER BY c.fingerprint`, [FENCE_CANDIDATE_OP, sourceIds ? [...sourceIds] : null]);
+ return rows.map(row => row.record);
+}
+
+/** One trend row: files or pages Tier 1 normalized, by fix class and by writer. */
+export interface TrendEntry { day: string; count: number; by_class: Record<string, number>; writers: Record<string, number> }
+
+/**
+ * A managed sync run's running total (replaced on every flush, so a run
+ * resumed across invocations is counted once); the row keeps the UTC day of
+ * its first flush.
+ */
+export async function recordSyncRunTrend(engine: Exec, input: { sourceId: string; runId: string; day: string; count: number;
+ byClass: Record<string, number>; writers: Record<string, number> }): Promise<void> {
+ if (!input.count) return;
+ const record = { version: 1, source_id: input.sourceId, day: input.day, count: input.count, by_class: input.byClass, writers: input.writers };
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,now())
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=jsonb_build_array((EXCLUDED.completed_keys->0)||jsonb_build_object('day',op_checkpoints.completed_keys->0->'day')),updated_at=now()`,
+ [FENCE_TREND_OP, `${input.sourceId}:run:${input.runId}`, JSON.stringify([record])]);
+}
+
+/**
+ * A sync run's fence tally (`counts.fences` of a managed cursor, or the legacy
+ * run's import tally) as its trend row; best effort, so a trend write never
+ * fails a sync.
+ */
+export async function flushSyncFenceTrend(engine: Exec, input: { sourceId: string; runId: string | null | undefined;
+ tally: { count: number; by_class: Record<string, number>; writers: Record<string, number> } | null | undefined; now?: Date }): Promise<void> {
+ if (!input.runId || !input.tally?.count) return;
+ try {
+ await recordSyncRunTrend(engine, { sourceId: input.sourceId, runId: input.runId, day: (input.now ?? new Date()).toISOString().slice(0, 10),
+ count: input.tally.count, byClass: input.tally.by_class, writers: input.tally.writers });
+ } catch { /* the trend is advisory; the sync result already reports fences_normalized */ }
+}
+
+/** One normalized page write (put_page, put_pages, remember, takes and fact writers), written once per request. */
+export async function recordWriteTrend(engine: Exec, input: { sourceId: string; requestKey: string; day: string; byClass: Record<string, number>; writer: string }): Promise<void> {
+ const record = { version: 1, source_id: input.sourceId, day: input.day, count: 1, by_class: input.byClass, writers: { [input.writer]: 1 } };
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,now()) ON CONFLICT(op,fingerprint) DO NOTHING`,
+ [FENCE_TREND_OP, `${input.sourceId}:write:${input.requestKey}`, JSON.stringify([record])]);
+}
+
+/**
+ * Writes the trend row of a committed page write whose outcome reports a
+ * normalized fence (the page-write `fences_normalized` object). Managed sync
+ * outcomes (a per-file fix list) are skipped: the sync run flushes its own
+ * total once per run.
+ */
+export async function recordPublicationFenceTrend(tx: Exec, row: { id: string; source_id: string; principal_kind: string }, outcome: Record<string, unknown>,
+ now: Date = new Date()): Promise<void> {
+ const report = outcome.fences_normalized as { count?: unknown; by_class?: Record<string, number> } | undefined;
+ if (!report || Array.isArray(report) || typeof report !== 'object' || !Number(report.count)) return;
+ await recordWriteTrend(tx, { sourceId: row.source_id, requestKey: row.id, day: now.toISOString().slice(0, 10), byClass: report.by_class ?? {}, writer: row.principal_kind });
+}
+
+/** Trend rows of these sources since `fromDay` (inclusive), summed per source and day. */
+export async function readTrend(engine: Exec, sourceIds: readonly string[], fromDay: string): Promise<Map<string, TrendEntry[]>> {
+ const out = new Map<string, TrendEntry[]>();
+ if (!sourceIds.length) return out;
+ const rows = await engine.executeRaw<{ record: TrendEntry & { source_id: string } }>(`SELECT completed_keys->0 AS record FROM op_checkpoints
+ WHERE op=$1 AND completed_keys->0->>'source_id'=ANY($2::text[]) AND completed_keys->0->>'day'>=$3`, [FENCE_TREND_OP, [...sourceIds], fromDay]);
+ for (const { record } of rows) {
+ const days = out.get(record.source_id) ?? [];
+ let day = days.find(entry => entry.day === record.day);
+ if (!day) days.push(day = { day: record.day, count: 0, by_class: {}, writers: {} });
+ day.count += Number(record.count ?? 0);
+ for (const [cls, n] of Object.entries(record.by_class ?? {})) day.by_class[cls] = (day.by_class[cls] ?? 0) + Number(n);
+ for (const [writer, n] of Object.entries(record.writers ?? {})) day.writers[writer] = (day.writers[writer] ?? 0) + Number(n);
+ out.set(record.source_id, days);
+ }
+ for (const days of out.values()) days.sort((a, b) => a.day.localeCompare(b.day));
+ return out;
+}
diff --git a/src/core/fence-repair/census.ts b/src/core/fence-repair/census.ts
new file mode 100644
index 0000000000..b89b30f84a
--- /dev/null
+++ b/src/core/fence-repair/census.ts
@@ -0,0 +1,416 @@
+/**
+ * #6188 fence census: the source-scoped candidate finder for malformed facts
+ * and takes fences, and the per-source counts `gbrain doctor`
+ * (`fence_integrity`) reports. Discovery only; nothing here repairs.
+ *
+ * Three origins, deduplicated by page slug into one candidate:
+ * - `hold`: an `invalid_fence` Git sync hold (the sync held the file).
+ * - `page`: a stored page whose fences fail the coordinated fence step,
+ * found by an incremental scan (pages updated since the watermark) plus a
+ * one-time resumable keyset backfill over `pages.id`. The next pass starts
+ * at the previous pass's start minus every writer transaction still open
+ * then (`pg_stat_activity`) and a grace period, so a transaction that wrote
+ * `updated_at` before a pass and committed after it is still read.
+ * - `file`: a working-tree file of a checkout-backed source, found by a
+ * resumable walk (a full first walk, then only files changed since the
+ * last walked commit, untracked files newer than it, mtime for non-Git
+ * sources, and every stored file candidate again). A deadline stops a walk
+ * between files; the next run resumes after the last judged path.
+ *
+ * Every finding is bound to the bytes it judged (sha256, page id and
+ * `updated_at`, file mtime) and carries the planned tier, reason codes and a
+ * location; never a cell value. A census is complete only when the backfill
+ * is done, the incremental pass caught up and the walk finished; anything
+ * less is `partial`, and a partial census never reads as healthy.
+ */
+import { execFileSync } from 'node:child_process';
+import { existsSync, lstatSync, readFileSync, statSync } from 'node:fs';
+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 { isFrontmatterScannablePath, walkDir } from '../brain-writer.ts';
+import { sha256 } from '../persistence/digest.ts';
+import { readGitSourceHolds, type GitHoldRecord } from '../persistence/sync-holds.ts';
+import { FENCE_RULES_VERSION } from './normalize.ts';
+import { FENCE_VERSION } from './refusal.ts';
+import { FENCE_REASONS } from './reasons.ts';
+import { fenceStep, pageHasFenceText } from './tier1.ts';
+import {
+ clearCandidateParts, readCandidateRecords, readScanRecord, upsertCandidatePart, writeScanRecord,
+ type CandidateFinding, type CandidateLocation, type CandidateRecord, type FileFinding, type PageFinding, type ScanRecord,
+} from './census-store.ts';
+import type { FenceCtx, FencePage, FenceReason, FenceTier } from './types.ts';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+export const FENCE_TIERS: readonly FenceTier[] = ['deterministic', 'resolver', 'llm', 'manual'];
+/** The fence rules a stored finding was judged with; a change restarts the scans. */
+export const CENSUS_RULES = `${FENCE_VERSION}.${FENCE_RULES_VERSION}`;
+/** Rows per DB scan batch. */
+export const CENSUS_PAGE_BATCH = 500;
+/** How far before the previous pass's start the next pass begins, besides the open writer transactions the database reports. */
+export const LATE_COMMIT_GRACE_MS = 120_000;
+/** Files judged between two cursor saves. */
+const FILE_SAVE_EVERY = 200;
+/** mtime slack for the non-Git watermark (coarse filesystem clocks). */
+const MTIME_SKEW_MS = 2_000;
+
+/** The tier that clears one reason: manual-only reasons and reasons whose tier depends on the page count as manual. */
+export function reasonTier(reason: string): FenceTier {
+ const spec = FENCE_REASONS[reason as FenceReason];
+ if (!spec || spec.manualOnly) return 'manual';
+ return spec.tier ?? 'manual';
+}
+
+const maxTier = (tiers: readonly FenceTier[]): FenceTier => tiers.reduce((worst, tier) => FENCE_TIERS.indexOf(tier) > FENCE_TIERS.indexOf(worst) ? tier : worst, 'deterministic');
+
+/**
+ * Judges one page's sections with the coordinated fence step (normalization
+ * on): null when clean, `deterministic` when Tier 1 fixes it losslessly,
+ * otherwise the highest tier its residual reasons need.
+ */
+export function judgeFences(page: FencePage, ctx: FenceCtx): Pick<CandidateFinding, 'tier' | 'reasons' | 'location'> | null {
+ const step = fenceStep(page, ctx, { normalize: true });
+ if (step.status === 'clean') return null;
+ if (step.status === 'normalized') {
+ const first = step.fixes[0]!;
+ const same = step.fixes.filter(fix => fix.fence === first.fence && fix.section === first.section);
+ return { tier: 'deterministic', reasons: [...new Set(step.fixes.map(fix => fix.class))],
+ location: { fence: first.fence, section: first.section, rows: [...new Set(same.flatMap(fix => fix.row === null ? [] : [fix.row]))].slice(0, 20),
+ columns: [...new Set(same.flatMap(fix => fix.column === null ? [] : [fix.column]))].slice(0, 20), line: first.line } };
+ }
+ const at = step.location;
+ return { tier: maxTier(step.issues.map(issue => reasonTier(issue.reason))), reasons: [...new Set(step.issues.map(issue => issue.reason))],
+ location: { fence: at.fence, section: at.section, rows: [...at.rows], columns: [...at.columns], line: at.line } };
+}
+
+interface CensusSource { id: string; incarnation: string; local_path: string | null }
+
+async function censusSources(engine: Exec, sourceIds?: readonly string[]): Promise<CensusSource[]> {
+ return engine.executeRaw<CensusSource>(`SELECT id, incarnation::text AS incarnation, local_path FROM sources
+ WHERE archived IS NOT TRUE AND incarnation IS NOT NULL AND ($1::text[] IS NULL OR id=ANY($1::text[])) ORDER BY id`, [sourceIds ? [...sourceIds] : null]);
+}
+
+const hasCheckout = (source: CensusSource) => !!source.local_path && existsSync(source.local_path) && statSync(source.local_path).isDirectory();
+
+/** Where the next incremental pass starts: this moment, or the start of the oldest writer transaction still open, minus the grace. */
+async function passHorizon(engine: Exec, graceMs: number): Promise<string> {
+ const grace = Math.max(0, Math.floor(graceMs));
+ try {
+ const [row] = await engine.executeRaw<{ at: string }>(`SELECT (LEAST(now(), COALESCE((SELECT min(xact_start) FROM pg_stat_activity
+ WHERE datname=current_database() AND backend_xid IS NOT NULL AND pid<>pg_backend_pid()), now())) - ($1::int * interval '1 millisecond'))::text AS at`, [grace]);
+ return row!.at;
+ } catch {
+ const [row] = await engine.executeRaw<{ at: string }>(`SELECT (now() - ($1::int * interval '1 millisecond'))::text AS at`, [grace]);
+ return row!.at;
+ }
+}
+
+interface PageRow {
+ id: number; slug: string; type: string; frontmatter: Record<string, unknown> | null; source_path: string | null; content_hash: string | null;
+ updated_at: string; live: boolean; compiled_truth: string | null; timeline: string | null;
+}
+
+const FENCED = (column: string) => `(strpos(${column},'gbrain:facts:')>0 OR strpos(${column},'gbrain:takes:')>0)`;
+/** Page columns for judging; bodies only for live markdown pages that mention a fence marker. */
+const PAGE_COLUMNS = `id, slug, type, frontmatter, source_path, content_hash, updated_at::text AS updated_at,
+ (deleted_at IS NULL AND page_kind='markdown') AS live,
+ CASE WHEN deleted_at IS NULL AND page_kind='markdown' AND (${FENCED('compiled_truth')} OR ${FENCED('timeline')}) THEN compiled_truth END AS compiled_truth,
+ CASE WHEN deleted_at IS NULL AND page_kind='markdown' AND (${FENCED('compiled_truth')} OR ${FENCED('timeline')}) THEN timeline END AS timeline`;
+
+/** Judges a batch of stored pages and stores what changed. */
+async function judgePages(engine: Exec, source: CensusSource, rows: readonly PageRow[], at: string): Promise<void> {
+ const clean: string[] = [];
+ for (const row of rows) {
+ const page = row.live && row.compiled_truth !== null ? { compiled_truth: row.compiled_truth, timeline: row.timeline ?? '' } : null;
+ const verdict = page && pageHasFenceText(page) ? judgeFences(page, screenFenceCtx({ type: row.type as never, frontmatter: row.frontmatter ?? {} })) : null;
+ if (!verdict) { clean.push(row.slug); continue; }
+ const finding: PageFinding = { ...verdict, sha256: sha256(`${page!.compiled_truth}\u0000${page!.timeline}`), checked_at: at,
+ page_id: Number(row.id), updated_at: row.updated_at, content_hash: row.content_hash, source_path: row.source_path };
+ await upsertCandidatePart(engine, { sourceId: source.id, incarnation: source.incarnation, key: row.slug }, 'page', finding);
+ }
+ await clearCandidateParts(engine, { sourceId: source.id, incarnation: source.incarnation }, 'page', clean);
+}
+
+/** Advances the backfill, then the incremental pass, until both are done or the deadline passes. Saves after every batch. */
+async function scanPages(engine: Exec, source: CensusSource, record: ScanRecord, opts: Required<Pick<CensusOptions, 'batchSize' | 'lateCommitGraceMs'>> & { deadline: number; now: () => Date }): Promise<boolean> {
+ const pages = record.pages;
+ while (!pages.backfill.done) {
+ if (opts.now().getTime() >= opts.deadline) return false;
+ const rows = await engine.executeRaw<PageRow>(`SELECT ${PAGE_COLUMNS} FROM pages WHERE source_id=$1 AND id>$2 ORDER BY id LIMIT $3`,
+ [source.id, pages.backfill.after_id, opts.batchSize]);
+ await judgePages(engine, source, rows, opts.now().toISOString());
+ if (rows.length) pages.backfill.after_id = Number(rows[rows.length - 1]!.id);
+ if (rows.length < opts.batchSize) Object.assign(pages.backfill, { done: true, completed_at: opts.now().toISOString() });
+ await writeScanRecord(engine, record);
+ }
+ for (;;) {
+ if (opts.now().getTime() >= opts.deadline) return false;
+ pages.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`,
+ [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) };
+ const caughtUp = rows.length < opts.batchSize;
+ if (caughtUp) { pages.watermark = pass.next; pages.pass = null; }
+ await writeScanRecord(engine, record);
+ if (caughtUp) return true;
+ }
+}
+
+function git(root: string, args: string[]): string | null {
+ try {
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
+ } catch {
+ return null;
+ }
+}
+
+const gitHead = (root: string) => git(root, ['rev-parse', '--verify', '-q', 'HEAD'])?.trim() || null;
+const nulList = (out: string) => out.split('\0').filter(Boolean).map(path => path.replace(/\\/g, '/'));
+
+/** Every file the walk judges, source-root relative and sorted (Git-visible files in a checkout, else a pruned walk). */
+function eligibleFiles(root: string): string[] {
+ const git = collectGitVisibleFiles(root, isFrontmatterScannablePath);
+ const absolute: string[] = git ?? [];
+ if (!git) walkDir(root, path => { absolute.push(path); });
+ return [...new Set(absolute.map(path => relative(root, path).replace(/\\/g, '/')).filter(isFrontmatterScannablePath))].sort();
+}
+
+const mtimeMs = (path: string): number | null => { try { return lstatSync(path).mtimeMs; } catch { return null; } };
+
+/**
+ * Files a `changed` pass judges: what changed since the last walked commit
+ * (committed, staged or edited), untracked files newer than the last walk
+ * (mtime for non-Git sources), and every stored file candidate. Null when
+ * the walked commit is gone, so the caller walks everything again.
+ */
+function changedFiles(root: string, walked: NonNullable<ScanRecord['files']>['walked'] & object, stored: readonly string[]): string[] | null {
+ const since = Date.parse(walked.at) - MTIME_SKEW_MS;
+ const fresh = (rel: string) => (mtimeMs(join(root, rel)) ?? Infinity) >= since;
+ let paths: string[];
+ if (walked.commit) {
+ const diff = git(root, ['diff', '--name-only', '--relative', '--no-renames', '-z', walked.commit]);
+ if (diff === null) return null;
+ const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '-z']) ?? '';
+ paths = [...nulList(diff), ...nulList(untracked).filter(fresh)];
+ } else {
+ paths = eligibleFiles(root).filter(fresh);
+ }
+ return [...new Set([...paths, ...stored])].filter(isFrontmatterScannablePath).sort();
+}
+
+/** Judges one working-tree file: its page slug and finding, or null when it is clean or unreadable (gone). */
+function judgeFile(root: string, rel: string, at: string): { key: string | null; finding: FileFinding | null } {
+ const path = join(root, rel);
+ let content: string;
+ let stat: ReturnType<typeof lstatSync>;
+ try {
+ stat = lstatSync(path);
+ if (!stat.isFile()) return { key: null, finding: null };
+ content = readFileSync(path, 'utf8');
+ } catch {
+ return { key: null, finding: null };
+ }
+ if (!content.includes('gbrain:facts:') && !content.includes('gbrain:takes:')) return { key: null, finding: null };
+ const parsed = parseMarkdown(content, rel);
+ const verdict = judgeFences(parsed, screenFenceCtx(parsed));
+ return { key: parsed.slug, finding: verdict ? { ...verdict, sha256: sha256(content), checked_at: at, path: rel, mtime_ms: Math.floor(stat.mtimeMs) } : null };
+}
+
+/** Advances the working-tree walk until it finishes or the deadline passes. */
+async function scanFiles(engine: Exec, source: CensusSource, record: ScanRecord, stored: Map<string, string>, opts: { deadline: number; now: () => Date }): Promise<boolean> {
+ const root = resolve(source.local_path!);
+ const files = record.files ??= { pass: null, walked: null };
+ const changed = files.walked && files.pass?.mode !== 'full' ? changedFiles(root, files.walked, [...stored.keys()]) : null;
+ files.pass ??= { mode: changed ? 'changed' : 'full', after: null, started_at: opts.now().toISOString(), commit: gitHead(root) };
+ const pass = files.pass;
+ if (pass.mode === 'changed' && !changed) pass.mode = 'full';
+ const list = pass.mode === 'changed' ? changed! : eligibleFiles(root);
+ const ids = { sourceId: source.id, incarnation: source.incarnation };
+ let since = 0;
+ for (const rel of list) {
+ if (pass.after !== null && rel <= pass.after) continue;
+ if (opts.now().getTime() >= opts.deadline) { await writeScanRecord(engine, record); return false; }
+ const { key, finding } = judgeFile(root, rel, opts.now().toISOString());
+ const previous = stored.get(rel);
+ if (previous !== undefined && previous !== key) await clearCandidateParts(engine, ids, 'file', [previous]);
+ if (key !== null && finding) { await upsertCandidatePart(engine, { ...ids, key }, 'file', finding); stored.set(rel, key); }
+ else { if (key !== null) await clearCandidateParts(engine, ids, 'file', [key]); stored.delete(rel); }
+ pass.after = rel;
+ if (++since >= FILE_SAVE_EVERY) { since = 0; await writeScanRecord(engine, record); }
+ }
+ files.walked = { commit: pass.commit, at: pass.started_at };
+ files.pass = null;
+ await writeScanRecord(engine, record);
+ return true;
+}
+
+export interface CensusOptions {
+ sourceIds?: readonly string[];
+ /** Epoch ms (on the `now` clock) after which no new batch or file starts. */
+ deadline: number;
+ /** The clock for deadlines and timestamps (default: the wall clock). */
+ now?: () => Date;
+ batchSize?: number;
+ lateCommitGraceMs?: number;
+}
+
+export interface CensusRun { source_id: string; complete: boolean; backfill_done: boolean; pages_caught_up: boolean; files: 'none' | 'done' | 'partial' }
+
+function freshRecord(source: CensusSource, at: string): ScanRecord {
+ return { version: 1, source_id: source.id, incarnation: source.incarnation, rules: CENSUS_RULES,
+ pages: { watermark: null, pass: null, backfill: { after_id: 0, done: false, started_at: at } }, files: null,
+ census: { complete: false, fresh_at: null, checked_at: at } };
+}
+
+/**
+ * Advances every scoped source's census until it is complete or the deadline
+ * passes, persisting each cursor as it goes. Safe to run from several
+ * processes: a finding is rewritten from current bytes either way.
+ */
+export async function runFenceCensus(engine: Exec, opts: CensusOptions): Promise<CensusRun[]> {
+ const now = opts.now ?? (() => new Date());
+ const tuning = { batchSize: opts.batchSize ?? CENSUS_PAGE_BATCH, lateCommitGraceMs: opts.lateCommitGraceMs ?? LATE_COMMIT_GRACE_MS, now };
+ const runs: CensusRun[] = [];
+ const records = await readCandidateRecords(engine, opts.sourceIds);
+ const sources = await censusSources(engine, opts.sourceIds);
+ for (const [index, source] of sources.entries()) {
+ // Each source gets an even share of what is left, so one large source cannot starve the others.
+ const started = now().getTime();
+ const deadline = Math.min(opts.deadline, started + Math.max(0, opts.deadline - started) / (sources.length - index));
+ const checkout = hasCheckout(source);
+ const stored = await readScanRecord(engine, source.id, source.incarnation);
+ const record = stored && stored.rules === CENSUS_RULES ? stored : freshRecord(source, now().toISOString());
+ // The first pass starts where the backfill starts, so a page updated during the backfill is read again.
+ record.pages.watermark ??= await passHorizon(engine, tuning.lateCommitGraceMs);
+ // With a checkout, the stored pages get half of the share first; the walk gets the rest.
+ const caughtUp = await scanPages(engine, source, record, { ...tuning, deadline: checkout ? started + (deadline - started) / 2 : deadline });
+ const storedFiles = new Map(records.filter(r => r.source_id === source.id && r.incarnation === source.incarnation && r.file).map(r => [r.file!.path, r.key]));
+ const walked = checkout ? await scanFiles(engine, source, record, storedFiles, { deadline, now }) : false;
+ const pagesDone = caughtUp || await scanPages(engine, source, record, { ...tuning, deadline });
+ const complete = record.pages.backfill.done && pagesDone && (!checkout || walked);
+ record.census = { complete, fresh_at: complete ? now().toISOString() : record.census.fresh_at, checked_at: now().toISOString() };
+ await writeScanRecord(engine, record);
+ runs.push({ source_id: source.id, complete, backfill_done: record.pages.backfill.done, pages_caught_up: pagesDone, files: !checkout ? 'none' : walked ? 'done' : 'partial' });
+ }
+ return runs;
+}
+
+export type CandidateOrigin = 'hold' | 'page' | 'file';
+
+/** One deduplicated candidate: every origin that names the page, the bucket that counts it, its planned tier and what binds it. */
+export interface FenceCandidate {
+ source_id: string;
+ /** The page slug (or `path:<file>` for a held file with no slug). */
+ key: string;
+ path: string | null;
+ page_id: number | null;
+ origins: CandidateOrigin[];
+ /** Counted once: a hold first, then a malformed stored page, then an unsynced file. */
+ bucket: CandidateOrigin;
+ tier: FenceTier;
+ reasons: string[];
+ location: CandidateLocation | null;
+ bound: { page_sha256?: string; updated_at?: string; content_hash?: string | null; file_sha256?: string; file_mtime_ms?: number; upstream_version?: string | null };
+ held_since?: string;
+}
+
+function holdTier(hold: GitHoldRecord, file: FileFinding | undefined): FenceTier {
+ if (file) return file.tier;
+ return reasonTier(hold.meta.fence?.reason ?? hold.meta.reason ?? 'unparseable');
+}
+
+/** Every candidate of the scoped sources, deduplicated across holds, stored pages and files. */
+export async function listFenceCandidates(engine: Exec, sourceIds?: readonly string[]): Promise<FenceCandidate[]> {
+ const records = await readCandidateRecords(engine, sourceIds);
+ const pageIds = records.flatMap(r => r.page ? [r.page.page_id] : []);
+ const live = new Set((pageIds.length ? await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE id=ANY($1::int[]) AND deleted_at IS NULL', [pageIds]) : [])
+ .map(row => Number(row.id)));
+ const out = new Map<string, FenceCandidate>();
+ const byPath = new Map<string, FenceCandidate>();
+ const key = (sourceId: string, k: string) => `${sourceId}\u0000${k}`;
+ for (const record of records) {
+ const page = record.page && live.has(record.page.page_id) ? record.page : undefined;
+ const file = record.file;
+ if (!page && !file) continue;
+ const primary = (page ?? file)!;
+ const candidate: FenceCandidate = { source_id: record.source_id, key: record.key, path: file?.path ?? page?.source_path ?? null, page_id: page?.page_id ?? null,
+ origins: [...(page ? ['page' as const] : []), ...(file ? ['file' as const] : [])], bucket: page ? 'page' : 'file', tier: primary.tier,
+ reasons: [...new Set([...(page?.reasons ?? []), ...(file?.reasons ?? [])])], location: primary.location,
+ bound: { ...(page ? { page_sha256: page.sha256, updated_at: page.updated_at, content_hash: page.content_hash } : {}),
+ ...(file ? { file_sha256: file.sha256, file_mtime_ms: file.mtime_ms } : {}) } };
+ out.set(key(record.source_id, record.key), candidate);
+ if (file) byPath.set(key(record.source_id, file.path), candidate);
+ }
+ const fileOf = (record: CandidateRecord | undefined) => record?.file;
+ const recordsByKey = new Map(records.map(r => [key(r.source_id, r.key), r]));
+ for (const source of await readGitSourceHolds(engine, sourceIds ? { sourceIds: [...sourceIds] } : {})) {
+ for (const hold of source.holds) {
+ if (hold.code !== 'invalid_fence') continue;
+ const existing = (hold.slug ? out.get(key(hold.source_id, hold.slug)) : undefined) ?? byPath.get(key(hold.source_id, hold.path));
+ const file = existing ? fileOf(recordsByKey.get(key(existing.source_id, existing.key))) : undefined;
+ const tier = holdTier(hold, file?.path === hold.path ? file : undefined);
+ const reason = hold.meta.fence?.reason ?? hold.meta.reason;
+ if (existing) {
+ Object.assign(existing, { origins: ['hold', ...existing.origins], bucket: 'hold', tier, path: hold.path, held_since: hold.held_at,
+ reasons: [...new Set([...(reason ? [reason] : []), ...existing.reasons])], location: existing.location ?? holdLocation(hold),
+ bound: { ...existing.bound, upstream_version: hold.upstream_version } });
+ continue;
+ }
+ const candidate: FenceCandidate = { source_id: hold.source_id, key: hold.slug ?? `path:${hold.path}`, path: hold.path, page_id: hold.page_id, origins: ['hold'],
+ bucket: 'hold', tier, reasons: reason ? [reason] : [], location: holdLocation(hold), bound: { upstream_version: hold.upstream_version }, held_since: hold.held_at };
+ out.set(key(hold.source_id, candidate.key), candidate);
+ }
+ }
+ return [...out.values()].sort((a, b) => a.source_id.localeCompare(b.source_id) || a.key.localeCompare(b.key));
+}
+
+function holdLocation(hold: GitHoldRecord): CandidateLocation | null {
+ const at = hold.meta.fence;
+ return at ? { fence: at.fence, section: at.section, rows: [...at.rows], columns: [...at.columns], line: at.line } : null;
+}
+
+export type TierCounts = Record<FenceTier, number> & { total: number };
+const zero = (): TierCounts => ({ deterministic: 0, resolver: 0, llm: 0, manual: 0, total: 0 });
+
+export interface SourceCensus {
+ source_id: string;
+ total: number;
+ holds: TierCounts;
+ pages: TierCounts;
+ files: TierCounts;
+ by_tier: TierCounts;
+ oldest_hold_at: string | null;
+ /** Up to five candidates, location only. */
+ sample: Array<Pick<FenceCandidate, 'key' | 'path' | 'bucket' | 'tier' | 'reasons'>>;
+ scan: { complete: boolean; fresh_at: string | null; checked_at: string | null; backfill_done: boolean; walking: boolean };
+}
+
+/** Per-source counts by bucket and planned tier, with the stored scan state; sources with nothing found and a complete scan are included too. */
+export async function summarizeFenceCensus(engine: Exec, sourceIds?: readonly string[]): Promise<SourceCensus[]> {
+ const sources = await censusSources(engine, sourceIds);
+ const candidates = await listFenceCandidates(engine, sources.map(source => source.id));
+ const out: SourceCensus[] = [];
+ for (const source of sources) {
+ const record = await readScanRecord(engine, source.id, source.incarnation);
+ const current = record?.rules === CENSUS_RULES ? record : null;
+ const mine = candidates.filter(c => c.source_id === source.id);
+ const census: SourceCensus = { source_id: source.id, total: mine.length, holds: zero(), pages: zero(), files: zero(), by_tier: zero(), oldest_hold_at: null,
+ sample: mine.slice(0, 5).map(c => ({ key: c.key, path: c.path, bucket: c.bucket, tier: c.tier, reasons: c.reasons })),
+ scan: { complete: current?.census.complete ?? false, fresh_at: current?.census.fresh_at ?? null, checked_at: current?.census.checked_at ?? null,
+ backfill_done: current?.pages.backfill.done ?? false, walking: !!current?.files?.pass } };
+ for (const candidate of mine) {
+ const bucket = candidate.bucket === 'hold' ? census.holds : candidate.bucket === 'page' ? census.pages : census.files;
+ bucket[candidate.tier]++; bucket.total++;
+ census.by_tier[candidate.tier]++; census.by_tier.total++;
+ if (candidate.held_since && (!census.oldest_hold_at || candidate.held_since < census.oldest_hold_at)) census.oldest_hold_at = candidate.held_since;
+ }
+ out.push(census);
+ }
+ return out;
+}
diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.ts
index 50cc7df7f7..a7442c2a65 100644
--- a/src/core/op-checkpoint.ts
+++ b/src/core/op-checkpoint.ts
@@ -1,6 +1,8 @@
import { createHash } from 'crypto';
import type { BrainEngine } from './engine.ts';
import { withRetry, BULK_RETRY_OPTS, RetryAbortError } from './retry.ts';
+import { FENCE_REPAIR_ATTEMPT_OP } from './fence-repair/attempts.ts';
+import { FENCE_CANDIDATE_OP, FENCE_SCAN_OP } from './fence-repair/census-store.ts';
/** Max paths per append-INSERT round-trip; bounds the param-array size. */
const APPEND_CHUNK = 1000;
@@ -486,9 +488,10 @@ export function syncFingerprint(p: { sourceId?: string; lastCommit: string }): s
* deliberately generous — any reasonable long-running op finishes inside
* that window, and the row is cheap (few KB). Durable state is exempt: Git
* sync holds, their summary while it counts any, retry requests, sync
- * import provenance and the blocked-cursor conversion log of a live source
- * incarnation leave only on resolution (or with the incarnation),
- * and connector hold-retry requests never expire (#5988).
+ * import provenance, the blocked-cursor conversion log, and the #6188 fence
+ * census (candidates and scan cursors) and paid fence-repair attempt claims
+ * and memos of a live source incarnation leave only on resolution (or with
+ * the incarnation), and connector hold-retry requests never expire (#5988).
*/
export async function purgeStaleCheckpoints(
engine: BrainEngine,
@@ -504,7 +507,7 @@ export async function purgeStaleCheckpoints(
WHERE updated_at < now() - ($1 || ' days')::interval
AND op NOT IN ('managed-atoms','managed-atoms-generation','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
AND op<>'connector-hold-retry'
- AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions')
+ AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions','${FENCE_CANDIDATE_OP}','${FENCE_SCAN_OP}','${FENCE_REPAIR_ATTEMPT_OP}')
AND NOT (op='sync-hold-summary' AND COALESCE((completed_keys->0->>'count')::int,0)=0)
AND EXISTS (SELECT 1 FROM sources s WHERE s.id=op_checkpoints.completed_keys->0->>'source_id'
AND s.incarnation::text=op_checkpoints.completed_keys->0->>'incarnation'))
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index c818f7e25f..caf9d87d29 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -168,7 +168,7 @@ export const GRADUATION_INVENTORY: Inventory = {
entry('planner_stats_deltas', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),
entry('planner_stats_state', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),
entry('gbrain_cycle_locks', 'discard', 'operational', 'TTL run locks; every row is an orphan under the kernel lock.'),
- entry('budget_reservations', 'discard', 'operational', 'No runtime reader or writer; only migrations reference it.'),
+ entry('budget_reservations', 'discard', 'operational', 'Daily-ledger holds (src/core/budget/daily-ledger.ts) that expire within minutes; budget_ledger carries the day\'s totals, so a hold dropped mid-graduation stays counted as reserved until its UTC day ends (only tightening that day\'s cap).'),
entry('subagent_rate_leases', 'discard', 'operational', 'Job-owned concurrency leases that expire.'),
entry('oauth_codes', 'discard', 'security', 'One-time authorization codes; an in-flight OAuth handshake restarts.'),
diff --git a/test/e2e/fence-census-postgres.test.ts b/test/e2e/fence-census-postgres.test.ts
new file mode 100644
index 0000000000..80d7fd91ee
--- /dev/null
+++ b/test/e2e/fence-census-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../fence-census.test.ts'));
diff --git a/test/fence-census.test.ts b/test/fence-census.test.ts
new file mode 100644
index 0000000000..d6df3ad0d4
--- /dev/null
+++ b/test/fence-census.test.ts
@@ -0,0 +1,308 @@
+/**
+ * #6188 PR3 fence census (`src/core/fence-repair/census.ts`, `census-store.ts`).
+ *
+ * Protects: the candidate finder sees every malformed facts or takes fence
+ * once (an `invalid_fence` hold, a stored page, an unsynced working-tree
+ * file), with its planned tier, bound to the bytes it judged and location
+ * only; the DB scan's watermark never skips a page whose transaction
+ * committed after a pass that started later than its `updated_at`; the
+ * one-time backfill and the file walk resume across deadlines instead of
+ * restarting, so damage beyond several deadlines is found; a later walk reads
+ * only changed, untracked and stored files; census, candidate and attempt
+ * rows survive the 7-day purge while their source incarnation lives; the
+ * normalization trend counts a resumed sync run and a replayed write once.
+ * Fails when: the watermark advances to the pass start (late commits lost),
+ * a cursor restarts at the prefix, dedup counts a page twice, a finding keeps
+ * cell text, or the purge drops live census state.
+ * Seams: a ticking clock for deadlines; PGLite always, Postgres through
+ * test/e2e/fence-census-postgres.test.ts (a second session holds a real open
+ * transaction). Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';
+import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';
+import { FENCE_REPAIR_ATTEMPT_OP } from '../src/core/fence-repair/attempts.ts';
+import { listFenceCandidates, runFenceCensus, summarizeFenceCensus } from '../src/core/fence-repair/census.ts';
+import {
+ FENCE_CANDIDATE_OP, FENCE_SCAN_OP, FENCE_TREND_OP, readScanRecord, readTrend, recordPublicationFenceTrend, recordSyncRunTrend,
+} from '../src/core/fence-repair/census-store.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const FB = '<!--- gbrain:facts:begin -->', FE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |';
+const FS = '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|';
+const T = '<!--- gbrain:takes:begin -->', TE = '<!--- gbrain:takes:end -->';
+const TH = '| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|';
+// Unique strings that must never leave the page: a claim, a holder and a kind.
+const CLAIM = 'Sentinelclaimzq8 ships quarterly', HOLDER = 'Sentinelholderzq8 Example', KIND = 'sentinelkindzq8';
+const SECRETS = [CLAIM, HOLDER, KIND, 'Sentinelclaimzq8', 'Sentinelholderzq8'];
+const factsRow = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | private | medium | 2026-01-01 | | call | |`;
+/** Missing end marker after the table: Tier 1 closes it (deterministic). */
+const DETERMINISTIC = ['## Facts', '', FB, FH, FS, factsRow(1, 'Synthetic fact'), factsRow(2, 'Second synthetic fact'), '', ''].join('\n');
+/** A display-name holder: the resolver tier. */
+const RESOLVER = `${T}\n${TH}\n| 1 | ${CLAIM} | take | ${HOLDER} | 0.7 | 2026-01 | chat |\n${TE}\n`;
+/** A takes kind gbrain never chooses: a manual edit. */
+const MANUAL = `${T}\n${TH}\n| 1 | Synthetic take | ${KIND} | brain | 0.7 | 2026-01 | chat |\n${TE}\n`;
+/** Rows with no header: the model tier. */
+const LLM = ['## Facts', '', FB, factsRow(1, 'Synthetic fact'), factsRow(2, 'Another synthetic fact'), FE, ''].join('\n');
+const CLEAN = ['## Facts', '', FB, FH, FS, factsRow(1, 'Clean synthetic fact'), FE, ''].join('\n');
+const md = (title: string, body: string) => `---\ntitle: ${title}\n---\n${body}`;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const roots: string[] = [];
+
+/** A deterministic clock that moves `step` ms on every read, so deadlines stop scans after a fixed amount of work. */
+function ticking(step = 1) {
+ let t = Date.parse('2026-10-06T12:00:00Z');
+ return { now: () => new Date(t += step), at: () => t };
+}
+
+for (const backend of backends) {
+ describe(`${backend}: fence census`, () => {
+ let engine: BrainEngine;
+ let second: PostgresEngine | undefined;
+ let close: () => Promise<void> = async () => {};
+
+ beforeAll(async () => {
+ if (backend === 'pglite') {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ return;
+ }
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine;
+ second = new PostgresEngine();
+ await second.connect({ database_url: pg.databaseUrl, poolSize: 2 });
+ close = async () => { await second!.disconnect(); await pg.close(); };
+ }, 120_000);
+
+ afterAll(async () => { await close(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+
+ async function source(files: Record<string, string> | null, opts: { git?: boolean } = {}) {
+ const id = `cen-${randomUUID().replace(/-/g, '').slice(0, 12)}`;
+ const root = files ? mkdtempSync(join(tmpdir(), 'fence-census-')) : null;
+ const write = (path: string, content: string) => { mkdirSync(join(root!, path, '..'), { recursive: true }); writeFileSync(join(root!, path), content); };
+ const commit = () => { git(root!, 'add', '-A'); git(root!, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); return git(root!, 'rev-parse', 'HEAD'); };
+ if (root) {
+ roots.push(root);
+ for (const [path, content] of Object.entries(files!)) write(path, content);
+ if (opts.git !== false) { git(root, 'init', '-q'); commit(); }
+ }
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ const stored = (slug: string, body: string) => engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '' }, { sourceId: id });
+ const census = (extra: Partial<Parameters<typeof runFenceCensus>[1]> = {}) => runFenceCensus(engine, { sourceIds: [id], deadline: Date.now() + 120_000, ...extra });
+ const keys = async () => (await listFenceCandidates(engine, [id])).map(c => c.key);
+ return { id, root: root!, incarnation, write, commit, stored, census, keys };
+ }
+
+ const expectNoSecrets = (text: string) => { for (const secret of SECRETS) expect(text).not.toContain(secret); };
+
+ test('holds, stored pages and files are found once each, tiered, bound to their bytes and location-only', async () => {
+ const s = await source({ 'notes/det.md': md('Det', DETERMINISTIC), 'notes/both.md': md('Both', RESOLVER), 'notes/held.md': md('Held', MANUAL),
+ 'notes/clean.md': md('Clean', CLEAN), 'notes/model.md': md('Model', LLM) });
+ await s.stored('notes/both', RESOLVER);
+ await s.stored('notes/stored-only', DETERMINISTIC);
+ await s.stored('notes/clean', CLEAN);
+ const observed = new Date().toISOString();
+ await engine.transaction(tx => writeGitHold(tx, { source_id: s.id, incarnation: s.incarnation, path: 'notes/held.md', source_path: 'notes/held.md', slug: 'notes/held',
+ page_id: null, code: 'invalid_fence', message: 'Fence takes_kind_unsupported: in the takes fence (body), row 1, column kind.', upstream_version: 'v1',
+ observed_at: observed, run_id: 'run-1', mode: 'managed',
+ meta: { reason: 'takes_kind_unsupported', recovery_version: 1, fence_version: 1,
+ fence: { reason: 'takes_kind_unsupported', fence: 'takes', section: 'body', rows: [1], columns: ['kind'], line: 4 } } }));
+
+ expect(await s.census()).toEqual([{ source_id: s.id, complete: true, backfill_done: true, pages_caught_up: true, files: 'done' }]);
+ const list = await listFenceCandidates(engine, [s.id]);
+ expect(list.map(c => [c.key, c.bucket, c.origins, c.tier])).toEqual([
+ ['notes/both', 'page', ['page', 'file'], 'resolver'],
+ ['notes/det', 'file', ['file'], 'deterministic'],
+ ['notes/held', 'hold', ['hold', 'file'], 'manual'],
+ ['notes/model', 'file', ['file'], 'llm'],
+ ['notes/stored-only', 'page', ['page'], 'deterministic'],
+ ]);
+ const both = list.find(c => c.key === 'notes/both')!;
+ expect(both).toMatchObject({ reasons: ['holder_unresolved'], location: { fence: 'takes', section: 'body', rows: [1], columns: ['who'] }, path: 'notes/both.md' });
+ expect(both.bound.page_sha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(both.bound.file_sha256).toBe(sha256(md('Both', RESOLVER)));
+ expect(typeof both.bound.updated_at).toBe('string');
+ expect(list.find(c => c.key === 'notes/held')!).toMatchObject({ path: 'notes/held.md', bound: { upstream_version: 'v1' } });
+
+ const [census] = await summarizeFenceCensus(engine, [s.id]);
+ expect(census).toMatchObject({ source_id: s.id, total: 5, holds: { manual: 1, total: 1 }, pages: { resolver: 1, deterministic: 1, total: 2 },
+ files: { deterministic: 1, llm: 1, total: 2 }, by_tier: { deterministic: 2, resolver: 1, llm: 1, manual: 1, total: 5 },
+ scan: { complete: true, backfill_done: true, walking: false } });
+ expect(census!.oldest_hold_at).toBeTruthy();
+
+ // Fixing the file and the stored copy clears both parts; the stored-only page stays.
+ s.write('notes/both.md', md('Both', CLEAN)); s.commit();
+ await s.stored('notes/both', CLEAN);
+ await s.census();
+ expect(await s.keys()).toEqual(['notes/det', 'notes/held', 'notes/model', 'notes/stored-only']);
+
+ const rows = await engine.executeRaw<{ completed_keys: unknown }>('SELECT completed_keys FROM op_checkpoints WHERE op=ANY($1::text[]) AND fingerprint LIKE $2',
+ [[FENCE_CANDIDATE_OP, FENCE_SCAN_OP], `${s.id}:%`]);
+ for (const blob of [JSON.stringify(rows), JSON.stringify(list), JSON.stringify(await summarizeFenceCensus(engine, [s.id]))]) expectNoSecrets(blob);
+ }, 60_000);
+
+ test('the incremental pass reads pages updated since the watermark, including a late commit older than the previous pass', async () => {
+ const s = await source(null);
+ for (const slug of ['notes/a', 'notes/b', 'notes/c']) await s.stored(slug, CLEAN);
+ expect((await s.census())[0]).toMatchObject({ complete: true, files: 'none' });
+ expect(await s.keys()).toEqual([]);
+
+ await s.stored('notes/a', DETERMINISTIC);
+ await s.census();
+ expect(await s.keys()).toEqual(['notes/a']);
+
+ // A transaction that set updated_at before the previous pass started and committed after it ended.
+ const { watermark } = (await readScanRecord(engine, s.id, s.incarnation))!.pages;
+ const [late] = await engine.executeRaw<{ before_now: boolean }>(`UPDATE pages SET compiled_truth=$1, updated_at=$2::timestamptz + interval '90 seconds'
+ WHERE source_id=$3 AND slug='notes/b' RETURNING updated_at < now() - interval '1 second' AS before_now`, [RESOLVER, watermark, s.id]);
+ expect(late!.before_now).toBe(true);
+ await s.census();
+ expect(await s.keys()).toEqual(['notes/a', 'notes/b']);
+
+ await s.stored('notes/a', CLEAN);
+ await engine.executeRaw('UPDATE pages SET deleted_at=now(), updated_at=now() WHERE source_id=$1 AND slug=$2', [s.id, 'notes/b']);
+ await s.census();
+ expect(await s.keys()).toEqual([]);
+ }, 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);
+ await s.stored('notes/late', CLEAN);
+ await s.census({ lateCommitGraceMs: 0 });
+ let release!: () => void;
+ let updated!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const wrote = new Promise<void>(resolve => { updated = resolve; });
+ const writer = second!.transaction(async tx => {
+ await tx.executeRaw('UPDATE pages SET compiled_truth=$1, updated_at=now() WHERE source_id=$2 AND slug=$3', [MANUAL, s.id, 'notes/late']);
+ updated();
+ await gate;
+ });
+ await wrote;
+ await new Promise(resolve => setTimeout(resolve, 50));
+ await s.census({ lateCommitGraceMs: 0 });
+ expect(await s.keys()).toEqual([]);
+ release();
+ await writer;
+ await s.census({ lateCommitGraceMs: 0 });
+ expect(await s.keys()).toEqual(['notes/late']);
+ }, 60_000);
+ }
+
+ test('the backfill resumes across deadlines and finds damage past several of them', async () => {
+ const s = await source(null);
+ for (let i = 0; i < 30; i++) await s.stored(`notes/p-${String(i).padStart(2, '0')}`, CLEAN);
+ await s.stored('notes/z-late', LLM);
+ const clock = ticking();
+ const progress: number[] = [];
+ let partial = 0;
+ for (let run = 0; run < 60; run++) {
+ const [result] = await s.census({ now: clock.now, deadline: clock.at() + 6, batchSize: 4 });
+ const record = (await readScanRecord(engine, s.id, s.incarnation))!;
+ if (result!.complete) break;
+ partial++;
+ expect((await summarizeFenceCensus(engine, [s.id]))[0]!.scan.complete).toBe(false);
+ progress.push(record.pages.backfill.done ? Number.MAX_SAFE_INTEGER : record.pages.backfill.after_id);
+ }
+ expect(partial).toBeGreaterThanOrEqual(3);
+ // Never restarted: every partial run ended further along than the last.
+ for (let i = 1; i < progress.length; i++) expect(progress[i]!).toBeGreaterThanOrEqual(progress[i - 1]!);
+ expect(new Set(progress).size).toBeGreaterThanOrEqual(3);
+ expect(await s.keys()).toEqual(['notes/z-late']);
+ }, 120_000);
+
+ test('the file walk resumes from its cursor across several deadlines and finds damage past them', async () => {
+ const files: Record<string, string> = {};
+ for (let i = 0; i < 24; i++) files[`notes/a-${String(i).padStart(2, '0')}.md`] = md(`A${i}`, CLEAN);
+ files['notes/z-one.md'] = md('Z1', DETERMINISTIC);
+ files['notes/z-two.md'] = md('Z2', MANUAL);
+ const s = await source(files);
+ const clock = ticking();
+ const cursors: string[] = [];
+ let partial = 0;
+ for (let run = 0; run < 60; run++) {
+ const [result] = await s.census({ now: clock.now, deadline: clock.at() + 12 });
+ if (result!.complete) break;
+ partial++;
+ const pass = (await readScanRecord(engine, s.id, s.incarnation))!.files?.pass;
+ if (pass?.after) cursors.push(pass.after);
+ expect((await summarizeFenceCensus(engine, [s.id]))[0]!.scan).toMatchObject({ complete: false });
+ }
+ expect(partial).toBeGreaterThanOrEqual(3);
+ expect(cursors.length).toBeGreaterThanOrEqual(3);
+ for (let i = 1; i < cursors.length; i++) expect(cursors[i]! > cursors[i - 1]!).toBe(true);
+ expect(await s.keys()).toEqual(['notes/z-one', 'notes/z-two']);
+ expect((await readScanRecord(engine, s.id, s.incarnation))!.files).toMatchObject({ pass: null, walked: { commit: git(s.root, 'rev-parse', 'HEAD') } });
+ }, 120_000);
+
+ test('after the first walk, changed, untracked and deleted files are read again', async () => {
+ const s = await source({ 'notes/one.md': md('One', CLEAN), 'notes/two.md': md('Two', CLEAN), 'notes/gone.md': md('Gone', DETERMINISTIC) });
+ await s.census();
+ expect(await s.keys()).toEqual(['notes/gone']);
+ s.write('notes/one.md', md('One', RESOLVER));
+ unlinkSync(join(s.root, 'notes/gone.md'));
+ const head = s.commit();
+ s.write('notes/fresh.md', md('Fresh', DETERMINISTIC));
+ s.write('notes/two.md', md('Two', MANUAL));
+ await s.census();
+ expect(await s.keys()).toEqual(['notes/fresh', 'notes/one', 'notes/two']);
+ expect((await readScanRecord(engine, s.id, s.incarnation))!.files!.walked!.commit).toBe(head);
+
+ const plain = await source({ 'notes/old.md': md('Old', CLEAN) }, { git: false });
+ await plain.census();
+ expect(await plain.keys()).toEqual([]);
+ plain.write('notes/new.md', md('New', LLM));
+ await plain.census();
+ expect(await plain.keys()).toEqual(['notes/new']);
+ }, 60_000);
+
+ test('census, candidate and attempt rows survive the 7-day purge while their source incarnation lives; trend rows age out', async () => {
+ const s = await source(null);
+ const dead = randomUUID();
+ const insert = (op: string, fingerprint: string, incarnation: string) => engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)
+ VALUES($1,$2,$3::text::jsonb,now() - interval '10 days')`, [op, fingerprint, JSON.stringify([{ source_id: s.id, incarnation, day: '2026-01-01', count: 1 }])]);
+ for (const op of [FENCE_CANDIDATE_OP, FENCE_SCAN_OP, FENCE_REPAIR_ATTEMPT_OP]) {
+ await insert(op, `${s.id}:${s.incarnation}:live`, s.incarnation);
+ await insert(op, `${s.id}:${dead}:dead`, dead);
+ }
+ await insert(FENCE_TREND_OP, `${s.id}:run:old`, s.incarnation);
+ await purgeStaleCheckpoints(engine);
+ const left = await engine.executeRaw<{ op: string; fingerprint: string }>('SELECT op, fingerprint FROM op_checkpoints WHERE fingerprint LIKE $1 ORDER BY op, fingerprint', [`${s.id}:%`]);
+ expect(left).toEqual([FENCE_CANDIDATE_OP, FENCE_REPAIR_ATTEMPT_OP, FENCE_SCAN_OP].sort().map(op => ({ op, fingerprint: `${s.id}:${s.incarnation}:live` })));
+ }, 60_000);
+
+ test('the trend counts a resumed sync run and a replayed page write once, and skips per-file sync outcomes', async () => {
+ const s = await source(null);
+ await recordSyncRunTrend(engine, { sourceId: s.id, runId: 'run-1', day: '2026-10-05', count: 3, byClass: { close_fence: 3 }, writers: { 'notes/': 3 } });
+ await recordSyncRunTrend(engine, { sourceId: s.id, runId: 'run-1', day: '2026-10-06', count: 5, byClass: { close_fence: 4, renumber: 1 }, writers: { 'notes/': 5 } });
+ const row = { id: randomUUID(), source_id: s.id, principal_kind: 'local_cli' };
+ const at = new Date('2026-10-06T10:00:00Z');
+ await recordPublicationFenceTrend(engine, row, { fences_normalized: { count: 1, by_class: { renumber: 1 } } }, at);
+ await recordPublicationFenceTrend(engine, row, { fences_normalized: { count: 1, by_class: { renumber: 1 } } }, at);
+ await recordPublicationFenceTrend(engine, { ...row, id: randomUUID() }, { fences_normalized: [{ class: 'renumber' }] }, at);
+ await recordPublicationFenceTrend(engine, { ...row, id: randomUUID() }, { status: 'imported' }, at);
+ expect((await readTrend(engine, [s.id], '2026-09-30')).get(s.id)).toEqual([
+ { day: '2026-10-05', count: 5, by_class: { close_fence: 4, renumber: 1 }, writers: { 'notes/': 5 } },
+ { day: '2026-10-06', count: 1, by_class: { renumber: 1 }, writers: { local_cli: 1 } },
+ ]);
+ expect((await readTrend(engine, [s.id], '2026-10-06')).get(s.id)!.map(day => day.day)).toEqual(['2026-10-06']);
+ }, 60_000);
+ });
+}