Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): failed-writes classifies a replay refused by file/database drift instead of looping on it (W4.11)
time-attacke34d08168d48
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex b03961df48..f7728a336d 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -8,7 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.-- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969).+- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id, and `file_database_drift` (W4.11) when its last replay attempt was refused `source_changed` and the page has not been written since (`lastFailedAttempt`; the detail and an apply's `file_database_drift` outcome name `gbrain sources reconcile <source> <slug> --preview`; `test/repair-failed-writes-drift-w411.test.ts`); owner-produced writes are `producer_owned` residuals with the producer command (a failed `managed_file_repair` names both `gbrain repair frontmatter` and `gbrain repair fences`). The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`). #5994: `laneContext` sets `ctx.replayAuthority` to the stored authority, so admission (`submissionAuthority` → `replayedAuthority` in `persistence/authority.ts`, and `requestPrincipalForContext`) reuses its principal, delegation, scopes and autoLinkTrusted for the same source incarnation and re-authorizes it live; a restricted write gets back its recorded job (`delegatedJobId`, or the id in a single legacy `wiki/agents/<id>/*` prefix, replayed on the legacy sandboxed path when its original was), and one with neither is accepted by `enforceSubagentSlugFence` (`ops/context.ts`) only through that marker with the exact non-empty stored allow-list. The fence still fails closed for every live dispatch. A put_page replay passes the stored `timeline_section` (#5969).- `src/core/repair/timeline-comments.ts` — `gbrain repair timeline-comments` (#6184), explicit-only. The plan lists pages with timeline rows whose source, summary or detail carries `<!--`/`-->` or whose body has a materialized bullet carrying markup (`dropCommentBullets`), with residuals `comment_only_rows`, `comment_bearing_rows`, `pages_with_comment_bullets`. Apply: one revision-bound `put_page` per page dropping those generated bullets (user-written bullets are left), then one transaction under the page lock (`withCoordinatedWrite` with maintenance attribution on managed brains) that deletes comment-only rows and rewrites the rest to their stripped tuple, or deletes them when the page already has it. Idempotent. `timeline.ts` warns `timeline_comment_markup` naming this kind while such rows exist.- `src/core/repair/orphan-children.ts` — `gbrain repair orphan-children` (#5216, #4738), explicit-only, brain-wide, projection publication. `PAGE_CHILD_FK_TARGETS` + `orphanPredicate` (a correlated, table-qualified `NOT EXISTS`, so Postgres plans an anti-join instead of a per-row subplan once page ids outgrow work_mem; `test/e2e/repair-orphan-children-plan-postgres.test.ts`) are the single target list (doctor `child_table_orphans` in `doctor/checks/core-health.ts` imports them and names this repair instead of printing SQL). One item per (table, column); apply deletes orphans or clears the two ON DELETE SET NULL references in one rechecking statement. `probeTornPages` reads every page body in 500-row batches, row by row inside a failing batch, and the plan reports torn rows as the `torn_pages` residual plus a warning naming id/source/slug; they are never changed. The `storage_corrupt` reason in `pg-access-classify.ts` points XX000 storage errors here (`repair-orphan-children-5216.test.ts`, `pg-access-storage-corrupt-5216.test.ts`).- `src/core/repair/fences.ts` — `gbrain repair fences` (#6188), preview-bound, `spends: 'llm'`, not explicit-only (no destructive consent). Candidates: the fence census (`listFenceCandidates` after a bounded `runFenceCensus`, `GBRAIN_FENCE_REPAIR_SCAN_MS`, default 10 s) filtered by `--only`/`--skip <path>` and `--slug <slug>`, plus files or pages the selection names that the census has not judged. Per candidate (`fence-repair/repair-io.ts` reads the current bytes): a non-owner host is `owner_unavailable`, an unfinished managed sync cursor or a pending write naming it is `sync_in_progress` (E9); `analyzeFences` (`repair-tiers.ts`) decides `proposal` (Tier 1 or Tier 2, validated, a fixed point, the exact diff), `llm` (only Tier 3 residuals: `fences.repair.llm`/`--no-llm` → `llm_disabled`, a page whose tags its file lacks → `canonical_overlay` before any spend, no measured model with a key and `models.fence_repair` unset → `no_measured_model`, an unpriced model under a user cap → `no_pricing`, under the default caps a warn-and-run notice naming `gbrain pricing set`, 0 caps or an estimate over `fences.repair.max_usd_per_page` → `budget_exhausted`, an attempt memo already rejected for these bytes → its stored verdict at $0) or `manual` with the exact location-only edit. The model is `resolveFenceRepairModel` (`fence-repair/model.ts`: `models.fence_repair`, else the first measured model with a key, else none). The preview saves the approved set (`previewHash` over sources, selection and each item's location, bytes hash, revision, tier and after-hash) and prints `apply_command` with `--expect`; `--apply --expect` replays it (`changed_since_preview` for moved bytes or revision), a bare `--apply` applies the current plan starting after the last candidate the previous bare run touched (`fence-repair-rotation`). Apply refuses a remote caller (`trusted_cli_required`) and runs Tier 3 through `runTier3` (ledger reservation, attempt claim, a corrective re-ask only after gate (a) or (e)); a daily-ledger refusal stops the run (`budget_exhausted`, D15: spent and cap, reset time, pages waiting, `gbrain config set fences.repair.max_usd_per_day <usd>` with consent `paid`). Outcomes `repaired` / `held` (FenceReason, also written to the hold with `recordFenceHoldRepair`) / `skipped`; `report` adds `repaired`, `remaining` by reason (an `--expect` apply re-checks the selection for what stays held) and `verification` (`FenceRepairVerification`: repaired per tier, held per reason, oldest hold, USD per Tier 3 repair). Tests: `test/repair-fences.test.ts` (PGLite and Postgres), `test/fence-repair-llm.test.ts`.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 6e6367750e..3ea708e6e9 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -613,6 +613,7 @@ candidate one class:| `duplicate` | A later request with the same intent exists; that one is the candidate. | Kept. || `superseded` | A later write or delete of the page committed or is still pending; for `put_page`, also a later failed `put_page` of the page (the newer content) or a page that changed after the revision the caller read. | Kept. Read the page and re-issue the change by hand if it is still wanted. || `unpinned_target` | A `remember` saved unattributed; replaying would infer its subject again and could pick another page. | Kept. Re-issue it with an explicit `entity` if it is still wanted. |+| `file_database_drift` | Its last replay was refused `source_changed`: the page's file and the database differ (an edit made in the file only), and the page has not been written since. | Kept. Reconcile the page first (`gbrain sources reconcile <source> <slug> --preview`, which the listing names); the next preview lists the write as `replay` again once the page changes. An apply that hits the same refusal reports `file_database_drift` too. || `producer_owned` | gbrain produced it (sync or file import, reconcile, relink, maintenance page, job). | Kept. The preview prints the command that produces it again from current content, such as `gbrain sync --source <id> --no-pull --retry-failed --json`. |The apply replays exactly the previewed set. Each write is classified againdiff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex 534f7570d8..a97f9e45d1 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -22,7 +22,11 @@* the newer content), or the page changed after the revision the caller* read;* - `unpinned_target`: a `remember` whose original target was inferred as- * unattributed; replaying would infer again and could pick another page.+ * unattributed; replaying would infer again and could pick another page;+ * - `file_database_drift` (W4.11): its last replay was refused+ * `source_changed` because the page's file and database differ, and the+ * page has not been written since; the listing names the reconcile+ * command, and the write is a candidate again once the page changes.** Explicit-only and preview-bound: the preview lists every candidate with its* class and saves the replay set, with each target page's revision, under its@@ -58,7 +62,7 @@ interface FailedWrite {id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string;intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null;}-type Disposition = 'replay' | 'already_written' | 'duplicate' | 'superseded' | 'unpinned_target';+type Disposition = 'replay' | 'already_written' | 'duplicate' | 'superseded' | 'unpinned_target' | 'file_database_drift';/** A replay bound to the page revision the preview saw (null: no live page). */interface ApprovedWrite extends FailedWrite { revision: string | null; selection: string[] }interface FailedWriteItem extends RepairItem { failed: ApprovedWrite; hash: string; last: boolean }@@ -113,9 +117,30 @@ async function replayAttempt(engine: BrainEngine, failedId: string): Promise<{ i}}+/** The newest replay attempt that ended without committing, or null. */+async function lastFailedAttempt(engine: BrainEngine, failedId: string): Promise<WriteRequest | null> {+ let last: WriteRequest | null = null;+ for (let attempt = 0; ; attempt++) {+ const [prior] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [replayId(failedId, attempt)]);+ if (!prior || prior.state === 'committed' || !isTerminal(prior)) return last;+ last = prior;+ }+}++/** W4.11: the reconcile step for a page whose file and database differ. */+function driftDetail(sourceId: string, slug: string): string {+ return `the page's file and database differ, so the replay was refused (source_changed); reconcile first: gbrain sources reconcile ${sourceId} ${slug} --preview, then run gbrain repair failed-writes again`;+}+/** Why a caller write must not be replayed now, or `replay`. */async function disposition(engine: BrainEngine, write: FailedWrite): Promise<{ class: Disposition; detail?: string }> {if ((await replayAttempt(engine, write.id)).prior?.state === 'committed') return { class: 'already_written', detail: 'replayed by gbrain repair failed-writes' };+ const drifted = await lastFailedAttempt(engine, write.id);+ if (drifted?.error_code === 'source_changed') {+ const [written] = await engine.executeRaw<{ later: boolean }>(+ 'SELECT updated_at > $3::timestamptz AS later FROM pages WHERE source_id=$1 AND slug=$2', [write.source_id, write.slug, drifted.updated_at]);+ if (!written?.later) return { class: 'file_database_drift', detail: driftDetail(write.source_id, write.slug) };+ }const replace = write.operation === 'put_page';const [later] = await engine.executeRaw<{ state: string; operation: string; same_intent: boolean }>(`SELECT state, operation, digest=$3 AS same_intent FROM persistence_requests@@ -269,6 +294,9 @@ async function replay(ctx: OperationContext, failed: ApprovedWrite): Promise<Repif (live.operation === 'remember') await submitRememberMutation(lane, params);else await submitPageMutation(lane, { operation: live.operation, params: replayed, ...(isTimelineSection(timelineSection) ? { timelineSection } : {}) });} catch (error) {+ if (error instanceof OperationError && error.code === 'source_changed') {+ return { applied: false, outcome: 'file_database_drift', reason: driftDetail(failed.source_id, failed.slug) };+ }if (error instanceof OperationError && !['write_pending', 'owner_unavailable', 'writer_lock_unavailable', 'writer_busy'].includes(error.code)) {return { applied: false, outcome: ['revision_conflict', 'revision_required'].includes(error.code) ? 'conflict' : 'refused', reason: `${error.code}: ${error.message}` };}diff --git a/test/repair-failed-writes-drift-w411.test.ts b/test/repair-failed-writes-drift-w411.test.tsnew file mode 100644index 0000000000..0a59300c75--- /dev/null+++ b/test/repair-failed-writes-drift-w411.test.ts@@ -0,0 +1,87 @@+/**+ * Wave 12 W4.11: a `remember` replay refused with `source_changed` (the page's+ * file and database differ) used to come back as `replay` in every preview and+ * fail the same way on every apply. It is now classified `file_database_drift`+ * with the reconcile command, in the apply outcome and in later previews,+ * until the page is written again.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { MANAGED_WRITER_GUARD_FUNCTION_SQL } from '../src/core/persistence/writer-guard-schema.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { withEnv } from './helpers/with-env.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';++let engine: PGLiteEngine;+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-replay-w411-db-'));+const logger = { info() {}, warn() {}, error() {} };++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema();+ for (const table of ['tags', 'timeline_entries', 'takes']) await engine.executeRaw(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS source_id TEXT`);+}, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); rmSync(dataDir, { recursive: true, force: true }); });++test('a replay refused because the page file drifted is classified file_database_drift, not replayed again and again', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-replay-w411-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `w411-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/bob-example', content: '---\ntitle: Bob Example\ntype: person\n---\nBob.', request_id: randomUUID() } });+ // A remember the managed writer guard refused (stored as writer_coordinator_required); the fault hook stands in for the guard.+ installFaultHook(async point => { if (point === 'consumer:prepared') throw new Error('guard refusal stand-in'); });+ await submitRememberMutation(ctx, { fact: 'Bob prefers morning meetings', entity: 'people/bob-example', provenance: 'test', visibility: 'world', request_id: randomUUID() }).catch(() => undefined);+ installFaultHook(undefined);+ await engine.executeRaw(`UPDATE persistence_requests SET error_code='writer_coordinator_required' WHERE source_id=$1 AND operation='remember' AND state='failed'`, [sourceId]);+ // The user edits the page's file by hand; the database still holds the old body.+ const file = join(root, 'people', 'bob-example.md');+ expect(existsSync(file)).toBe(true);+ appendFileSync(file, '\nEdited in the file only.\n');++ const scope = await resolveRepairScope(engine, sourceId);+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect((preview.listing ?? []).map(entry => entry.class)).toEqual(['replay']);+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('failed-writes', scope,+ { explicit: true, sourceFlag: sourceId, expect: preview.apply_command.split('--expect ')[1] });+ expect(applied.outcomes).toEqual({ file_database_drift: 1 });++ const again = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect(again.affected).toBe(0);+ expect(again.residuals).toEqual({ file_database_drift: 1 });+ const [entry] = again.listing ?? [];+ expect(entry?.class).toBe('file_database_drift');+ expect(entry?.detail).toContain(`gbrain sources reconcile ${sourceId} people/bob-example --preview`);++ // Once the page is written again (a reconcile commits a new revision), the write is a replay candidate again.+ await engine.executeRaw(`ALTER TABLE pages DISABLE TRIGGER USER`);+ await engine.executeRaw(`UPDATE pages SET updated_at = now() + interval '1 minute' WHERE source_id=$1 AND slug='people/bob-example'`, [sourceId]);+ await engine.executeRaw(`ALTER TABLE pages ENABLE TRIGGER USER`);+ const after = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });+ expect((after.listing ?? []).map(e => e.class)).toEqual(['replay']);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw(MANAGED_WRITER_GUARD_FUNCTION_SQL);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+}, 180_000);