Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(persistence): crash robot, fault seams, history fixture and replay setup
garrytan252e3bcd6373
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 638d34f94b..75d566b5c9 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -696,7 +696,13 @@ The persistence invariant jobs run the complete `scripts/persistence/validate.tsgate (10,000-write soak) on pushes to master and manual dispatches. Pull requestsrun the same schedules and crash boundaries with a 2,500-write soak; the fullPGLite soak alone takes 15-28 minutes and would otherwise set every PR's wall-time. `test/scripts/data-safety-native-workflow.test.ts` pins the split.+time. `test/scripts/data-safety-native-workflow.test.ts` pins the split. The+crash robot (generated sequences of real operations, SIGKILL at every crash+seam they reach, process faults, the reference model) runs as its own job+beside the soak: 150 s on pull requests, 600 s elsewhere, Postgres through a+transaction-mode PgBouncer. That job also replays the shrunk crash-robot+regressions (`test/persistence-crash-robot.slow.test.ts`) and the history+fixture test on both engines; see `scripts/persistence/README.md`.For platform-only feedback, dispatch`gh workflow run test.yml --ref <branch> -f native_only=true`. This explicit manual option uses a separate concurrencydiff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex d6b38433ad..42edf1385a 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -18,3 +18,4 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `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. Tests: `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.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.- `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, 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`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.+- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) and `consumer:prepared` (between preparing a claimed request and publishing it). Used by `scripts/persistence/crash-robot.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex a13f08269b..310169e4cc 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -26,7 +26,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.mdindex a43bce80ae..d30829c088 100644--- a/docs/architecture/key-files/tooling-and-tests.md+++ b/docs/architecture/key-files/tooling-and-tests.md@@ -62,6 +62,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.+- `scripts/persistence/{ops,generator,model,crash-robot,robot-driver,shrink,lock-order,history-fixture,would-have-caught}.ts` — the crash robot, a phase of `validate.ts` (`--robot-seconds`, default 300; CI runs it as its own `persistence-validation.yml` job). `ops.ts` is the JSON op-descriptor protocol between driver and workers: each descriptor names an op kind (put/edit/delete/restore page, remember/forget, takes add/supersede, timeline add, sync, connector publish, revoke access), an actor (the local CLI principal or a remote agent whose bearer token the production `verifyAccessToken` resolves), a source, a fixed request id and arguments whose `{ $ref }` values come from earlier observations; workers run every op through its registered operation handler. `generator.ts` builds seeded schedules: the fixed cross-boundary sequences (withdrawal then stale republication, overlapping slugs across two sources, competing writers, caller-bound replay, authority revoked with effects pending, sync and connector publish racing direct writes) plus random sequences with concurrent groups. `model.ts` is the temporal oracle: receipts and revisions at the observation point, legal later transitions, late receipts against page history, withdrawal permanence on recall/get_page/facts, source isolation, caller-bound replay, takes/facts fence projections, attribution, orphans, drain and wedge bounds; `EFFECT_SEAMS` maps every `EffectKind` to its trigger op and seam (typecheck-exhaustive). `crash-robot.ts` runs a schedule in-process or as a worker role (`count`, `run` frozen at a `fault-points.ts` seam and SIGKILLed by the driver, `recover`), plus process faults (stale `index.lock`, a hung git commit holding `index.lock`, Postgres session drops). `robot-driver.ts` crashes every seam the fixed sequences reach, then fills the budget with random sequences; Postgres connects through `GBRAIN_PGBOUNCER_URL` when set and, under a budget below 300 s, skips seams that wait out a dead owner's claim lease. `shrink.ts` is dependency-preserving ddmin accepted on 3/3 reproduction; `--replay`/`--shrink` re-run a manifest's failing runs. `lock-order.ts` traces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication). `history-fixture.ts` exports `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (a managed brain with real persistence history up to 10k pages, used by engine graduation and attribution backfill) and `prepareTopology`. `would-have-caught.ts` reverts each fix in `would-have-caught.json` in a scratch worktree and runs the pre-robot gate and the robot against it. Tests: `test/persistence-crash-robot.test.ts`, `test/persistence-crash-robot.slow.test.ts` (shrunk regressions in `test/fixtures/crash-robot/`), `test/persistence-history-fixture.test.ts`.- `scripts/persistence/{matrix,matrix-cases}.ts` — required real Postgres/PgBouncer deployment matrix: 24 combinations of RLS policy enforcement, ordinary pool sizes 1/2/3 and shared/separate direct capacity. Production bulk reservations must leave short claims, renewals and reads usable; size-one publication stays queued. Fresh fixtures also verify successor manifests, stale owners, retained native lock exclusion during root replacement and source deletion/recreation. `test/e2e/persistence-runtime-matrix.test.ts` runs it when configured and refuses missing required pooler fixtures. Supplied URLs pass the test-database guard before its CREATE/DROP control connection uses the maintenance database; fresh case databases isolate it from other E2E shards.- `scripts/persistence/{performance,read-workload,read-metrics,read-admission,read-diagnostics}.ts` — required median-of-three read-workload validity check with advisory CI latency around the existing heavy query corpus (500 pages, 200 reads, four writers, writesPerWriter 25, four-connection PostgreSQL pool). Both engines use public page mutation handlers; every read/write or drained sampler error invalidates the sample, actual in-flight mutation intervals must cover at least 90% of reads, and CI reports the 50% loaded-versus-idle p99 threshold without blocking on that ratio. CI uses `--informational`, which never suppresses invalid-workload failures; the default CLI and explicit strict heavy runs still enforce the threshold. Isolated children retain runtime/source hashes, queue/admission/commit/RSS/recovery/pool metrics and bounded diagnostic records with total/dropped counts, including failed partial observations. Numeric query/corpus/write indices and monotonic timestamps correlate reads, admissions, terminal receipts and pool samples without retaining SQL, parameters, identifiers, content or raw errors. Fixed failure stages retain only allowlisted error properties; raw stacks are omitted. The root postgres.js begin observer covers lexical readers and writers, preserves the original promise/receiver/arguments, and excludes nested savepoints. Dispatch-to-callback includes BEGIN and client scheduling, not pure checkout wait; PGLite has no transaction-entry timing. Identical 20ms timers record event-loop lateness in both phases. Observers run during seed/warmup before measurement; context setup and read retention sit outside query timing where possible, but transaction/timer callbacks add unquantified overhead. No SQL or server sampling is added, and sparse pool samples cannot establish lock causes. The original `tests/heavy/read_latency_under_sync.sh` invokes this runner. The stable admission proxy requires one resolved top-level queued journal transaction per committed UUID. `test/persistence-performance.test.ts` guards validity, strict threshold semantics and advisory CLI exit behavior; `test/persistence-admission-observer.test.ts` proves rollback/publication boundaries; `test/persistence-read-diagnostics{,.serial}.test.ts` covers bounds, transparency, nested transactions, safe failure retention, tiny manifests and late sampler rejection.diff --git a/scripts/persistence/README.md b/scripts/persistence/README.mdindex 35a35c9c48..11db5d6c92 100644--- a/scripts/persistence/README.md+++ b/scripts/persistence/README.md@@ -69,6 +69,101 @@ use the real consumer, authority checks, kernel locks, coordinator, durablefiles and database transactions. Four writes per producer stay in flight;every seventeenth logical write is replayed under the same request ID.+## Crash robot++The crash robot runs generated sequences of real operations against a+managed brain and checks a reference model after every step, after every+crash and recovery, and after the final drain. It is a phase of+`validate.ts` with a time budget (`--robot-seconds`, default 300; `0` skips+it). Run it alone with:++```sh+bun --no-env-file scripts/persistence/validate.ts --engine=pglite \+ --schedules=0 --operations=0 --no-crashes --robot-seconds=300+```++Every op is a JSON descriptor (`ops.ts`) executed through its registered+operation handler with a real `OperationContext`: page writes, edits,+deletes and restores, `remember`/`forget`, takes add and supersede, timeline+entries, a user commit followed by `sync_brain`, a GitHub connector publish,+and credential revocation. Actors are the local CLI principal and two remote+agents, an OAuth client and a legacy access token, authenticated through the+production token verifier. Two sources share slugs, sit in two durability-+hardened Git checkouts, and a third source is the connector's.++Each run starts from a fresh datastore. The fixed sequences always run:+withdrawal followed by a stale republication, overlapping slugs across two+sources, competing writers on one page, caller-bound replay, an authority+revoked while effects are pending, and sync plus connector publish racing+direct writes. A counting pass records every crash seam a sequence reaches+(`src/core/persistence/fault-points.ts`); the robot then crashes each seam at+least once: the worker freezes at the seam, the driver SIGKILLs it, and a+fresh worker checks the state left behind, drains, resubmits the interrupted+requests with their original request ids and finishes the sequence. Random+sequences fill the rest of the budget. Process faults run once per engine:+a stale `index.lock`, a hung `git commit` that holds `index.lock` (it releases+the lock on SIGTERM, not on SIGKILL), and, on Postgres, every session of the+run database dropped every 400 ms.++The reference model (`model.ts`) checks: a committed receipt is visible at+once and later revisions move only through committed ops; a late receipt+names a revision the page really had; a refused write never becomes visible;+a withdrawn fact never returns through recall, `get_page` or the facts table;+a write never lands in another source; another principal reusing a request+id never receives the original receipt; takes and facts rows equal their+page fences; content rows carry write attribution; no orphan rows; every+request and effect drains (within 20 s on PGLite, whose restarted owner+releases a dead owner's claims, and within the 2-minute effect lease plus+margin on Postgres); a fresh write still commits. `lock-order.ts` checks each+transaction's row locks: worktrees before sources, sources in id order, and+no exclusive brain-row lock inside a publication.++Postgres runs connect through `GBRAIN_PGBOUNCER_URL` when it is set, with+prepared statements off. A Postgres run with a budget under 300 s skips the+seams whose recovery waits out a dead owner's claim lease; full runs crash+every seam. The manifest's `robot` key lists every run (schedule, seed,+seam and occurrence or process fault), `sequences_x_crash_points`,+`lease_bound_seams_skipped` and violations with the observed trace;+`robot_full_gate` is true for a full-budget run with no violations.++A failing run prints two commands. `--replay=<manifest>` re-runs exactly the+manifest's failing runs. `--shrink=<manifest>` removes ops from the first+failing run (an op whose producer was removed goes with it) while a+violation of the same class remains, accepts the result only when it+reproduces in 3 of 3 reruns, and writes `<manifest>.shrunk.json`. Accepted+shrunk sequences are checked in under `test/fixtures/crash-robot/` and+replayed by `test/persistence-crash-robot.slow.test.ts`.++For a local Postgres and PgBouncer replay:++```sh+docker network create gbrain-robot+docker run -d --name robot-pg --network gbrain-robot -p 5432:5432 \+ -e POSTGRES_USER=gbrain_test -e POSTGRES_PASSWORD=gbrain_test -e POSTGRES_DB=gbrain_test \+ pgvector/pgvector:pg16+docker run -d --name robot-pgbouncer --network gbrain-robot -p 55433:5432 \+ -e DB_HOST=robot-pg -e DB_PORT=5432 -e DB_USER=gbrain_test -e DB_PASSWORD=gbrain_test \+ -e POOL_MODE=transaction -e AUTH_TYPE=plain -e MAX_CLIENT_CONN=200 -e DEFAULT_POOL_SIZE=10 \+ -e IGNORE_STARTUP_PARAMETERS=extra_float_digits,statement_timeout,idle_in_transaction_session_timeout,search_path \+ edoburu/pgbouncer:latest+PGPASSWORD=gbrain_test DATABASE_URL=postgres://[email protected]:5432/gbrain_test \+ GBRAIN_PGBOUNCER_URL=postgres://[email protected]:55433/gbrain_test \+ bun --no-env-file scripts/persistence/validate.ts --engine=postgres --replay=<manifest>+```++`buildHistoryFixture(engine, { pages, seed, sources, worktrees })`+(`history-fixture.ts`) builds a managed brain with real persistence history+(up to 10,000 pages) through the same op protocol: committed and queued+requests, a delayed Git effect, withdrawals, superseded takes, page versions,+chronicle ledger rows, local writers, an OAuth client and token, and an+access token with unified grant columns. The engine must be initialized and+not yet activated, under an isolated `GBRAIN_HOME`.++`would-have-caught.ts` measures the gate against past fixes: for each fix+frozen in `would-have-caught.json` it reverse-applies the fix's `src/` hunks+in a scratch worktree and runs the pre-robot gate and the robot phase+against it, after a HEAD control that must pass.+The default manifest is `.context/persistence-<engine>-manifest.json`. Itcontains the actual completed case counts, crash outcomes, runtime/platform,latency distributions (p50/p95/p99/max), concurrent canonical-read checks, throughput, peak resident RSS,diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex a11ae084a4..dad0274ee8 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -268,7 +268,7 @@ test/scripts/ci-pr-scope.test.ts pull-request CI scope 8 readFileSynctest/scripts/ci-runner-routing.test.ts CI runner routing 6 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 23 bun-file,doctor-source-helper,exec-scan,readFileSync,source-surface-helpertest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSync-test/scripts/data-safety-native-workflow.test.ts data-safety native CI coverage 12 readFileSync+test/scripts/data-safety-native-workflow.test.ts data-safety native CI coverage 13 readFileSynctest/scripts/e2e-backend-matrix.test.ts scripts/e2e-backend-matrix.txt 3 readFileSynctest/scripts/e2e-live-key-only.test.ts shared live-key E2E exclusion list 4 readFileSynctest/scripts/e2e-runner.test.ts second 5 readFileSync