Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(fences): commit a sync run's fences_normalized total with the cursor step that counts it (#6188)
garrytan9d5a1e0d165a
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 74b1fcf454..1f9fbf3a0e 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -9,7 +9,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/fence-repair/{normalize,structure,content,rules}.ts` — #6188 Tier 1. `normalizeFences(page, ctx)` returns a page that compiles plus location-only fixes and residual issues; a page whose fences compile comes back as the same object, and only edited cells, markers and headers change (no table is re-rendered). `structure.ts` closes a fence only when nothing but blank lines follows its last row and fixes two-dash takes markers; `content.ts` rewrites headers into canonical order with header-level defaults and renumbers prior-aware across both sections (`nextFreeRowNum`: above every fence and stored number; hidden rows never move); `rules.ts` holds the cell rules (kind map with the original word kept in `context`, enum and holder synonyms, percent confidence). `safeNormalizeFences` turns a throw into residual `normalizer_failed`. Tests: `test/fence-repair-normalize.test.ts`, `test/fence-repair-fixtures.test.ts`.- `src/core/fence-repair/{validate,validate-cells,page-checks}.ts` — #6188 the one gate every tier's output passes before a write: (a) compiles, (e) row count and containment, (b) claims, (c) existing row numbers, (d) visibility only tightens, (f) per-row cell preservation with rule-produced changes only, (g) nothing the privacy boundary hid is shown; gates (b), (c), (e) and (f) read the raw-row view. `isFenceFixedPoint` is E14. `page-checks.ts` holds `strictFailures` (gate a, the projection's three checks) and `exposedLines` (gate g). Tests: `test/fence-repair-validate.test.ts`.- `src/core/fence-repair/{tier1,import-step,config,report}.ts` — #6188 Tier 1 on every write path. `fenceStep(page, ctx, { normalize })` is the step the coordinated screen, `importFromContent` and the append verbs share: no work beyond a marker substring check for a page with no fence, one shared scan when the fences compile, and `normalized` only when the validator passes and the output is a fixed point; otherwise `residual` with issues and the refusal location (`fenceIssuesWire` is the D18 `fence_issues` shape). `import-step.ts`: `applyImportFences` runs inside `importFromContent` before the remote hidden-row merge and withdrawal preservation (E7), reusing the screen's verdict unless hidden rows or a planned `renumber` need the database (stored rows load only then); `normalizeTargetFences` normalizes an append verb's target page or throws `target_fence_malformed` for a residual in its own fence kind; `normalizePageFences` serves synthesize verify. `config.ts`: `fences.normalize` (default on, read only when there is something to fix) and the model-repair caps `fences.repair.max_usd_per_page` (0.05) and `fences.repair.max_usd_per_day` (1.00), validated at `config set` as non-negative USD (0 = no model spend) and read by `readFenceRepairCaps` (stored value = a user cap). `report.ts`: the one `fences_normalized` shape (count, by_class, writers, sample paths for local callers, coaching fix), the `fence_normalized` coaching notice and the per-file import tally (`fence_issues` for lenient imports). Tests: `test/fence-write-verbs.test.ts`, `test/persistence-sync-fence-holds.test.ts`, `test/fence-normalize-overhead.slow.test.ts`.-- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per managed or legacy sync run, replaced as its total grows via `flushSyncFenceTrend`, and one per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.+- `src/core/fence-repair/{census,census-store}.ts` — #6188 the fence census: discovery only, nothing repairs. `runFenceCensus(engine, { sourceIds, deadline, now })` advances per source (an even share of the deadline each): the stored-page scan (a one-time keyset backfill over `pages.id`, then incremental passes over `updated_at >= watermark`, where each new watermark is the previous pass's start minus the oldest open writer transaction in `pg_stat_activity` and `LATE_COMMIT_GRACE_MS`, so a transaction that committed after a later pass is still read) and, for a checkout, the working-tree walk (a full first walk of `isFrontmatterScannablePath` files via `collectGitVisibleFiles`/`walkDir`, then only `git diff <walked commit>` files, untracked files newer than the last walk, mtime for non-Git sources, and every stored file candidate). Both resume from cursors saved after every batch; a deadline leaves the census `partial`. `judgeFences` runs the coordinated `fenceStep` (normalization on): `deterministic` when Tier 1 fixes it, else the highest `FENCE_REASONS` tier of its residual reasons (`reasonTier`; manual-only or page-dependent counts as manual). `listFenceCandidates` dedupes by page slug across `invalid_fence` holds, stored pages and files (bucket hold > page > file; held-file tier from the walked file, else the hold reason), each bound to the judged bytes (page sha256/`updated_at`/`content_hash`, file sha256/mtime, hold `upstream_version`); `summarizeFenceCensus` counts per source by bucket and tier with the oldest hold and scan state. `census-store.ts`: `op_checkpoints` rows `fence-candidate` (one per source incarnation and slug, `page`/`file` parts), `fence-scan` (cursors and last census) and `fence-trend` (one row per sync run, keyed by run id: a managed run's total is rewritten in the same transaction as each cursor step that changes it, so the trend never differs from the cursor, and a legacy run writes its total when it ends; plus one row per normalized page write via `recordPublicationFenceTrend`, which the coordinator and group publication call inside the publication transaction and which skips per-file sync outcomes); candidate and scan rows survive the 7-day purge while their incarnation lives, trend rows age out. Location only: tiers, reasons, rows, columns, slugs and paths, never a cell value. Tests: `test/fence-census.test.ts` (+ `test/e2e/fence-census-postgres.test.ts`), `test/doctor-fence-integrity.test.ts`.- `src/core/fence-repair/attempts.ts` — #6188 attempt claims and the attempt memo for paid (Tier 3) fence repairs, one `op_checkpoints` row per candidate (op `fence-repair-attempt`) changed only by compare-and-swap on a record version: `claimed` → `dispatched` → `settled` → `published` | `rejected` | `transient`, at most one paid call plus one corrective re-ask per claim. A rejected or published memo (content sha256, model, fence rules version, prompt version) is not claimed again until one changes; transient failures do not consume it; an expired lease is taken over (a stale dispatch counts a crash, two reject the memo). Records carry location and reason codes and their source incarnation, so the purge keeps them while it lives. Tests: `test/fence-repair-attempts.test.ts` (+ Postgres e2e).- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.tsindex 27f40443fb..8cb83df1f4 100644--- a/src/commands/sync/holds.ts+++ b/src/commands/sync/holds.ts@@ -10,7 +10,7 @@*/import { createHash, randomUUID } from 'crypto';import { importFenceTally } from '../../core/fence-repair/report.ts';-import { flushSyncFenceTrend } from '../../core/fence-repair/census-store.ts';+import { recordSyncRunTrend } from '../../core/fence-repair/census-store.ts';import { existsSync, lstatSync } from 'fs';import { join } from 'path';import type { SyncResult } from '../sync.ts';@@ -230,8 +230,8 @@ export async function legacyHoldFields(engine: BrainEngine, holds: LegacyHolds |? recoveredReport(holds.sourceId, addRecovered(undefined, { paths: holds.recoveredPaths, commentValues: holds.counts.commentValues })) : undefined;const fences = holds.fences.fields();const normalized = fences.fences_normalized;- await flushSyncFenceTrend(engine, { sourceId: holds.sourceId, runId: holds.runId, tally: normalized && { count: normalized.count,- by_class: normalized.by_class as Record<string, number>, writers: Object.fromEntries(normalized.writers.map(w => [w.writer, w.count])) } });+ if (normalized) await recordSyncRunTrend(engine, { sourceId: holds.sourceId, runId: holds.runId, day: new Date().toISOString().slice(0, 10), count: normalized.count,+ byClass: normalized.by_class as Record<string, number>, writers: Object.fromEntries(normalized.writers.map(w => [w.writer, w.count])) });return { ...report, ...(recovered ? { recovered_frontmatter: recovered } : {}), ...fences };}diff --git a/src/core/fence-repair/census-store.ts b/src/core/fence-repair/census-store.tsindex 7956f317c7..f6afa29c2b 100644--- a/src/core/fence-repair/census-store.ts+++ b/src/core/fence-repair/census-store.ts@@ -9,11 +9,13 @@* `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.+ * - `fence-trend`: what Tier 1 normalized, per source: one row per sync run+ * (a managed run's total commits with the checkpoint publication that+ * completes the run; a legacy run writes its total when it ends) and one+ * row per normalized page write (written once per request inside its+ * publication, 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@@ -130,9 +132,8 @@ export async function readCandidateRecords(engine: Exec, sourceIds?: readonly stexport 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.+ * One sync run's total, keyed by run id (a rewrite replaces it, so a run is+ * counted once); the row keeps the UTC day of its first write.*/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> {@@ -143,20 +144,6 @@ export async function recordSyncRunTrend(engine: Exec, input: { sourceId: string[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 } };diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 2c44caf95a..4bc7b5bfb0 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -41,7 +41,7 @@ import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { faultPoint } from './fault-points.ts';import { withCoordinatedWrite } from './context.ts';import { principalAttribution } from './attribution.ts';-import { flushSyncFenceTrend } from '../fence-repair/census-store.ts';+import { recordSyncRunTrend } from '../fence-repair/census-store.ts';import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, fencesNormalizedReport, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold, type FencesTally } from './sync-holds.ts';export interface ManagedSyncWriteDiagnostic {@@ -151,6 +151,10 @@ async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null,await tx.executeRaw('UPDATE op_checkpoints SET updated_at=now() WHERE op=$1 AND fingerprint=$2', [`${OP}-manifest`, next.runId]);// #5988: a hold write or clear commits with the cursor step that passes its entry, never without it.if (saved.length) await inTx?.(tx);+ // #6188 (E33): the run's fences_normalized total commits with the cursor step that counts it, so the trend never differs from the cursor.+ const fences = next.counts.fences;+ if (saved.length && fences?.count && fences.count !== before.counts.fences?.count) await recordSyncRunTrend(tx, { sourceId: next.sourceId, runId: next.runId,+ day: new Date().toISOString().slice(0, 10), count: fences.count, byClass: fences.by_class, writers: fences.dirs });}return currentCursor(tx, key, next);}@@ -717,8 +721,6 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slscreened: 'entries' in (cursor ?? {}) ? (cursor as Cursor).entries.slice(0, cursor!.index).filter(entry => entry.action === 'import').length : 0 });const recovered = state.remote ? undefined : recoveredReport(state.sourceId, cursor?.counts.recovered);const fences = fencesNormalizedReport(state.sourceId, cursor?.counts.fences, state.remote === true);- const tally = cursor?.counts.fences;- await flushSyncFenceTrend(engine, { sourceId: state.sourceId, runId: cursor?.runId, tally: tally && { count: tally.count, by_class: tally.by_class, writers: tally.dirs } });return { ...synced, ...report, ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),...(recovered ? { recovered_frontmatter: recovered } : {}), ...(fences ? { fences_normalized: fences } : {}) };} catch {diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.tsindex 70fb3b7065..ba012b3d37 100644--- a/test/persistence-sync-fence-holds.test.ts+++ b/test/persistence-sync-fence-holds.test.ts@@ -388,3 +388,30 @@ test('E33: a sync that normalizes 50 files writes one trend row with the run totexpect(candidates.map(c => [c.key, c.bucket, c.origins, c.tier, c.reasons])).toEqual([['people/malformed', 'hold', ['hold', 'file'], 'resolver', ['holder_unresolved']]]);expectNoSecrets(JSON.stringify(candidates));}), 240_000);++test('E33: a completed sync run always has its trend row; a failed trend write fails the cursor step that counts it instead of vanishing', () => each(async engine => {+ const s = await source(engine, { 'notes/fix-a.md': fixable('A'), 'notes/fix-b.md': fixable('B'), 'notes/plain.md': note('Plain') });+ const rows = () => engine.executeRaw<{ record: Record<string, unknown> }>(`SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'=$2`,+ [FENCE_TREND_OP, s.id]);+ // Forced fault: the first trend INSERT fails, wherever it runs (the run's own statement or inside a publication transaction).+ const original = engine.executeRaw;+ let injected = 0;+ (engine as unknown as { executeRaw: typeof original }).executeRaw = function (this: typeof engine, sql: string, params?: unknown[]) {+ if (!injected && params?.[0] === FENCE_TREND_OP && sql.includes('INSERT INTO op_checkpoints')) { injected++; return Promise.reject(new Error('injected trend write failure')); }+ return original.call(this, sql, params) as never;+ } as typeof original;+ let first: SyncResult | null = null;+ try { first = await s.sync(); } catch { /* the cursor step that carried the failed trend write failed with it */ } finally {+ (engine as unknown as { executeRaw: typeof original }).executeRaw = original;+ }+ expect(injected).toBe(1);+ // A run reported complete has its trend row; a run whose trend could not be written did not complete.+ const complete = (result: SyncResult | null) => result?.status === 'first_sync' || result?.status === 'synced';+ if (complete(first)) expect(await rows()).toHaveLength(1);+ // The next sync resumes the same run from its cursor and records the run's whole total once.+ const settled = complete(first) ? first! : await s.sync();+ expect(complete(settled)).toBe(true);+ const recorded = await rows();+ expect(recorded).toHaveLength(1);+ expect(recorded[0]!.record).toMatchObject({ count: 2, by_class: { kind_map: 2, holder_alias: 2 } });+}), 180_000);