Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): replay a pinned-worktree refusal on file bytes, not mtime vs a DB timestamp
garrytanced9b29985f2
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex eb8fe8e613..c248a78a34 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -30,7 +30,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/sync-slug-mode.ts` — #6694: the checkpoint's slug-root mode against the source's pinned `slug_root_mode`. `emptySyncScope` (source root is the repository root, both realpathed) lets `sync-prepare.ts`'s checkpoint `UPDATE` accept either pin and keep the pinned one; at a subdirectory a differing pin is diagnosed by `pinnedSlugModeMismatch` after the guarded `UPDATE` matched nothing and refused `slug_root_mode_mismatch` (cause and the person's two choices from `slugModeMismatchCause`); anything else stays `revision_conflict` (`CHECKPOINT_MOVED_MESSAGE`). `slugModeCheckpointRevivable` is the second revival predicate of `sync-run.ts` `reviveCheckpoint`: a checkpoint refused `slug_root_mode_mismatch`, or an older release's moved-checkpoint `revision_conflict`, is revived when `last_commit` still equals the run's `from` and the pin is unset, equal to the run's mode or the scope is empty; `retryFailedStart` does not consult it, so `--retry-failed` keeps its rediscovery. Test: `test/sync-slug-root-mode-6694.test.ts` (both engines).- `src/core/persistence/sync-cursor-moves.ts` — #6712 (L2, one page, one fate): the managed-sync cursor's pure transitions, peeled out of `sync-run.ts`; each returns the next cursor and writes nothing (sync-run.ts saves it with one compare-and-swap). `advanceHeld`/`settledPast` pass an entry without a commit (held, waived via `waivedCursor`, an idempotent deletion via `deletionSettled`) and add its index to the settled ranges the checkpoint skips; a deferred entry (`Cursor.deferred`, a `source_changed` file retried after the manifest end) leaves the deferred list instead of moving the index. `promoteWindow` makes the window's first group the cursor's group once the cursor reaches it, so requests admitted after a failed or held entry are read by their own receipts, never frozen again; `committedPast` does the same after a commit. `withHeldKeys` records a held entry's page keys (`dependencyKeys`) so a later entry of the run that shares one is held behind it (`blocked_on`).-- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`. #6712 PR 3 (L7): `recordedStop` also returns the row's `gbrain_version`. `retryRecordedFailure` in `sync-run.ts` (what `--retry-failed`, now its deprecated alias, did on request) retries every recorded failure on the next plain sync, except a refusal nothing changed since the same version recorded it (`replaysUnchangedRefusal`: a content refusal while the file has its frozen bytes; a `source_changed` pinned import while HEAD is the run's target and the file was not written since), a slug-mode refusal and a checkpoint whose source's `last_commit` moved (#6834), which wait for a changed file or `gbrain repair managed-sync-orphans`.+- `src/core/persistence/sync-stop-class.ts` — #6712 (L2; #6565): how the settle path in `sync-run.ts` classifies a page request that ended without committing. `receiptClass` reads the terminal classifier: `transport` (a dropped connection or a retryable refusal, re-frozen in place), `page` (held, deferred or blocked under the hold policy) or `systemic` (the run stops with the classifier's action). `resumableStop` is a systemic stop the fault table retries (an unrecognised P0001 or a 55000 surfacing as `storage_error`); `stopRecorded` says an earlier invocation already stopped this run (its failure ledger row carries the run id), so the next plain sync re-freezes every page that refusal failed, bounded by `STOPS_PER_ENTRY`. #6712 PR 3 (L7): `recordedStop` also returns the row's `gbrain_version`. `retryRecordedFailure` in `sync-run.ts` (what `--retry-failed`, now its deprecated alias, did on request) retries every recorded failure on the next plain sync, except a refusal nothing changed since the same version recorded it (`replaysUnchangedRefusal`: a content refusal while the file has its frozen bytes; a `source_changed` pinned import while HEAD is the run's target and the file still holds the working-tree bytes that refused, compared by hash rather than by mtime), a slug-mode refusal and a checkpoint whose source's `last_commit` moved (#6834), which wait for a changed file or `gbrain repair managed-sync-orphans`.- `src/core/persistence/sync-knock-on.ts` — #6643, shrunk by #6712 (one page, one fate): no producer is left. It keeps the legacy predicate over receipts older builds wrote (`error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }`, or the pre-#6643 producers' exact messages, never an operator cancel): `isSyncKnockOn`/`syncKnockOnSql` (one predicate, never NULL) feed the terminal classifier, which renders such a receipt superseded, and `sync-run.ts` `refreezeInPlace`, which re-freezes the entry when a resumed cursor meets one (bounded by `STOPS_PER_ENTRY`, no config key). `cursorFenceCause` reads the two live causes of "cursor changed" (`run_replaced`, `outside_fence`; an older `window_dropped` still parses). `checkpoint-validation.ts` clause 3 skips converted receipts and the cursor's settled index ranges only; #6712 removed the knock-on exemption. `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`, each with `knock_on`).- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.diff --git a/src/core/persistence/sync-stop-class.ts b/src/core/persistence/sync-stop-class.tsindex 45cc675d20..f9e00d6fe7 100644--- a/src/core/persistence/sync-stop-class.ts+++ b/src/core/persistence/sync-stop-class.ts@@ -13,8 +13,6 @@ import { sha256 } from './digest.ts';import { readSyncFile } from './sync-discovery.ts';import { VERSION } from '../../version.ts';import { pinnedWorktreeConflict } from './sync-page-fault.ts';-import { statSync } from 'node:fs';-import { join } from 'node:path';/*** #6712 (#6565): how the run treats a receipt that did not commit, from the terminal classifier: `transport` (a dropped@@ -51,10 +49,10 @@ export async function stopRecorded(engine: BrainEngine, key: string, runId: stri/** #6712 PR 3 (L7): this run's recorded stop with the gbrain version that recorded it (null on a row from before versions were kept), or null when none is. */export async function recordedStop(engine: BrainEngine, key: string, runId: string): Promise<RecordedStop | null> {const [row] = await engine.executeRaw<RecordedStop>(- "SELECT completed_keys->0->>'gbrain_version' AS gbrain_version, (extract(epoch FROM updated_at)*1000)::text AS recorded_ms FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, runId]);+ "SELECT completed_keys->0->>'gbrain_version' AS gbrain_version FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, runId]);return row ?? null;}-export interface RecordedStop { gbrain_version: string | null; recorded_ms: string }+export interface RecordedStop { gbrain_version: string | null }/*** #6712 PR 3 (L7): a content refusal is a function of the file's bytes and the parser that read them, so while both are the@@ -68,14 +66,17 @@ export function replaysContentRefusal(failed: WriteRequest, recorded: { gbrain_v/*** #6712 PR 3 (L7): whether the next sync replays a page's recorded refusal instead of retrying it, because what decides it* has not changed since this gbrain version recorded it: a content refusal while the file has its frozen bytes, and a pinned- * import refused for newer working-tree bytes (`source_changed`) while HEAD is still the run's target and the file was not- * written after the failure was recorded. Committing the file, editing it or upgrading gbrain retries it.+ * import refused for newer working-tree bytes (`source_changed`) while HEAD is still the run's target and the file still+ * holds the working-tree bytes that refused (the frozen `rawHash`). Bytes decide, never the+ * file's mtime against the stop's database timestamp: those are two clocks, and a correction written within their skew+ * (a filesystem timestamp lags the wall clock by up to a scheduler tick) read as unwritten and replayed the refusal.+ * Committing the file, editing it or upgrading gbrain retries it.*/export function replaysUnchangedRefusal(failed: WriteRequest, recorded: RecordedStop,entry: { root: string; intent: { path?: string | null; rawHash?: string | null }; target: string; head: () => string }): boolean {if (replaysContentRefusal(failed, recorded, () => fileUnchangedSinceFreeze(entry.root, entry.intent))) return true;if (!pinnedWorktreeConflict(failed) || recorded.gbrain_version !== VERSION || !entry.intent.path || entry.head() !== entry.target) return false;- try { return statSync(join(entry.root, entry.intent.path)).mtimeMs <= Number(recorded.recorded_ms); } catch { return false; }+ return fileUnchangedSinceFreeze(entry.root, entry.intent);}/** Whether the entry's file still has the bytes its frozen request carried (a missing file, for a deletion). */diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex fef34a828b..dd1ce59a45 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { execFileSync } from 'node:child_process';@@ -471,6 +471,40 @@ test.each([false, true])('managed terminal receipts survive a missing ledger and}}), 120_000);+// The replay of a pinned-worktree refusal is decided by the file's bytes, not by its mtime against the stop's database+// timestamp: a filesystem timestamp lags the wall clock by up to a scheduler tick, so a correction written right after+// the stop was recorded read as unwritten and replayed the refusal (the flake of the test above, about 1 run in 7).+// The mtimes are forced to either side of the stop so the old comparison fails deterministically in both directions.+test('a pinned-worktree refusal replays on the file bytes, whatever the file mtime says', async () =>+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ await engine.setConfig('sync.holds', 'fail');+ try {+ const f = await fixture(engine, { 'notes/example.md': 'An original observation about the example system.\n' });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const pinned = 'A newly committed observation about the example system.\n';+ const working = 'A private uncommitted observation that must not appear in diagnostics.\n';+ const path = join(f.root, 'notes/example.md');+ writeFileSync(path, pinned);+ const target = commit(f.root);+ writeFileSync(path, working);+ const opts = { sourceId: f.id, noPull: true };+ const blocked = await performManagedSync(engine, opts);+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', managedWrite: { reason: 'pinned_git_worktree_conflict', write_request: { state: 'conflict' } } });+ const minute = 60;+ const later = Date.now() / 1000 + minute, earlier = Date.now() / 1000 - minute;+ writeFileSync(path, working); utimesSync(path, later, later);+ const rewritten = await performManagedSync(engine, opts);+ expect(rewritten.status).toBe('blocked_by_failures');+ expect(rewritten.managedWrite?.write_request).toEqual(blocked.managedWrite!.write_request);+ writeFileSync(path, pinned); utimesSync(path, earlier, earlier);+ const corrected = await performManagedSync(engine, opts);+ expect(corrected.status).toBe('synced');+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);+ } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }+ }+ }), 120_000);+test('pending durable sync retries keep the same request ID and do not claim committed imports', async () =>withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {