Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/master (v0.60.53.0, Foundations 2) into #6007; links effect gets its crash seam

garrytanfac76df63fb0
diff --cc CHANGELOG.md
index 0c189eec50,2a4c3a1c89..fcd3adea79
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,62 -10,117 +10,173 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.54.0] - 2026-10-04
+
+**An agent connected to a remote brain can now save a stack of long pages in under a minute, and gbrain tells it how.**
+
+Agents writing to a brain over MCP (for example through `gbrain serve --http` on another machine) used to save pages one at a time, and each page cost several seconds of back-and-forth with the database. A large page also outlasted the reply's built-in wait, so the agent got "still pending" and had to keep asking. Writing 27 long research pages took about 15 minutes, followed by around 30 more calls to wire up links the pages already contained.
+
+Now the agent sends its pages in batches with `put_pages`, waits for the commit in the same reply with `wait_ms`, and the server links `[[wikilinks]]` between the pages by itself. The server also does far less database work per page and publishes a whole batch in one transaction. The instructions every MCP agent receives at connect time say all of this up front.
+
+Measured with 25 pages of 60 KB each, written over MCP to a Postgres brain 30 ms away (round trip), with embeddings and Git on:
+
+| | Before | Now |
+| --- | --- | --- |
+| 25 pages, one `put_page` at a time, with polling | nearly 5 minutes (about 11 s a page) | not needed |
+| 25 pages, 4 `put_pages` calls sent one after another | not available | 51 s, no polling |
+| One 60 KB `put_page` | 7.2 s reply saying "pending", then polls (about 11 s total) | committed in about 6 s, in the reply |
+| SQL statements on one page's publish path | 135 | 107 |
+| Backlinks between the pages you just wrote | about 30 manual `add_link` calls | built automatically after the commit |
+
+## To take advantage of v0.60.54.0
+
+`gbrain upgrade` should do this automatically. Remote agents pick up the new instructions the next time they connect.
+
+1. **Tell your agent** (or let the connect-time instructions do it): *"When you save more than three pages to gbrain, use put_pages with one request_id per batch and wait_ms 25000."*
+2. **Turn mention links off** if you don't want them: `gbrain config set mcp.remote_auto_links false`.
+3. **Verify:** `gbrain call put_pages '{"request_id":"<uuid>","pages":[{"slug":"notes/test-a","content":"# A"},{"slug":"notes/test-b","content":"# B\n\nSee [[notes/test-a]]."}],"wait_ms":25000}'` returns `"state": "committed"`, and `gbrain call get_links '{"slug":"notes/test-b"}'` shows the `mentions` link to `notes/test-a`.
+
+### Itemized changes
+
+#### Batch writes
+- New MCP tool `put_pages` (full surface): 1-50 complete pages, 8 MB of content at most, per call. Every page is an ordinary `put_page` write with the same fences, revision checks and receipts. The pages are accepted together, so queue capacity (request count and bytes) is reserved for the whole batch, or the call refuses with `queue_capacity` and accepts none.
+- One receipt per batch: the state of each page with its revision or its own error envelope, totals, `links`, and `next` (`done`, `poll` or `fix_pages`). A page refused for its own reason does not stop the others. A grant that cannot write refuses the whole call with one `permission_denied`.
+- Replaying the identical call with the same `request_id` never writes twice. `put_pages` with only `request_id` reports progress without resending content. A replay with different pages refuses with `idempotency_conflict` and names the changed pages.
+- Every page needs `put_page` permission; bound clients get each page's slug fenced like `put_page`.
+
+#### Waiting for the commit
+- `put_page` and `put_pages` accept `wait_ms` (0-30000, counted from arrival; default 5000 for `put_page`, 25000 for `put_pages`). It is not part of the write's identity, so a replay with a different wait is still the same write. Out-of-range values refuse with `invalid_write_wait` before anything is accepted.
+- A pending receipt's `retry_after_ms` comes from the server's recent publishing pace instead of a fixed 1 s.
+- `get_write_request` states its poll cadence and final states; a pending `put_page` names `wait_ms` and `put_pages`.
+
+#### Faster publishing
+- A `put_pages` batch publishes up to 8 pages per database transaction, with file-safe recovery: if one page fails, the group rolls back, every file is restored, and the pages publish one at a time so each failure stays with its own page.
+- Fewer database round trips per write: claiming, admission, recovery records and completion each take fewer statements, a page's own writes skip repeated reads, and a batch's shared admission reads run once.
+- Connector writes wait for a pending withdrawal rewrite of the same page before reading its file, so a sync right after a `forget` no longer fails with `source_changed`.
+
+#### Links for remote writes
+- Remote `put_page`, `put_pages`, `capture` and `edit_page` writes queue a `links` effect after the commit. It turns `[[wikilinks]]` and markdown links in the page body into plain `mentions` links to pages that already exist in the same source, are visible to the writer and sit inside its slug grant. Typed, frontmatter and timeline edges stay off for untrusted writes. A batch links its pages to each other once its last page commits.
+- On by default; `mcp.remote_auto_links false` turns it off. Receipts report `auto_links.mention_links` and the effect's `added`/`removed` counts.
+
+#### Agent guidance
+- The connect-time instructions put the prompt-critical lines first, so harnesses that read only the first 2,048 characters still see them: `context_pack` at session start, `put_page` replaces the whole page, and the writing guidance (`put_pages`, `wait_ms`, following `next`).
+- `put_page`, `add_link` and `add_timeline_entry` descriptions say when links and timeline entries come from the page itself.
+- The simple HTTP transport's 413 reply tells the agent to split the request and names `GBRAIN_HTTP_MAX_BODY_BYTES`.
+
+### For contributors
+- New e2e coverage: Postgres statement budgets per write phase, two-connection page-guard tests, grouped `put_page` publication (happy path and per-member failure), and the remote links effect on both engines.
+- The initialize-instructions and served-schema budgets grew for the write guidance; a new test pins the prompt-critical lines inside the first 2,048 characters.
+ ## [0.60.53.0] - 2026-10-04
+
+ **gbrain now crash-tests its own write path on every pull request, notes on a PGLite brain turn into facts without anyone running a command, and new dashboard API keys stop handing out admin access by default.**
+
+ Three things got measurably better in this release. First, the gate that guards your data now kills gbrain in the middle of real writes, over and over, and checks that nothing was lost, duplicated or leaked into another source afterwards. A full 10-minute run kills it 69 to 75 times on PGLite and 18 times on Postgres behind a connection pooler, at 11 different points in the write path, and finds zero problems. Second, on a PGLite brain served by `gbrain serve`, ten new meeting notes became 49 facts within about 20 minutes with no further command; before, they waited forever. Third, an API key created in the admin dashboard used to get full admin access unless you knew better. Now 0 of 20 do.
+
+ ### The numbers that matter
+
+ | What we measured | Before | Now |
+ | --- | --- | --- |
+ | Crash runs in one full persistence gate run (600 s budget) | 0 | 69 to 75 on PGLite, 18 on Postgres through PgBouncer, 11 crash points, 0 violations |
+ | Past persistence fixes the gate catches when the fix is reverted (12 tried) | 0 | 1 on each engine |
+ | Facts from 10 meeting notes on a served PGLite brain, no command run | 0 after 22 min (10 jobs waiting) | 49 facts from all 10 pages at about 20 min, $0.084 |
+ | Dashboard-minted API keys with full admin access | 20 of 20 | 0 of 20 |
+ | Legacy tokens authorized from the old JSON grant after upgrade | 50 of 50 | 0 of 50 (all 50 still work) |
+ | Unattributed writer references in the code | 90 in 40 files | 7 in 3 files |
+ | Scale tier enforced gates at 10,000 pages | n/a | 25 of 25 PGLite, 24 of 24 Postgres |
+ | Scale tier at 20,000 pages | nightly timed out at 50 min | green on both engines, about 8 min per job |
+ | `gbrain extract timeline --source db` at 20,000 PGLite pages | 12.6 min | about 2 min |
+
+ Search latency did not regress with the facts drain running beside it (12 pages, real model): `get_page` p95 3.2 to 3.3 ms, `list_pages` 9.1 to 8.8 ms, search 439 to 389 ms.
+
+ ### How to use it
+
+ ```bash
+ gbrain doctor --only legacy_token_null_scope,facts_drain --json # full-access keys and the drain's state
+ gbrain auth rescope --id <token-id> --scopes read,write # narrow an old full-access key
+ gbrain auth rescope --client <id> --sources none # an OAuth client that reads no source
+ gbrain auth rescope --client <id> --takes-holders world,brain # per-client takes holders
+ gbrain repair take-supersession # preview; add --apply after review
+ gbrain config set facts.extraction_enabled false # turn automatic fact extraction off
+ ```
+
+ ### Things to watch
+
+ - The facts drain is on by default on PGLite and spends real money: one chat call per page, capped at $1 per run and $5 per rolling day (`facts.drain_budget_usd`, `facts.drain_daily_budget_usd`). A brain without a chat key queues the pages and `gbrain doctor` says so.
+ - Large-brain ceilings (MCP search latency at 10k and 20k pages, calibrated budgets) are still report-only. The scale tier measures them every night; enforcement stays off until five nightly runs are stable.
+ - MCP search on Postgres slows from 78.6 ms at 10k pages to 615 ms at 20k (1,169 ms source-scoped). This is filed, not fixed.
+ - Older binaries keep reading tokens through the `permissions` mirror, which is written until 2026-11-04.
+
+ ## To take advantage of v0.60.53.0
+
+ `gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+ 1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes
+ ```
+ 2. **Your agent reads `skills/migrations/v0.60.53.0.md` the next time you interact with it.** Migration v202 converts every legacy token grant to the grant columns without changing what any token can do, and v203 adds the per-client source and takes-holder columns. Restart every `gbrain serve`, autopilot and worker so the facts drain and the new token reads take effect.
+ 3. **Verify the outcome:**
+ ```bash
+ gbrain doctor --only legacy_token_null_scope,legacy_token_grant_shape,facts_drain,revision_backfill --json
+ gbrain stats
+ ```
+ 4. **If any step fails or the numbers look wrong,** please file an issue:
+ https://github.com/garrytan/gbrain/issues with:
+ - output of `gbrain doctor`
+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists
+ - which step broke
+
+ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.
+
+ ### Itemized changes
+
+ #### Crash robot in the persistence gate
+
+ - The persistence gate runs a crash robot (`scripts/persistence/crash-robot.ts`, `generator.ts`, `model.ts`, `ops.ts`): seeded sequences of real operations across two sources and a connector source (local CLI, an OAuth client and a legacy token as remote agents; page writes, edits, deletes and restores, `remember`/`forget`, takes add and supersede, timeline entries, `sync_brain`, a GitHub connector publish, credential revocation). It SIGKILLs the owner at every crash seam the sequences reach (`src/core/persistence/fault-points.ts`), and runs process faults: a stale `index.lock`, a hung `git commit`, Postgres session drops every 400 ms, and the owner killed right after a `facts-absorb` job commits. A reference model checks for lost or duplicated writes, untrue receipts, withdrawn facts coming back, cross-source writes, request-id replay across principals, takes and facts rows against their page fences, write attribution, orphan rows, wedged queues and lock order.
+ - `.github/workflows/persistence-validation.yml` adds a `crash-robot` job per engine with PgBouncer for Postgres: 150 s on pull requests, 600 s on pushes, schedules and manual runs. Failing runs replay with `--replay` and shrink with `--shrink`; accepted shrunk sequences live in `test/fixtures/crash-robot/`.
+ - A restarted PGLite owner (for example `gbrain serve` after a crash) resumes the effects and writes its predecessor left claimed instead of waiting out a 2-minute lease that also held back writes to a withdrawn page.
+ - `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (`scripts/persistence/history-fixture.ts`) builds a managed brain with real persistence history at up to 10,000 pages.
+
+ #### Facts and chronicle
+
+ - Automatic facts drain on PGLite (`src/core/facts/drain.ts`, `drain-scheduler.ts`): `gbrain serve` (stdio and `--http`) and the new `facts_drain` cycle phase run queued `facts-absorb` jobs under per-run and daily spend caps. Jobs without a key are deferred without spending an attempt (minion job deferral); doctor `facts_drain` reports the state. Guide: `docs/guides/facts-drain.md`.
+ - The `extract_facts` cycle phase fences facts without a fence row itself (#5299).
+ - `gbrain repair take-supersession` rebuilds supersession chains broken on managed brains (#5886).
+ - Doctor `revision_backfill` reports pages waiting on the page revision backfill with a resume command that works, and the backfill runs on managed brains (#5216).
+ - Life chronicle: two same-day events of one page that share who and what both survive (`src/core/chronicle/event-identity.ts`), and an ended calendar invite becomes a `Scheduled:` meeting event without a model call (`invite-projection.ts`).
+
+ #### Keys and grants
+
+ - Dashboard API keys mint through `mintLegacyToken` with read and write by default; admin only when the box is checked. The dashboard revokes a key by id, so two keys with the same name no longer revoke each other.
+ - Doctor `legacy_token_null_scope` names every existing full-access key with the command that narrows it.
+ - Migration v202 (`legacy_token_grant_conversion`) converts every legacy token grant to the unified grant columns; HTTP auth on both transports reads those columns, and a row created later converts on its first read. A malformed `permissions` value now denies every axis on every path.
+ - Migration v203 (`oauth_client_grant_axes`) adds `oauth_clients.source_grant` and `oauth_clients.takes_holders`: `gbrain auth rescope --client <id> --sources none` and `--takes-holders a,b|none`.
+
+ #### Write attribution
+
+ - Imports, legacy sync renames and deletes, timeline extraction, legacy facts and takes helpers, cycle phases, schema-pack conversions and repairs record the local maintenance principal (`maintenanceTransaction`). Changed rows keep their creator and move their last writer. `gbrain extract`, meeting-timeline extraction and enrichment remain unattributed (`docs/architecture/system-of-record.md`).
+ - Batch maintenance writers commit one bounded transaction per batch: 10,000 pages of timeline extraction run as 100 transactions of at most 100 rows.
+ - `gbrain repair attribution-backfill` on a 10,000-page managed history with 75% of rows reset refilled 6,868 of 7,509 pages, 5,502 of 5,609 versions and 1,501 of 1,501 facts exactly and changed no content; the rest were last changed by `forget`.
+ - `gbrain calibration undo-wave` works on Postgres.
+
+ #### Scale and operations
+
+ - The scale tier asserts the large-brain ceilings through the real CLI at every size: progress-aware sync deadline, loud `embed --stale` budget stop, serve boot window, and a 20,000-file `sources add` at 20k pages and up. Ceiling enforcement stays report-only.
+ - The Postgres `find_orphans` known answer reads totals and one maximal page (it read 1 page of 100 against 104 orphans and failed the 20k nightly).
+ - PGLite writes made outside a transaction take the WAL checkpoint guard, so large raw writes no longer hang at a 529 MB WAL.
+ - `gbrain extract timeline --source db` refreshes PGLite planner statistics on batch boundaries during the walk.
+ - `gbrain migrate --to` refusals carry why and a filled fix naming the refusing side; an unknown engine is `invalid_params`; `postgres` is the canonical engine name (`supabase` stays an alias).
+ - `gbrain sources refresh` runs inside a resident PGLite owner (`writer_refresh` administration operation); delegated syncs keep the progress-aware deadline; the consumer's idle probe honors the refresh fence.
+ - `gbrain sources add` no longer fails with `internal_error` (ENOENT under `.git/objects`) when a background `git gc` prunes the checkout while it is being registered.
+ - Search reuses its projection-readiness answer until the brain changes (`GBRAIN_PROJECTION_READINESS_CACHE=0` turns it off).
+ - The OpenClaw context-engine heartbeat reports seat write failures with their hints; a pattern page drops a seat its reflections no longer share (#4618).
+
+ ### For contributors
+
+ - Generated files were regenerated, not merged: migration registry, flag registry, schema blobs, llms bundles, goldens.
+ - New write-attribution suites `test/write-attribution-<family>.test.ts`; helpers `test/helpers/unmanaged-attribution.ts` and `attribution-history-fixture.ts` (`GBRAIN_TEST_BACKFILL_FIXTURE_PAGES`). A test that overrides an engine method with a copy bound to the base engine deadlocks on PGLite once the writer runs in a transaction; override through the transaction engine instead.
+ - `scripts/persistence/would-have-caught.ts` reverts past fixes one at a time and reports which the gate catches.
+
## [0.60.52.0] - 2026-10-04
**A PGLite brain that has saved memory can now move to Postgres with nothing lost: one command shows the plan, one confirmation moves it, and the move proves the copy matches before it switches.**
diff --cc scripts/module-size-limits.tsv
index b718aaea2d,7edd9ab883..6613ff8161
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -19,8 -19,8 +19,8 @@@ src/core/cycle/extract-atoms.ts 1809 ra
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
+src/core/operations.ts 337 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +1 #6007: pageBatchOperations import (spread shares the pages line)
- src/core/pglite-engine.ts 2978 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move)
+ src/core/pglite-engine.ts 2982 ratchet +4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move)
src/core/postgres-engine.ts 2919 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)
diff --cc scripts/persistence/model.ts
index 0000000000,492b58a69d..ed7cc2f848
mode 000000,100644..100644
--- a/scripts/persistence/model.ts
+++ b/scripts/persistence/model.ts
@@@ -1,0 -1,452 +1,455 @@@
+ /**
+ * The crash robot's reference model: an independent temporal oracle. It
+ * derives expectations from durable receipts (request id -> revision) plus a
+ * small state model of page identities, revisions, markers, withdrawals and
+ * supersession chains. Committed visibility is checked at the observation
+ * point (right after the caller saw the receipt); afterwards only legal
+ * transitions are allowed: a page's revision moves only when a committed op
+ * touched that page, and a withdrawn fact never becomes visible again.
+ *
+ * Documented exceptions: `remember` without an entity page writes a DB-only
+ * fact (src/core/persistence/memory-mutations.ts) and has no fence row; an
+ * explicit `remember` of a withdrawn claim is a new assertion, not a resurrection.
+ */
+ import type { EffectKind } from '../../src/core/persistence/effect-model.ts';
+ import { EFFECT_FAULT_POINTS, type FaultPoint } from '../../src/core/persistence/fault-points.ts';
+ import { operationsByName } from '../../src/core/operations.ts';
+ import { parseFactsFence } from '../../src/core/facts-fence.ts';
+ import { parseTakesFence } from '../../src/core/takes-fence.ts';
+ import { isRegistryCode } from '../../src/core/error-catalogue.ts';
+ import { CONNECTOR_SLUG, contextFor, type OpDescriptor, type OpKind, type OpObservation, type World } from './ops.ts';
+
+ /**
+ * How the generator reaches each effect kind's mid-effect seam: the op that
+ * queues it. A new effect kind without an entry fails typecheck.
+ * facts-backstop is queued only when facts extraction is configured; keyless
+ * robot brains never queue it, so its seam is exercised by the facts drain.
++ * links is queued only for remote (untrusted) page writes; its seam is
++ * exercised whenever the generator's put_page runs as a remote caller.
+ */
+ export const EFFECT_SEAMS = {
+ git: { op: 'put_page', point: EFFECT_FAULT_POINTS.git },
+ embedding: { op: 'put_page', point: EFFECT_FAULT_POINTS.embedding },
+ 'withdrawal-mirror': { op: 'forget', point: EFFECT_FAULT_POINTS['withdrawal-mirror'] },
+ 'facts-backstop': { op: 'put_page', point: EFFECT_FAULT_POINTS['facts-backstop'] },
++ links: { op: 'put_page', point: EFFECT_FAULT_POINTS.links },
+ } as const satisfies Record<EffectKind, { op: OpKind; point: FaultPoint }>;
+
+ /** Retry a harness read across a dropped connection (the pooler_disconnect fault); other errors propagate. */
+ export async function retryingRead<T>(read: () => Promise<T>): Promise<T> {
+ for (let attempt = 0; ; attempt++) {
+ try { return await read(); } catch (error) {
+ const text = `${(error as { code?: string }).code ?? ''} ${String((error as Error).message)}`;
+ if (attempt >= 8 || !/CONNECTION_CLOSED|CONNECTION_ENDED|ECONNRESET|57P01|08P01|08006|server conn crashed|terminating connection|Connection terminated/i.test(text)) throw error;
+ await Bun.sleep(150 * (attempt + 1));
+ }
+ }
+ }
+
+ /** Non-error outcomes a sync or connector run reports as its status (not error codes). */
+ const EXTERNAL_RESULT_CODES = new Set(['blocked_by_failures', 'dry_run']);
+
+ /**
+ * Findings outside the safety classes, filed in TODOS.md with a skipped test,
+ * stay visible in the manifest (`deferred`) without failing the gate.
+ */
+ export const KNOWN_DEFERRALS: { class: ViolationClass; match: RegExp; todo: string }[] = [
+ { class: 'untyped_error', match: /\(internal_error\)[\s\S]*(LockUnavailableError|SyncLockBusyError)/,
+ todo: 'TODOS.md "A held sync lock reaches agents as internal_error"' },
+ ];
+
+ export type ViolationClass = 'lost_write' | 'duplicate_apply' | 'untrue_receipt' | 'wedge' | 'withdrawal_permanence'
+ | 'source_isolation' | 'authorization' | 'caller_bound_replay' | 'projection_drift' | 'missing_attribution' | 'orphan_rows' | 'effects_not_terminal'
+ | 'untyped_error' | 'lock_order';
+ /** Violations that always block a ship (see the plan's bug-fix bound). */
+ export const SAFETY_CLASSES: ReadonlySet<ViolationClass> = new Set(['lost_write', 'duplicate_apply', 'untrue_receipt', 'wedge',
+ 'withdrawal_permanence', 'source_isolation', 'authorization', 'caller_bound_replay']);
+ export interface Violation { class: ViolationClass; op?: string; detail: string }
+
+ interface PageModel { live: boolean; revision: string | null; markers: Set<string>; lastMarker: string | null }
+ interface FactModel { id: string; source: string; text: string; entity: string; withdrawn: boolean; op: string }
+
+ const MARKER = /mk-[a-z]+\d+/g;
+ const key = (source: string, slug: string) => `${source}\u0000${slug}`;
+ function memberMarkersOf(members: { d: OpDescriptor }[]): string[] { return members.flatMap(x => markersIn(JSON.stringify(x.d.args))); }
+ function markersIn(text: string | undefined | null): string[] { return text ? [...text.matchAll(MARKER)].map(m => m[0]) : []; }
+ /** The newest page-body marker: edits insert theirs right after "Marker: ". */
+ function bodyMarker(text: string | undefined | null): string | null { return /Marker: (mk-[a-z]+\d+)/.exec(text ?? '')?.[1] ?? null; }
+
+ export class ReferenceModel {
+ pages = new Map<string, PageModel>();
+ facts = new Map<string, FactModel>();
+ /** Marker -> source of the committed op that introduced it. */
+ committedMarkers = new Map<string, string>();
+ /** Markers of ops that were refused: they must never become visible. */
+ refusedMarkers = new Set<string>();
+ /** Re-asserted withdrawn claims (an explicit remember after forget). */
+ reasserted = new Set<string>();
+ violations: Violation[] = [];
+ /** Pages a committed op touched in the current step: their revision may move. */
+ touched = new Set<string>();
+ revoked = new Set<string>();
+ /** Accepted but not yet terminal when the caller stopped waiting: settled by `settlePending`. */
+ pending = new Map<string, OpDescriptor>();
+
+ constructor(readonly world: World) {}
+ violate(v: Violation) { this.violations.push(v); }
+
+ /** Durable model state, so a worker started after a SIGKILL continues the same oracle. */
+ toJSON(): Record<string, unknown> {
+ return { pages: [...this.pages].map(([k, p]) => [k, { ...p, markers: [...p.markers] }]), facts: [...this.facts],
+ committedMarkers: [...this.committedMarkers], refusedMarkers: [...this.refusedMarkers], reasserted: [...this.reasserted],
+ revoked: [...this.revoked], violations: this.violations, pending: [...this.pending] };
+ }
+ static fromJSON(world: World, state: Record<string, any>): ReferenceModel {
+ const m = new ReferenceModel(world);
+ m.pages = new Map(state.pages.map(([k, p]: [string, any]) => [k, { ...p, markers: new Set(p.markers) }]));
+ m.facts = new Map(state.facts); m.committedMarkers = new Map(state.committedMarkers);
+ m.refusedMarkers = new Set(state.refusedMarkers); m.reasserted = new Set(state.reasserted);
+ m.revoked = new Set(state.revoked); m.violations = state.violations; m.pending = new Map(state.pending ?? []);
+ return m;
+ }
+ /** An interrupted op whose outcome is unknown: its marker may legally be visible, in its own source only. */
+ uncertain(d: OpDescriptor): void {
+ const marker = markersIn(JSON.stringify(d.args)).at(-1);
+ if (!marker) return;
+ this.refusedMarkers.delete(marker); this.committedMarkers.set(marker, d.source);
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : d.args.slug;
+ if (typeof slug === 'string') this.pages.delete(key(d.source, slug));
+ }
+ /** Pages an in-flight op names: a crash may or may not have committed it, so their revision may move. */
+ allowInFlight(ops: OpDescriptor[]): void {
+ for (const d of ops) {
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : d.args.slug ?? d.args.entity;
+ if (typeof slug === 'string') this.touched.add(key(d.source, slug));
+ if (d.kind === 'forget') for (const f of this.facts.values()) if (f.source === d.source) this.touched.add(key(f.source, f.entity));
+ }
+ }
+ /** Forget pending page-liveness expectations an in-flight delete/restore may have settled either way. */
+ relaxInFlight(ops: OpDescriptor[]): void {
+ for (const d of ops) if (['delete_page', 'restore_page', 'put_page', 'sync'].includes(d.kind) && typeof d.args.slug === 'string') {
+ this.pages.delete(key(d.source, d.args.slug));
+ }
+ }
+
+ page(source: string, slug: string): PageModel {
+ let p = this.pages.get(key(source, slug));
+ if (!p) { p = { live: false, revision: null, markers: new Set(), lastMarker: null }; this.pages.set(key(source, slug), p); }
+ return p;
+ }
+
+ /** Ops of the current concurrent group: their observation-point checks wait for `settleGroup`. */
+ private deferred = false;
+
+ /** Fold one observed op into the model and check its observation-point promises. */
+ async observe(d: OpDescriptor, o: OpObservation, original?: OpObservation): Promise<void> {
+ const marker = markersIn(JSON.stringify(d.args)).at(-1) ?? null;
+ if (d.replayOf && original) {
+ await this.checkReplay(d, o, original);
+ // A same-principal replay returns the original receipt; it is not a new write.
+ if (d.actor === original.actor) return;
+ }
+ if (d.actor !== 'local' && this.revoked.has(d.actor) && o.status === 'committed') {
+ this.violate({ class: 'authorization', op: d.id, detail: `${d.kind} by revoked ${d.actor} committed` });
+ }
+ if (o.status === 'pending') { this.pending.set(d.id, d); return; }
+ this.pending.delete(d.id);
+ if (o.status !== 'committed') {
+ if (marker && !this.committedMarkers.has(marker)) this.refusedMarkers.add(marker);
+ // The agent sees the MCP envelope: its code must be a registered one, and not the unknown-failure fallback.
+ const agentCode = o.agentCode ?? o.code;
+ if (o.status === 'refused' && agentCode !== 'http:401' && (!agentCode || !isRegistryCode(agentCode) || agentCode === 'internal_error') && !EXTERNAL_RESULT_CODES.has(o.code ?? '')) {
+ this.violate({ class: 'untyped_error', op: d.id, detail: `${d.kind} failed without a registered agent error code (${agentCode}): ${JSON.stringify(o.raw).slice(0, 300)}` });
+ }
+ return;
+ }
+ if (marker) { this.committedMarkers.set(marker, d.source); this.refusedMarkers.delete(marker); }
+ await MODEL[d.kind](this, d, o);
+ }
+
+ /** Start of a step: pages a committed op touches during this step (or a pending op names) may move their revision. */
+ beginStep(concurrent: boolean): void {
+ this.touched.clear(); this.deferred = concurrent;
+ this.allowInFlight([...this.pending.values()]);
+ }
+ get deferringVisibility(): boolean { return this.deferred; }
+
+ /**
+ * After a concurrent group: each touched page's revision must be one a
+ * committed group member returned, every committed edit's marker is
+ * visible, and every superseded member revision is in the page's history.
+ */
+ async settleGroup(batch: OpDescriptor[], observed: OpObservation[]): Promise<void> {
+ const committed = batch.map((d, i) => ({ d, o: observed[i] })).filter(x => x.o.status === 'committed');
+ const bySlug = new Map<string, typeof committed>();
+ for (const x of committed) {
+ const slug = x.d.kind === 'connector_publish' ? CONNECTOR_SLUG : String(x.d.args.slug ?? x.d.args.entity ?? '');
+ if (slug) bySlug.set(key(x.d.source, slug), [...(bySlug.get(key(x.d.source, slug)) ?? []), x]);
+ }
+ for (const [k, members] of bySlug) {
+ const [source, slug] = k.split('\u0000');
+ const read = await this.readPage('local', source, slug);
+ const revisions = members.map(x => x.o.values.revision).filter(Boolean) as string[];
+ if (revisions.length && !revisions.includes(String(read?.revision))) {
+ this.violate({ class: 'lost_write', op: members.map(x => x.d.id).join('+'), detail: `concurrent group left ${source}/${slug} at ${String(read?.revision)}, none of the committed revisions ${revisions.join(',')}` });
+ }
+ // Whole-page writers (put, sync, connector) may legally replace each other; edits and fact writes compose.
+ const replacing = members.some(x => ['put_page', 'sync', 'connector_publish'].includes(x.d.kind));
+ const memberMarkers = members.map(x => ['edit_page', 'put_page', 'sync', 'connector_publish'].includes(x.d.kind) ? markersIn(JSON.stringify(x.d.args)).at(-1) : null);
+ if (replacing && memberMarkers.some(Boolean) && !memberMarkers.some(mk => mk && markersIn(String(read?.content)).includes(mk))) {
+ this.violate({ class: 'lost_write', op: members.map(x => x.d.id).join('+'), detail: `no committed whole-page write of the group is visible in ${source}/${slug}` });
+ }
+ for (const [i, x] of members.entries()) {
+ const marker = memberMarkers[i];
+ if (!replacing && marker && !markersIn(String(read?.content)).includes(marker)) this.violate({ class: 'lost_write', op: x.d.id, detail: `committed concurrent ${x.d.kind} marker ${marker} is not visible` });
+ if (x.o.values.revision && x.o.values.revision !== read?.revision) {
+ const [kept] = await this.q<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id
+ WHERE p.source_id=$1 AND p.slug=$2 AND v.knowledge_revision::text=$3`, [source, slug, x.o.values.revision]);
+ if (!kept.n) this.violate({ class: 'untrue_receipt', op: x.d.id, detail: `committed revision ${x.o.values.revision} of ${source}/${slug} never existed` });
+ }
+ }
+ const page = this.page(source, slug);
+ page.revision = read?.revision ? String(read.revision) : null;
+ if (members.some(x => ['edit_page', 'put_page', 'sync', 'connector_publish'].includes(x.d.kind))) page.lastMarker = bodyMarker(String(read?.content)) ?? markersIn(String(read?.content)).find(mk => memberMarkersOf(members).includes(mk)) ?? page.lastMarker;
+ }
+ this.deferred = false;
+ }
+
+ /**
+ * Requests whose receipts the caller sees late (a pending write settled after
+ * the drain, or an interrupted request resubmitted after a crash) were
+ * committed in queue order with writes observed since. Their receipt must
+ * name a revision the page really had (current or archived in page_versions);
+ * the page's current state is then adopted as the model's.
+ */
+ async settleLate(batch: OpDescriptor[], observed: OpObservation[]): Promise<void> {
+ for (const [i, d] of batch.entries()) {
+ const o = observed[i];
+ if (o.status !== 'committed' || !o.values.revision) continue;
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : String(d.args.slug ?? d.args.entity ?? '');
+ const [seen] = await this.q<{ n: number }>(`SELECT
+ (SELECT count(*)::int FROM pages p WHERE p.source_id=$1 AND p.slug=$2 AND p.knowledge_revision::text=$3)
+ + (SELECT count(*)::int FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2 AND v.knowledge_revision::text=$3) AS n`,
+ [d.source, slug, o.values.revision]);
+ if (!seen.n) this.violate({ class: 'untrue_receipt', op: d.id, detail: `late receipt names revision ${o.values.revision} that ${d.source}/${slug} never had` });
+ }
+ for (const d of batch) {
+ const slug = d.kind === 'connector_publish' ? CONNECTOR_SLUG : d.args.slug ?? d.args.entity;
+ if (typeof slug !== 'string') continue;
+ const page = this.page(d.source, slug); const read = await this.readPage('local', d.source, slug);
+ this.touched.add(key(d.source, slug));
+ page.live = read !== null; page.revision = read?.revision ? String(read.revision) : null;
+ page.lastMarker = read ? bodyMarker(String(read.content)) : null;
+ }
+ this.deferred = false;
+ }
+
+ private async checkReplay(d: OpDescriptor, o: OpObservation, original: OpObservation): Promise<void> {
+ const sameActor = d.actor === original.actor;
+ const sameIntent = JSON.stringify(d.args) === JSON.stringify(this.world.descriptors?.get(original.id)?.args);
+ if (!sameActor) {
+ if (o.receipt && original.receipt && o.receipt.revision && o.receipt.revision === original.receipt.revision) {
+ this.violate({ class: 'caller_bound_replay', op: d.id, detail: `${d.actor} replaying ${original.actor}'s request id received the original receipt` });
+ }
+ return;
+ }
+ if (sameIntent) {
+ if (original.status === 'committed' && o.status !== 'committed') this.violate({ class: 'untrue_receipt', op: d.id, detail: `same-intent replay of a committed request returned ${o.status}/${o.code}` });
+ if (original.status === 'committed' && o.receipt?.revision && original.receipt?.revision && o.receipt.revision !== original.receipt.revision) {
+ this.violate({ class: 'duplicate_apply', op: d.id, detail: 'same-intent replay produced a new revision' });
+ }
+ } else if (original.status !== 'refused' && o.status === 'committed') {
+ this.violate({ class: 'caller_bound_replay', op: d.id, detail: 'changed intent under one request id committed instead of idempotency_conflict' });
+ }
+ }
+
+ /** Read surfaces an agent uses, under a given actor. */
+ /**
+ * The oracle's own reads retry a dropped connection (the pooler_disconnect
+ * fault terminates sessions between statements); only the system under test
+ * is judged on such errors.
+ */
+ private retrying<T>(read: () => Promise<T>): Promise<T> { return retryingRead(read); }
+ q<R = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<R[]> {
+ return this.retrying(() => this.world.engine.executeRaw<R>(sql, params));
+ }
+
+ /** The last read error, quoted in a violation so a failed read is never mistaken for a missing page. */
+ lastReadError: string | null = null;
+ async readPage(actor: string, source: string, slug: string): Promise<Record<string, unknown> | null> {
+ this.lastReadError = null;
+ try {
+ return await this.retrying(() => operationsByName.get_page.handler(contextFor(this.world, actor, source),
+ { slug, include_content: true, ...(actor === 'local' ? { source_id: source } : {}) })) as Record<string, unknown>;
+ } catch (error) {
+ const e = error as { code?: string; message?: string };
+ this.lastReadError = `${e.code ?? 'error'}: ${String(e.message).slice(0, 160)}`;
+ return null;
+ }
+ }
+ async recall(actor: string, source: string, entity: string): Promise<string[]> {
+ try {
+ const r = await this.retrying(() => operationsByName.recall.handler(contextFor(this.world, actor, source),
+ { entity, limit: 100, ...(actor === 'local' ? { source_id: source } : {}) })) as { facts?: { fact?: string }[] };
+ return (r.facts ?? []).map(f => String(f.fact ?? ''));
+ } catch { return []; }
+ }
+
+ /** Invariants over the whole brain; run after every step and after recovery. */
+ async checkGlobal(stage: string): Promise<void> {
+ const rows = await this.q<{ source_id: string; slug: string; compiled_truth: string; timeline: string; revision: string | null; deleted: boolean; id: number }>(
+ 'SELECT id,source_id,slug,compiled_truth,timeline,knowledge_revision::text AS revision,deleted_at IS NOT NULL AS deleted FROM pages');
+ const seen = new Set<string>();
+ for (const row of rows) {
+ const k = key(row.source_id, row.slug); seen.add(k);
+ for (const m of markersIn(`${row.compiled_truth}\n${row.timeline}`)) {
+ const owner = this.committedMarkers.get(m);
+ if (owner && owner !== row.source_id) this.violate({ class: 'source_isolation', detail: `${stage}: ${m} written to ${owner} is visible in ${row.source_id}/${row.slug}` });
+ if (!owner && this.refusedMarkers.has(m)) this.violate({ class: 'untrue_receipt', detail: `${stage}: refused write ${m} is visible in ${row.source_id}/${row.slug}` });
+ }
+ const model = this.pages.get(k);
+ if (!model) continue;
+ if (model.live === row.deleted) this.violate({ class: model.live ? 'lost_write' : 'untrue_receipt', detail: `${stage}: ${row.source_id}/${row.slug} live=${!row.deleted}, model expects ${model.live}` });
+ if (this.touched.has(k)) model.revision = row.revision;
+ else if (model.revision && row.revision !== model.revision) {
+ this.violate({ class: 'lost_write', detail: `${stage}: ${row.source_id}/${row.slug} revision ${row.revision} != last committed ${model.revision}` });
+ }
+ if (model.live && model.lastMarker && !markersIn(row.compiled_truth).includes(model.lastMarker)) {
+ this.violate({ class: 'lost_write', detail: `${stage}: ${row.source_id}/${row.slug} lost committed marker ${model.lastMarker}` });
+ }
+ }
+ for (const [k, model] of this.pages) if (model.live && !seen.has(k)) this.violate({ class: 'lost_write', detail: `${stage}: committed page ${k.replace('\u0000', '/')} is missing` });
+ await this.checkWithdrawals(stage);
+ await this.checkProjection(stage, rows.filter(r => !r.deleted));
+ await this.checkAttribution(stage);
+ }
+
+ private async checkWithdrawals(stage: string): Promise<void> {
+ const withdrawn = [...this.facts.values()].filter(f => f.withdrawn && !this.reasserted.has(`${f.source}\u0000${f.text}`));
+ for (const fact of withdrawn) {
+ const actors = ['local', ...this.world.remotes.filter(r => r.sourceId === fact.source && !this.revoked.has(r.name)).map(r => r.name)];
+ for (const actor of actors) {
+ if ((await this.recall(actor, fact.source, fact.entity)).includes(fact.text)) {
+ this.violate({ class: 'withdrawal_permanence', op: fact.op, detail: `${stage}: withdrawn fact "${fact.text}" returned by recall for ${actor}` });
+ }
+ }
+ const page = await this.readPage('local', fact.source, fact.entity);
+ const live = parseFactsFence(String(page?.content ?? '')).facts.filter(f => !f.forgotten && f.validUntil === undefined && f.claim === fact.text);
+ if (live.length) this.violate({ class: 'withdrawal_permanence', op: fact.op, detail: `${stage}: withdrawn fact "${fact.text}" is a live row in ${fact.source}/${fact.entity}'s fence` });
+ const [db] = await this.q<{ n: number }>(
+ 'SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [fact.source, fact.text]);
+ if (db.n > 0) this.violate({ class: 'withdrawal_permanence', op: fact.op, detail: `${stage}: withdrawn fact "${fact.text}" has ${db.n} active row(s)` });
+ }
+ }
+
+ private async checkProjection(stage: string, live: { id: number; source_id: string; slug: string }[]): Promise<void> {
+ for (const row of live) {
+ const page = await this.readPage('local', row.source_id, row.slug);
+ const content = String(page?.content ?? '');
+ const takes = parseTakesFence(content).takes;
+ const dbTakes = await this.q<{ row_num: number; claim: string; active: boolean }>(
+ 'SELECT row_num,claim,active FROM takes WHERE page_id=$1 ORDER BY row_num', [row.id]);
+ const fence = takes.map(t => `${t.rowNum}:${t.claim}:${t.active}`).sort();
+ const db = dbTakes.map(t => `${t.row_num}:${t.claim}:${t.active}`).sort();
+ if (JSON.stringify(fence) !== JSON.stringify(db)) this.violate({ class: 'projection_drift', detail: `${stage}: ${row.source_id}/${row.slug} takes fence ${JSON.stringify(fence)} != rows ${JSON.stringify(db)}` });
+ const liveFacts = parseFactsFence(content).facts.filter(f => !f.forgotten && f.validUntil === undefined).map(f => f.claim).sort();
+ const dbFacts = (await this.q<{ fact: string }>(`SELECT fact FROM facts WHERE source_id=$1 AND source_markdown_slug=$2
+ AND expired_at IS NULL AND superseded_by IS NULL AND (valid_until IS NULL OR valid_until > now())`, [row.source_id, row.slug])).map(f => f.fact).sort();
+ if (JSON.stringify(liveFacts) !== JSON.stringify(dbFacts)) this.violate({ class: 'projection_drift', detail: `${stage}: ${row.source_id}/${row.slug} facts fence ${JSON.stringify(liveFacts)} != rows ${JSON.stringify(dbFacts)}` });
+ }
+ const [orphans] = await this.q<{ takes: number; timeline: number }>(`SELECT
+ (SELECT count(*)::int FROM takes t WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id=t.page_id)) AS takes,
+ (SELECT count(*)::int FROM timeline_entries e WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id=e.page_id)) AS timeline`);
+ if (orphans.takes || orphans.timeline) this.violate({ class: 'orphan_rows', detail: `${stage}: orphan takes=${orphans.takes} timeline=${orphans.timeline}` });
+ }
+
+ private async checkAttribution(stage: string): Promise<void> {
+ const [missing] = await this.q<{ facts: number; takes: number; timeline: number; pages: number }>(`SELECT
+ (SELECT count(*)::int FROM facts WHERE write_principal_kind IS NULL) AS facts,
+ (SELECT count(*)::int FROM takes WHERE write_principal_kind IS NULL) AS takes,
+ (SELECT count(*)::int FROM timeline_entries WHERE write_principal_kind IS NULL) AS timeline,
+ (SELECT count(*)::int FROM pages WHERE deleted_at IS NULL AND revision_principal_kind IS NULL) AS pages`);
+ for (const [table, n] of Object.entries(missing)) if (n) this.violate({ class: 'missing_attribution', detail: `${stage}: ${n} ${table} row(s) without write attribution` });
+ }
+
+ /** After a drain: nothing pending, every effect terminal, and a fresh write still admits (no wedge). */
+ async checkDrained(stage: string): Promise<void> {
+ const [pending] = await this.q<{ requests: number; effects: number }>(`SELECT
+ (SELECT count(*)::int FROM persistence_requests WHERE state IN ('queued','running','recovering')) AS requests,
+ (SELECT count(*)::int FROM persistence_effects WHERE state IN ('queued','running') OR recovery IS NOT NULL) AS effects`);
+ if (pending.requests) this.violate({ class: 'wedge', detail: `${stage}: ${pending.requests} request(s) still pending after the drain` });
+ if (pending.effects) this.violate({ class: 'effects_not_terminal', detail: `${stage}: ${pending.effects} effect(s) not terminal after the drain` });
+ }
+ }
+
+ type Fold = (m: ReferenceModel, d: OpDescriptor, o: OpObservation) => Promise<void>;
+ const pageWrite = (kind: 'put' | 'edit'): Fold => async (m, d, o) => {
+ const slug = String(d.args.slug); const page = m.page(d.source, slug); const k = key(d.source, slug);
+ const marker = d.args.content === '$stale_content' ? bodyMarker(o.pageContent)
+ : markersIn(String(d.args.content ?? JSON.stringify(d.args.edits ?? ''))).at(-1) ?? null;
+ page.live = true; page.revision = o.values.revision ?? null; m.touched.add(k);
+ if (kind === 'put') page.markers = new Set(markersIn(o.pageContent));
+ if (marker) page.markers.add(marker);
+ page.lastMarker = marker;
+ if (m.deferringVisibility) return;
+ const read = await m.readPage(d.actor === 'local' || m.revoked.has(d.actor) ? 'local' : d.actor, d.source, slug);
+ if (!read || read.revision !== o.values.revision) {
+ const [row] = await m.q<Record<string, unknown>>(`SELECT knowledge_revision::text AS revision,deleted_at IS NOT NULL AS deleted,
+ source_path FROM pages WHERE source_id=$1 AND slug=$2`, [d.source, slug]);
+ m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed ${d.kind} revision ${o.values.revision} not visible (read ${String(read?.revision)}${m.lastReadError ? `; ${m.lastReadError}` : ''}; row ${JSON.stringify(row ?? null)})` });
+ }
+ else if (page.lastMarker && !markersIn(String(read.content)).includes(page.lastMarker)) m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed ${d.kind} marker ${page.lastMarker} not visible` });
+ };
+ const touch = (slugOf: (d: OpDescriptor) => string): Fold => async (m, d, o) => {
+ const k = key(d.source, slugOf(d)); m.touched.add(k);
+ const page = m.page(d.source, slugOf(d));
+ if (o.values.revision) page.revision = o.values.revision;
+ else page.revision = null;
+ };
+
+ /** A file edit picked up by sync, or a connector item: the page now carries its marker. */
+ function externalWrite(target: (d: OpDescriptor) => [string, string, string]): Fold {
+ return async (m, d) => {
+ const [source, slug, text] = target(d);
+ const marker = markersIn(text).at(-1) ?? null;
+ const page = m.page(source, slug); m.touched.add(key(source, slug));
+ page.live = true; page.revision = null; page.lastMarker = marker;
+ if (marker) { page.markers.add(marker); m.committedMarkers.set(marker, source); }
+ if (m.deferringVisibility) return;
+ const read = await m.readPage('local', source, slug);
+ if (marker && !markersIn(String(read?.content)).includes(marker)) m.violate({ class: 'untrue_receipt', op: d.id, detail: `${d.kind} reported success but ${source}/${slug} lacks ${marker}` });
+ };
+ }
+
+ /** One fold per op kind: how a committed observation moves the model, plus its observation-point check. */
+ export const MODEL: Record<OpKind, Fold> = {
+ put_page: pageWrite('put'),
+ edit_page: pageWrite('edit'),
+ remember: async (m, d, o) => {
+ const text = String(d.args.fact); const entity = String(d.args.entity ?? '');
+ if (o.values.fact_id) m.facts.set(o.values.fact_id, { id: o.values.fact_id, source: d.source, text, entity, withdrawn: false, op: d.id });
+ if ([...m.facts.values()].some(f => f.withdrawn && f.source === d.source && f.text === text)) m.reasserted.add(`${d.source}\u0000${text}`);
+ await touch(() => entity)(m, d, o);
+ const status = (o.raw as { status?: string } | undefined)?.status;
+ if (!m.deferringVisibility && status !== 'duplicate' && !(await m.recall(m.revoked.has(d.actor) ? 'local' : d.actor, d.source, entity)).includes(text)) {
+ m.violate({ class: 'untrue_receipt', op: d.id, detail: `committed remember "${text}" not returned by recall` });
+ }
+ },
+ forget: async (m, d, o) => {
+ const id = String((o.raw as { id?: unknown } | undefined)?.id ?? '');
+ const fact = m.facts.get(id);
+ if (fact) {
+ if (fact.source !== d.source) m.violate({ class: 'source_isolation', op: d.id, detail: `forget in ${d.source} expired fact ${id} of ${fact.source}` });
+ fact.withdrawn = true; m.reasserted.delete(`${fact.source}\u0000${fact.text}`);
+ m.touched.add(key(fact.source, fact.entity)); m.page(fact.source, fact.entity).revision = null;
+ }
+ },
+ takes_add: touch(d => String(d.args.slug)),
+ takes_supersede: touch(d => String(d.args.slug)),
+ add_timeline_entry: touch(d => String(d.args.slug)),
+ delete_page: async (m, d, o) => { await touch(d => String(d.args.slug))(m, d, o); m.page(d.source, String(d.args.slug)).live = false; },
+ restore_page: async (m, d, o) => { await touch(d => String(d.args.slug))(m, d, o); m.page(d.source, String(d.args.slug)).live = true; },
+ revoke_access: async (m, d) => { m.revoked.add(String(d.args.actor)); },
+ sync: externalWrite(d => [d.source, String(d.args.slug), String(d.args.content)]),
+ connector_publish: externalWrite(d => [d.source, CONNECTOR_SLUG, String(d.args.body)]),
+ };
diff --cc src/core/persistence/coordinator.ts
index b0d6e5272d,93cc757a01..5d8457f17b
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@@ -141,31 -142,9 +142,32 @@@ export function decoratePublicationOutc
* The root lock spans all file effects; the DB guards span authorization and
* publication. A rejected/ambiguous commit is recovered before releasing FIFO.
*/
+/**
+ * The recovery record of one page file publication (its before bytes, hashes,
+ * mode and reserved staging names) and the recovery bytes it reserves. Read
+ * while holding the worktree's native lock, before any file is touched.
+ */
+export function pageRecoveryRecord(row: WriteRequest, file: PageMutationFile, binding: WorktreeBinding): { record: FileRecoveryRecord; bytes: number } {
+ const before = existsSync(file.path) ? readFileSync(file.path) : null;
+ const record: FileRecoveryRecord = {
+ version: 1, path: file.path, root: file.root,
+ before: before?.toString('base64') ?? null, beforeHash: before ? sha256(before) : null,
+ afterHash: file.content === null ? null : sha256(file.content),
+ mode: before ? statSync(file.path).mode & 0o7777 : null,
+ ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!,
+ staging: {
+ ...(file.content === null ? {} : { publication: recoveryStagingFile(file.path, file.content) }),
+ ...(before === null ? {} : { restoration: recoveryStagingFile(file.path, before) }),
+ },
+ };
+ const nextBytes = file.content === null ? 0 : typeof file.content === 'string' ? Buffer.byteLength(file.content) : file.content.byteLength;
+ const beforeBytes = before?.byteLength ?? 0;
+ return { record, bytes: Math.max(beforeBytes * 3 + nextBytes * 2, Buffer.byteLength(JSON.stringify(record)) + beforeBytes + nextBytes) + 4096 };
+}
+
export async function publishMutation(engine: BrainEngine, row: WriteRequest, prepared: PreparedMutation,
- hostId = localHostId(), hooks: PublicationHooks = {}): Promise<WriteRequest> {
+ hostId = localHostId(), callerHooks: PublicationHooks = {}): Promise<WriteRequest> {
+ const hooks = withFaultPoints(callerHooks);
let lock: NativeLockHandle | null = null;
let releaseCapacity: (() => void) | null = null;
let binding: WorktreeBinding | null = null;
diff --cc src/core/persistence/effect-journal.ts
index f6eac2e207,c932f45668..434c691b37
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@@ -13,17 -13,11 +13,18 @@@ import { loadConfig } from '../config.t
import { resolveDefaultVisibility } from '../facts/visibility.ts';
import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { refreshFenceClear } from './worktree-refresh-schema.ts';
+import { pageBatchChildRequestIds } from './page-batch-id.ts';
+ import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';
-/** `snapshot` is the publication's final read of the page, including deleted rows, in this transaction. */
+/**
+ * `snapshot` is the publication's final read of the page, including deleted rows, in this transaction.
+ * A remote put_page/capture/edit_page also queues a `links` effect, in one statement that inserts
+ * nothing while `auto_link` or `mcp.remote_auto_links` is off (unset is on).
+ */
export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>, snapshot: PageSnapshot | null,
- outcome: Record<string, unknown>, prepared?: PreparedMutation): Promise<void> {
+ outcome: Record<string, unknown>, prepared?: PreparedMutation,
+ /** A grouped publication completes its members after queueing all of them, then calls `reconcileFinishedBatch` itself. */
+ opts: { deferBatchReconcile?: boolean } = {}): Promise<void> {
if (prepared?.noop || prepared?.target === 'skill_bundle') return;
await declarePersistenceProtocol(tx);
const revision = snapshot?.revision;
diff --cc src/core/persistence/fault-points.ts
index 0000000000,2ff1f7e8c2..899a039c60
mode 000000,100644..100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@@ -1,0 -1,42 +1,43 @@@
+ /**
+ * Named crash seams for the persistence gate (`scripts/persistence/`). Each
+ * seam sits at a point where a process death leaves durable state the
+ * recovery path must finish: publication boundaries, after an effect's side
+ * effect but before its completion is recorded, before a recovery record is
+ * cleared, between sync checkpoints, and after the consumer prepared a
+ * claimed request. Production never installs a hook, so every call is a
+ * no-op there; the gate's workers install one that SIGKILLs or stalls the
+ * process at a chosen point.
+ */
+ import type { EffectKind } from './effect-model.ts';
+ import type { PublicationHooks } from './coordinator.ts';
+ import type { WriteRequest } from './model.ts';
+
+ export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];
+ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid`
+ | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'consumer:prepared';
+ export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null }
+ type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;
+
+ /** The mid-effect seam of every effect kind; a new kind without one fails typecheck. */
+ export const EFFECT_FAULT_POINTS: Record<EffectKind, FaultPoint> = {
+ git: 'effect:git:mid',
+ embedding: 'effect:embedding:mid',
+ 'withdrawal-mirror': 'effect:withdrawal-mirror:mid',
+ 'facts-backstop': 'effect:facts-backstop:mid',
++ links: 'effect:links:mid',
+ };
+
+ let installed: FaultHook | undefined;
+ /** Gate workers only. */
+ export function installFaultHook(hook: FaultHook | undefined): void { installed = hook; }
+ export async function faultPoint(point: FaultPoint, detail: FaultDetail = {}): Promise<void> {
+ if (installed) await installed(point, detail);
+ }
+ /** Publication hooks that also reach the installed seam; returns the caller's hooks unchanged when none is installed. */
+ export function withFaultPoints(hooks: PublicationHooks): PublicationHooks {
+ if (!installed) return hooks;
+ return { ...hooks, async boundary(name: PublicationBoundary, row: WriteRequest) {
+ await hooks.boundary?.(name, row);
+ await faultPoint(`publication:${name}`, { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });
+ } };
+ }
diff --cc test/fixtures/goldens/cli/tools-json.json
index b38edfba85,2f3183df9d..a6b3c44c98
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@@ -2,8 -2,8 +2,8 @@@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 199714,
- "stdoutSha256": "961f72b106aa1150f888864c865a65a9fe4e2fd391c5ff0e1bed921ece4ea1c9",
- "stdoutBytes": 197023,
- "stdoutSha256": "20847890a8675cef50b3fc32b88c43beae726ee1a0b84a78e7de69d2ce63fa9c",
++ "stdoutBytes": 199751,
++ "stdoutSha256": "07411c9b9efbfda138af2a0efbef740b1d0e4354f8f8c391a9a9a3976a66832d",
"toolNames": [
"remember",
"entity",