Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(key-files): move the #7514 atom write-failure entry to core-persistence-continued (60 KB cap)
garrytan2236a40b0ca5
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 9680eaa1c6..29bcb69c76 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -27,6 +27,7 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.- `src/core/persistence/import-reads.ts` — GBRA-75 wave 10: `readImportSnapshots` reads a run of pages as `readPageSnapshot(slug, { sourceId, includeDeleted: true })` returns each (soft-deleted rows, withdrawals and purge markers included) through `readPageSnapshotsBatch({ includeDeleted, absentIsNull })`, looping over its byte-budget prefixes; the managed import screen uses it for two or more new members. `importGroupReads` serves an import group's preparation (`group-publish.ts` `preparationReads`): each member's first own snapshot read comes from one batch, and `findDuplicatePage` calls that arrive together (all members, or a 2 ms window) are answered by one `findDuplicatePages` (`engine-sql/pages.ts`, same predicate and ranking per input); a failed batch falls back to each member's single read; with `reread` (the read-only screen) a member's later reads of its page come from the batch too. GBRA-108: `sliceReads` answers a screened slice's per-page reads (the origin claimants of `sync-origin.ts`, the stored timeline and take collisions of `canonical-projections.ts`, the safe-chunk fence of `page-state/projections.ts`, matched by their exported statements) from one statement per kind over the slice, row for row; a page with stored takes, a page or path outside the slice, a signalled call or a failed slice read runs its own statement (test `test/sync-legacy-sweep-gbra108.test.ts`). Tests: `test/import-reads.test.ts`, Postgres arm `test/e2e/import-reads.test.ts`.- `src/core/persistence/screening-paths.ts` — GBRA-75 wave 7: `withScreeningPaths(run)` opens one screening batch's memo of root-level filesystem facts and `screeningPath(key, compute)` resolves each once inside it: other sources' root realpaths (`assertImportPaths`), shared skillpack root canonical paths and the source root's Git scope (`knowledge-guard.ts`). Per-file paths are never memoized; a nested batch joins the open one; the memo closes with `run`, so work that outlives it computes fresh; a throwing compute is never memoized. Opened by the managed import plan and screen loops (`import-mutations.ts`), each sync waiver screen (`screenWaiver`) and `sync-run.ts` `waiveRun`'s screens. Tests: `test/persistence-skip-cost.test.ts`.- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. #6278: the lookup also matches the entry's file path, origin and a rename from that origin (`unfinishedPageRequestParams`), so the hold gate in `sync-run.ts` shares it. `unchangedSyncImport` (and so `sameContentAtOrigin`'s preparation) runs the sync preparer under `raceSyncBudget` against `persistence.sync_preparation_ms` (`syncPreparationBudgetMs`, read at most every 5 s, default 120 s) and the run's signal: past the budget nothing is waived and the origin refusal stands (fail open, nothing counted or held, `SyncPreparationBudgetExceeded`); a cancelled run propagates. GBRA-75 wave 8: `unchangedSyncImport` prepares with `{ unsaved: true }`, so its validation also accepts this run's cursor with nothing pending; before that every import waiver-run screen failed the cursor check and each unchanged file took a pending save, a second screen and its own waiver transaction. `waiveNoopRun` (up to 64 entries, one cursor write) re-reads the owner epoch under its lock (a change passes nothing; the per-entry path then refuses it) and each import's file bytes (an edit ends the prefix). Both waiver transactions read a waived import's file (a raw hash that no longer matches admits the entry) and write its `sync-import-provenance` record from the preparation's `importProvenance` (`waivedProvenance`: disk hash and blob id of those bytes, the page's current revision), so a waived page carries the same record a publication writes. Tests: `test/sync-waiver-budget.test.ts`, `test/sync-waiver-run-imports.test.ts`, `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.+- `src/core/persistence/atom-maintenance.ts` (write failures) — #7514: a batch whose write ended without committing (`conflict`, `failed`, `cancelled`) is a write failure, `atomWriteFailure`: its record carries the write's request id and refusal code (the code survives receipt compaction, which erases the message to "The write did not commit."), and on the drain each time the batch is met counts one strike in an `op_checkpoints` row (`managed-atoms-uncommitted`, keyed by the failed run key) with no model call, since a failed batch is never re-extracted on its own. At `MAX_DETERMINISTIC_FAILURES` strikes a journaled failure completion (intent `attempts`) advances the drain-key checkpoint to `held`, so the origin leaves the backlog and doctor lists it with that completion's receipt and the reviewed retry; an explicit retry records no strike. Test: `test/extract-atoms-commit-failure-hold.test.ts`.- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load under its stable or alias key (`loadableConnectorKeys`, #6561), and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`, whose preview counts alias-kept rows as `alias_protected`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. No upgrade step rewrites alias rows (#6561): `connector-sync.ts` `resumeCheckpoint` resumes from an alias row written after the stable one when the stable key has none or the alias holds the newer completed Gmail backfill, and the run's first save moves that cursor to the stable key; every checkpoint and page write compares against and writes only the stable row. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns, the role's superuser and BYPASSRLS standing and the auto-RLS event trigger and its function owner); `targetProbeBlockers` (non-superuser targets get the exact SQL a DBA runs for `vector`, BYPASSRLS and the event trigger) and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex fde2af4b36..346f75ac02 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -17,7 +17,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. `SEGMENTED_WRITER_FLOOR` (`page-body/writer-floor.ts`): a seven-day writer below it or unmarked keeps `pages.segmented_storage` off (`page-body/limits.ts`, doctor `segmented_storage`); marked rows of any role meet the floor (ingest log: two partial indexes, v254/v259). Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage and authority errors fail the attempt without completing it, so they never strike either. #7514: a batch whose write ended without committing (`conflict`, `failed`, `cancelled`) is a write failure, `atomWriteFailure`: its record carries the write's request id and refusal code (the code survives receipt compaction, which erases the message to "The write did not commit."), and on the drain each time the batch is met counts one strike in an `op_checkpoints` row (`managed-atoms-uncommitted`, keyed by the failed run key) with no model call, since a failed batch is never re-extracted on its own. At `MAX_DETERMINISTIC_FAILURES` strikes a journaled failure completion (intent `attempts`) advances the drain-key checkpoint to `held`, so the origin leaves the backlog and doctor lists it with that completion's receipt and the reviewed retry; an explicit retry records no strike. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read (it takes the importer's path for the file: a frontmatter-less file under a directory-inference rule also matches when `readCanonicalAsImported` (BOM strip + `applyInference` at `scannerSourcePath`) reproduces the stored row, with an inferred type treated as undeclared, #6605; reconcile reads the file side through `reconcileFileReading` in `reconcile-state.ts`); the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage and authority errors fail the attempt without completing it, so they never strike either. #7514 write-failure strikes and hold: [continued](core-persistence-continued.md). A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).Atom completion admits replacement and revision-pinned stale-atom deletion children together. A failed, partial-input or zero-yield batch admits no retirement, and each retirement child refuses `revision_conflict` until every replacement page of its run is committed (`replacementPublished`), so a partly published batch leaves the prior generation live.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.