Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge master 43a434db into the GST-2260 stale-plan heal, trimmed to the driver heal and the two database-only re-runs

garrytan2ec9846aeb5d
diff --cc CHANGELOG.md
index 90b6b24de6,4c16397716..3018ad1366
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,19 -10,274 +10,286 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
- **A running `gbrain serve`, worker or autopilot no longer fails writes after another process changes a table's columns (GST-2260).** When `gbrain apply-migrations` or an upgrade in another process added, renamed or dropped a column, every pooled connection that had already prepared a `SELECT *` or `RETURNING *` on that table failed its next run with "cached plan must not change result type". Outside a transaction the driver quietly prepared the statement again, but inside one the error had already aborted the transaction, so the caller saw it: a `put_page` came back `internal_error`, or was accepted and then failed at publication, once for each statement on each pooled connection. Now the first such error makes every connection in the process prepare its statements again before its next query, the write paths re-run the transaction it aborted, and so do an OAuth token grant whose client read meets it and a minion job's completion or failure record. Pools that do not prepare statements (transaction-mode pooler URLs, `prepare: false`) and PGLite are unchanged.
++**A running `gbrain serve`, worker or autopilot no longer fails writes after another process changes a table's columns (GST-2260).** When `gbrain apply-migrations` or an upgrade in another process added, renamed or dropped a column, every pooled connection that had already prepared a `SELECT *` or `RETURNING *` on that table failed its next run with "cached plan must not change result type". Outside a transaction the driver quietly prepared the statement again, but inside one the error had already aborted the transaction, so the caller saw it: a `put_page` came back `internal_error`, or was accepted and then failed at publication, once for each statement on each pooled connection. Version 0.60.646.0 made the write paths re-run the transaction it aborted. Now the first such error also makes every connection in the process prepare its statements again before its next query, and an OAuth token grant whose client read meets it and a minion job's completion or failure record are re-run too. Pools that do not prepare statements (transaction-mode pooler URLs, `prepare: false`) and PGLite are unchanged.
+
+### Itemized changes
+
+- `vendor/postgres` (`patches/[email protected]`): the first `RevalidateCachedQuery` error on a statement a connection had cached starts a process-wide plan generation; each connection drops its prepared statements before it builds its next query, and a statement described under an older generation is not cached in the new one.
- - `src/core/retry-matcher.ts`: `isStalePlanError` (SQLSTATE 0A000 with routine `RevalidateCachedQuery`, never the code alone) and `retryOnStalePlan`, one more run for a transaction that does only database work.
- - `src/core/persistence/admission-retry.ts`, `src/core/persistence/coordinator.ts`: write admission re-runs a stale plan up to three times within its existing budget and then rethrows it unchanged, and publication and effects release a claim it aborted, as they do for contention.
++- `src/core/retry-matcher.ts`: `retryOnStalePlan`, one more run, on 0.60.646.0's `isStalePlanError`, for a transaction that does only database work.
+- `src/core/oauth-grants.ts`: the client-locked OAuth grant transaction runs once more when a stale plan fails its opening client read, before the callback writes anything.
+- `src/core/minions/queue.ts`: `completeJob` and `failJob`, whose transactions do only database work, run once more after a stale plan.
+- Tests: `test/stale-plan-heal.test.ts` (Postgres; listed in `test/postgres-unit-arms.txt`).
+
+ ## [0.60.646.0] - 2026-11-10
+
+ **A migration that adds a column under a running server no longer fails writes on direct Postgres.** On a direct Postgres connection the driver reuses each connection's prepared statements. When a migration adds a column to a table that a `SELECT *` reads, the next run of that statement inside a transaction fails with SQLSTATE 0A000, "cached plan must not change result type", once per pooled connection. Outside a transaction the driver quietly prepares it again; inside one, the transaction is already aborted and the error reaches the write. Two places lost writes this way. A legacy-token write whose authority reads `access_tokens` failed with `storage_error` and committed nothing; a retry worked. Worse, after a migration added a column to `persistence_requests`, an accepted write could end `failed`/`storage_error` at publication and was never retried, so a caller that left on `write_pending` lost it unless it polled the receipt; other submissions were refused at admission with `internal_error`. Four of the last 50 migrations (v254, v261, v292, v294) changed that table. Now the two `access_tokens` reads name their columns, so a new column leaves their result unchanged; the stale-plan error counts as a transient interruption of the write (cause `stale_plan`), so the request is claimed again after the usual backoff and stays bounded by `persistence.max_transient_retries`; and admission re-runs on it like a serialization failure. Only the stale-plan error matches (the server's plan-revalidation routine, in any locale, or that English message): every other 0A000 stays a refusal. Both reads also keep working on a schema behind the build (a brain whose migrations could not be applied): an accepted legacy-token write still replays, a new one is refused `migrations_pending`, and shared-skill membership still works. A transaction-mode pooler (`prepare=false`) and PGLite were never affected. Writes that already failed this way stay failed; `gbrain doctor`'s terminal-failures check lists them, and each needs a resubmit with a new `request_id`.
+
+ ### Itemized changes
+
+ - `src/core/retry-matcher.ts`: `isStalePlanError` matches SQLSTATE 0A000 with the server routine `RevalidateCachedQuery`, or, when no routine is reported, the "cached plan must not change result type" message.
+ - `src/core/persistence/transient-retry.ts`: `transientInterruption` returns `{ cause: 'stale_plan', sqlstate: '0A000' }` for it, so `finishUnpublishedFailure`, the recovery route and grouped publication charge it against `persistence.max_transient_retries` and release the claim with backoff; past the limit the write ends `write_interrupted`. `src/core/persistence/coordinator.ts` words that receipt for the new cause.
+ - `src/core/persistence/admission-retry.ts`: `retryWriteAdmission` re-runs an admission that hit it, within its existing time budget.
+ - `src/core/persistence/coordinator.ts`: `transientDatabaseFailure` also accepts the stale-plan error, so with `persistence.preparation_deadlines false` it is released uncounted as database contention, as a 57014 is; the effect worker, the consumer's release paths and the recovery resolver share that predicate.
+ - `src/core/grants/model.ts`: `TOKEN_GRANT_ROW_COLUMNS` lists the columns `grantFromTokenRow` reads, and the async `tokenGrantRowSelect(engine)` selects the ones the table has; `src/core/persistence/authority.ts` (publication authority, `FOR SHARE`) and `src/core/shared-skills/membership-authority.ts` use it instead of `*`, at the cost of one catalog read per legacy-token call.
+ - Docs: `docs/guides/write-refusals.md` and `docs/guides/error-codes.md` (`write_interrupted`), `docs/architecture/key-files/persistence-stalls.md`.
+ - Tests: `test/persistence-stale-plan-retry.test.ts` adds a `persistence_requests` column under a pool of 3 and requires all 9 later `put_page` calls to commit with no request past the retry limit (on the previous code 3 to 9 of the 9 failed; without the admission retry or without the publication classification it still fails). `test/access-token-grant-columns.test.ts` runs both `access_tokens` reads on every pooled connection before and after an added column, plus a legacy-token `put_page` (all three failed on the previous code). Its worktree-backed case does the same on a git checkout and requires each page's file once with one Git commit (on the previous code 5 and 6 writes failed). `test/access-token-grant-columns.test.ts` also drops `private_pages` to stand in for an older schema: both reads still work, an accepted request replays and a new one is refused `migrations_pending` (42703 or `unavailable` on the previous code). `test/stale-plan-classification-gst2314.test.ts` covers the routine match, a non-English message and that other 0A000 errors stay refusals. `test/publication-failure-owner-exception.test.ts` now uses a different 0A000 as its sample owner exception, since the stale-plan one retries. `test/access-ungranted-member-writes.test.ts` resets its connections after the column-rename case, which left stale plans for the next test; no assertion changed.
+
+ ## [0.60.645.0] - 2026-11-10
+
+ **A GitHub (or other API) connector source no longer stops for good when one of its items is a page stored in segments.** A long issue (a body plus hundreds of comments) grows past 1 MiB and is stored in segments. Before, that item could never import, and once such a page existed, every later sweep of a bound source stopped on `page_body_segmented` with no item named, so nothing after it imported and the cursor never moved. Now an item up to 24 MiB imports and re-renders like any other, and one the sweep cannot read whole (over 24 MiB) fails on its own from the first sweep, and is held after three (`gbrain sources status`), while the rest of the run imports and the cursor moves; a new comment on it re-tries only that item. Reported and first diagnosed in #9062.
+
+ ### Itemized changes
+
+ - `src/core/persistence/connector-sync.ts`: the connector publication reads a segmented page back as strings (up to 24 MiB) before it carries its timeline and fences into the re-render, seals a segmented body through its import (never the inline text seal, which read the whole timeline), and runs the import's after-commit step, so a segmented page left unsealed is chunked. The freshness read (`page()`) reads a segmented page back the same way.
+ - `src/core/github-source.ts`: a stored page the sweep cannot read fails that item (a content hold after three runs), not the run.
+ - `src/core/connectors/connector-hold-session.ts`: on a bound source, `page_body_segmented` raised before any write request is counted against the item instead of aborting the run, as invalid connector text already was.
+ - Tests: `test/connector-segmented-page-9062.test.ts` (PGLite) and its PostgreSQL arm `test/e2e/connector-segmented-page-9062.test.ts`.
+
+ ## [0.60.644.0] - 2026-11-10
+
+ **`gbrain doctor` now ends on its `--budget-ms` deadline when `git` hangs in an OpenClaw workspace.** The bootstrap entry checks push health by running `git status`, `git branch` and `git rev-list` on the install receipt's workspace, and on a workspace whose last push failed. Those calls ran synchronously with a 10-second limit each. While one hung, nothing else in the process could run, so the run overran its budget and every later check, the cheap incident checks included, started with no time left. They now run asynchronously, like the home-dir probes since #8979. Each call is killed with SIGKILL, together with its process group, at 10 seconds or at the entry's deadline, whichever comes first, and a call that fails or is cut short reads as unverified, as before. Every local probe's output is also capped at 1 MiB again: a probe that prints more than that is killed and reads as absent, which is what `execFile`'s buffer limit did before #8979.
+
+ **The Postgres crash robot no longer fails a full run when a race makes one fewer slot than its count run saw.** The robot first runs each schedule to count the seams it reaches, then crashes one run at a counted slot. In `sync_and_connector_race_direct_write`, the connector republish races a direct write, and the race legally settles two ways: one makes 5 publications, the other 6, with the git effects, preparations and commits following. A crash planned at the 6th publication was never reached by a run that took the 5-publication outcome, and the job failed with `fault_not_reached` (#8078). A run that misses its fault now reports how many slots of that seam it made. If it was exactly one short of the count run, it runs once more at its last slot, and the manifest records `retargeted` on the run and lists it under `faults_retargeted`. A run that found violations, made no slot, fell two or more short, or misses again still fails as `fault_not_reached`.
+
+ ### Itemized changes
+
+ - `src/commands/doctor/local-probe.ts`: `localProbe` moved here from `checks/local-audits.ts`. It takes `ownTimeoutMs` (default 5 s) and `windowsShell` (git runs without cmd.exe on Windows), and it kills a probe and returns null once its stdout passes `LOCAL_PROBE_MAX_OUTPUT_BYTES` (1 MiB).
+ - `src/commands/doctor/bootstrap-checks.ts`: `bootstrapDoctorChecks(engine, entryDeadlineAt)` runs every git call through `localProbe` with a 10 s bound. `commitsAheadOfOrigin`, `treeMatchesOrigin` and `recordedPushFailureCheck` are async.
+ - Tests: `test/doctor-bootstrap-git-deadline-8990.test.ts`. A `git` stand-in that ignores SIGTERM and waits on a 6 s child is killed within a 1000 ms budget, on both the workspace probe and the recorded-failure probe, and neither it nor its child survives (each fails on the previous code, at 18 s and 12 s). A probe that floods stdout is killed within 1.5 s and reads as absent, one that prints 2 MiB and exits reads as absent, and one under the cap returns its whole output (the first two fail without the cap).
+ - `scripts/persistence/crash-robot.ts`: the run role's fault hook reports `reached`, the slots of its seam it made. `scripts/persistence/robot-driver.ts`: a planned crash carries `counted` (the count run's slots), and `retargetable` reruns a run once when it found no violations, `counted` is set and `0 < reached`, `counted - 1 <= reached < nth`.
+ - Tests: `test/persistence-crash-robot.test.ts`. A run one slot short crashes at its last slot and passes; a short run with violations, a run two short, a run short again after the retarget, a run with no slot and a run with no counted plan still fail. The failed #9071 manifest entry, given the `counted: 6` its count run saw, failed 4 of 4 on Postgres before the fix and passed 3 of 3 after it, crashing at the 5th publication.
+
+ ## [0.60.643.0] - 2026-11-10
+
+ **Retrying an interrupted `gbrain sources remove` or `purge` can no longer delete a re-added source's pages.** A managed remove or purge deletes a large source's pages in batches, and a run that stops partway can be finished by rerunning it with the same `--request-id`. Until now nothing tied that request id to the source it was started against: if the source was removed and added again under the same ID in between, the rerun deleted the new source's pages. The first batch now records which incarnation of the source the request was admitted against, in the same transaction as its first deletion. A rerun against the same incarnation still resumes and finishes; a rerun after the source was replaced refuses with `source_retire_superseded` and changes nothing. Restoring, archiving or otherwise changing the source after a run stopped abandons that run the same way, so a purge stopped before a restore can't hold up `deactivate` or graduation for good, and both ask the user before a stopped run is finished, since finishing deletes the rest of the source's pages. A stopped automatic expired-archive purge is left to the next automatic run instead of being handed to a person, and `gbrain sources writer status --source <id> --json` now lists a source's stopped and superseded remove and purge requests.
+
+ ### Itemized changes
+
+ - `src/core/persistence/topology-receipts.ts`: `admitTopologyRetire` records a retire admission (a `persistence_topology_changes` row in state `recovering` with no recovery record, bound to the source incarnation, holding one lifetime ID and a full receipt reservation after the same quota check `assertTopologyChangeCapacity` made); `recordTopologyChange` settles a request's own admission `committed` and trues up its receipt bytes; `supersedeTopologyRetires` settles other requests' admissions `failed` when a remove or purge deletes their incarnation, or when any other lifecycle operation (archive, restore, rebind, claim) commits a change to it; it skips only the caller's own (principal, request id) pair, so a retry under a replaced CLI registration settles the old registration's admission too.
+ - `src/core/persistence/source-lifecycle.ts`: a request id whose admission names another incarnation than the source registered now refuses `source_retire_superseded` before any lock or deletion (a dry run too) and settles the admission `failed`, so a later retry refuses the same way; the batches and the final transaction resume past their own admission (#8984).
+ - `src/core/persistence/source-lifecycle.ts`: a remove or purge retry also refuses `source_retire_superseded` when another CLI registration (one replaced since) admitted the same request id against a different incarnation of the source, and settles that admission `failed`; idempotency is per registration, so before this the retry ran as a new request and deleted the re-added source's pages. An admission bound to the current incarnation still resumes under the new registration (#8984).
+ - `src/core/error-registry.ts`: new caller code `source_retire_superseded`, with a read-only writer-status fix; `sources writer status --json` gains `topology_requests` (recovering admissions and superseded requests).
+ - `src/core/persistence/deactivation.ts`, `graduation-drain.ts`: an unfinished retire is listed as a blocker that names its request id and asks the user whether to finish it (rerun the same command with its request id) or keep what is left (another lifecycle change abandons it); graduation marks it `needsUser`. A stopped automatic expired-archive purge (its admission records `expired_only`) instead says the next automatic run finishes it, with `needsUser: false`.
+ - Tests: `test/source-retire-incarnation.test.ts` (PGLite) and `test/e2e/source-retire-incarnation-postgres.test.ts`: a retry after the final transaction failed, and a retry after committed batches already deleted part of the source, both refuse once the source was replaced and keep the new source's pages (both resolved `committed` on master); a same-incarnation retry resumes and settles; a restore after an interrupted purge abandons it, so its retry refuses and no blocker stays. `test/source-retire-batched.test.ts` and its Postgres twin now expect the interrupted run's admission row.
+
+ ## [0.60.642.0] - 2026-11-10
+
+ **A purged page's facts no longer come back.** When the 72-hour retention purge removed a soft-deleted page's row, it left the page's facts active, because facts have no foreign key to pages. Once the tombstone was gone, those facts showed up again for every reader, local and remote, and a new page written at the same slug picked them up. The purge now expires those facts in the same transaction as the page delete: the facts filed on the page, and the facts about it that no page holds. The rows are kept, expired, never deleted. A fact another page holds about the slug stays active, even when that page is soft-deleted, so restoring it brings the fact back. An ontology observation about a live entity that was sourced from the purged page also stays active.
+
+ ### Itemized changes
+
+ - `src/core/facts/gone-page-facts.ts`: `expireGonePageFacts`, the facts a purged page takes with it, as two updates that each use their slug index.
+ - `src/core/engine-sql/pages.ts` (`purgeDeletedPages`, the bulk purge) and `src/core/persistence/purge-deleted.ts` (`expireRecordedTombstones`, the belief-ledger purge of a recorded source) call it in the purge transaction. The managed purge already sweeps the facts filed on the page.
+ - Tests: `test/purge-expires-page-facts.test.ts` (PGLite and Postgres), which fails before the fix on the bulk and recorded purges.
+
+
+ ## [0.60.641.0] - 2026-11-10
+
+ **Facts, timeline entries, tags and ontology observations now follow the page they are about, so a remote caller who cannot read a page learns nothing about it from fact reads, and a deleted page's facts, timeline and tags stay hidden from everyone until it is restored.** Before this, a fact saved on an open page about a page with `readable_by` or `visibility: private` still reached remote callers through recall, ontology_get, volunteer_chronicle, delta, find_trajectory, hot memory and the entity card, and a soft-deleted page's facts, timeline rows and tags kept answering every reader. Recorded-time reads (get_page and get_versions with known_as_of), plain get_versions with include_body, and delta's belief changes now also keep a quarantined page's bodies and claims from remote callers, including a page quarantined only by a later write and a version history that spans several sources. Nothing is deleted or expired, so restore_page brings every row back as it was. A new page written at a deleted page's slug still shows the deleted page's facts, and a purged page's facts still come back, as before; both are follow-up work.
+
+ ### Itemized changes
+
+ - `src/core/search/private-visibility.ts`: `privateFactFilterForCaller` and `privateEntityFilterForCaller` add the entity-page read gate to the provenance-page gate; recall, the entity card, contested claims, attribution, saved-fact matching, entity facts and the proactive brief use it.
+ - `src/core/eligibility/sql.ts`: `deletedPageProjectionHiddenSql` hides facts on or about a soft-deleted page, and that page's takes and timeline rows, in every projection read; fact list reads, ontology reads and the unattributed-facts review list apply it even without a read policy.
+ - `src/core/ops/tags.ts`: `get_tags` reads live pages only, for local callers too.
+ - `src/core/ops/get-page-projection.ts`, `admin.ts`, `known-as-of.ts`: `historyQuarantine` gives each stored version the quarantine view of its own page (quarantined now or in that version), so a remote caller gets no body for it.
+ - `src/core/belief/history.ts`, `changes.ts`: a quarantined page's fact and take events and fence claims stay out of a remote caller's belief history and delta.
+ - `src/core/persistence/page-prepare.ts`: a put over a soft-deleted page takes its tags from its own content and does not write the deleted page's database-only timeline rows into the new page's first version.
+ - Tests: `test/fact-reads-page-access.test.ts` (new), `test/recorded-read-gate.test.ts` (new cases 4 to 7), `test/get-tags-remote-privacy.test.ts`, on PGLite and Postgres.
+
+ ## [0.60.640.0] - 2026-11-10
+
+ **The skill resolver's hook lane is faster and safer at its 50 ms deadline, offers skills again after a Codex compaction, supports Pi and Cursor, and takes per-harness settings.** The hook starts its worker first and skips the CLI dispatcher, so the worker bundle drops from 172 KB to 62 KB and the lane's p90 drops from 58.9 ms to 38.1 ms on a 2-CPU machine (0 of 40 turns over 50 ms, was 7). A turn the deadline ends mid-commit now removes its session temp file and releases the session lease. The resolver stays off by default, lexical-only and fail-open.
+
+ ### Itemized changes
+
+ - Lane speed: the hook fast path (`src/core/skills/resolver/hook-lane.ts`, `hook-worker.ts`, `lane-worker.ts`) starts the worker before reading settings and never loads the CLI dispatcher. That hook process no longer prints the update heartbeat or the backup nag; `GBRAIN_HOOKS=0` and the CLI preflight still apply. A worker that exits before answering is logged as `skill_resolver_internal` at once instead of waiting out the deadline.
+ - Deadline: the session commit holds a release handle, so a deadline exit removes the temp file and the `.json.lock` lease it took.
+ - Codex compaction: `gbrain setup codex --skill-loading resolve` also writes a `SessionStart` hook (with its trust entry), and a `SessionStart` with `source: "compact"` resets the session's offered skills. An existing install gets the hook on its next setup run.
+ - Harnesses: `pi` and `cursor` join the path harnesses (each suggestion carries its SKILL.md path). The turn-input and build-receipt schemas list them.
+ - Resolve: `min_match_strength` (`--min-match`) drops weaker suggestions before the cut to `top_k`; exclude lists take up to 1,024 ids (`EXCLUDE_MAX`); `skill_catalog_mismatch` carries `catalog_hash`; a skill the turn names keeps its line after the budget is spent; with no catalog word in the message, `previous_user_message` is ranked instead. `RESOLVER_FEATURES` and `MATCH_STRENGTHS` are exported from `gbrain/skill-resolver`.
+ - Config: `skills.resolver.top_k`, `skills.resolver.min_match`, `skills.resolver.pinned` and `skills.resolver.per_harness.<harness>.{top_k,min_match}`, validated by `gbrain config set` (which refuses `per_harness.constructor`). With nothing set, Claude Code and Codex keep 5 suggestions and no floor.
+ - Logs: `skill-index/logs/lane-<UTC day>.jsonl` and `resolver-<UTC day>.log`, kept 14 days and capped at 2 MB a day; the old undated file is removed and doctor reads today and yesterday.
+ - Library bundle: `gbrain-skill-resolver.mjs` is built with whitespace minification, so the CLI build and the release build have one sha256 whatever the working directory.
+ - Bench: `scripts/bench-skill-resolver.ts` runs a discarded warm-up round, then judges the median of nine rounds of 100 cold turns; the bars stay 10 ms at 1,000 skills and 40 ms at 7,500.
+ - Tests: `test/skill-resolver-hook-lane.test.ts` (deadline stalls during the lease and after the temp write, Codex compaction, fast path), `test/skill-resolver.test.ts`, `test/skill-resolver-contract.test.ts`, `test/setup-skill-resolver.test.ts`, `test/skill-resolver-packaging.test.ts` (two-directory sha256), `test/skill-resolver-cli.test.ts` and `test/cli-fast-path.test.ts`.
+
+ ## [0.60.639.0] - 2026-11-10
+
+ **Access hardening: job results, write receipts, the status snapshot and graph edges stay inside the caller's grant; a forgotten fact stays forgotten; transcript redaction, `.env` handling and test databases are tighter.** An agent job, its result and its progress now answer only a caller acting for the same audience the job was submitted with, and write receipts follow the same rule. `get_status_snapshot` lists only the sources a remote caller's grant reads. Link reads, graph walks, entity cards and context packs leave out edges whose authoring page is deleted or, for a source-scoped caller, lives outside the caller's sources. A forgotten fact stays forgotten when the default visibility narrows or extraction runs again, while an explicit `remember` of the same claim still saves it. Transcript redaction also catches credentials assigned to names that end in a `key` word (`STRIPE_KEY=`), a `.env` file in the working directory can no longer set `GBRAIN_SURFACE`, the stale-editor-save check works on any Postgres encoding, and the throwaway test databases publish on loopback only.
+
+ ### Itemized changes
+
+ - Jobs: `jobActorSql` (`src/core/minions/types.ts`) matches the job's stored audience as well as its attested actor, so `get_agent_job`, `get_job`, `wait_job`, `get_job_progress`, `list_jobs` (both paging modes) and `cancel_job` answer only the audience the job was submitted for; a job with no audience answers only callers that name none.
+ - Write receipts: `sameAttestedActor` (`src/core/access/member-facts.ts`) compares a stored audience the same way, so `get_write_request`, `list_write_requests`, `cancel_write_request` and `request_id` replay stay with the audience the write was made for.
+ - `get_status_snapshot` (`src/core/ops/skills-catalog.ts`) confines its sources to the `sourceScopeOpts` ladder `sources_list` and `get_health` use; the local CLI keeps every source.
+ - Links (`src/core/engine-sql/links.ts`, `src/core/verbs/entity-card.ts`): every arm of `getLinks`/`getBacklinks`, traversal, `listLinkSources` and the entity card drop an edge whose origin page is soft-deleted, and, under a source grant, one whose origin page is outside it. For remote callers, `find_orphans` counts only links whose other endpoint and origin page are inside the caller's sources; the local operator's count stays brain-wide.
+ - Facts (`src/core/facts/withdrawal.ts`, `backstop.ts`, `fence-write.ts`, `src/core/persistence/facts-prepare.ts`, `facts-maintenance.ts`): every automatic admission path (extraction, the refused-window retry, the withdrawal retry and the moved-facts follow-up) checks the withdrawal ledger under the lock at any visibility, so narrowing `facts.default_visibility` or extracting again never brings a forgotten claim back. `remember` with `content-origin user_said` still saves it.
+ - Redaction (`src/core/secret-scan-assignment.ts`): the `high_entropy_assignment` key also accepts an identifier whose last word is `key` (`SUPABASE_SERVICE_ROLE_KEY=`, `deploy-key:`); `MONKEY=`, a bare `KEY=` and short or low-entropy values stay as written.
+ - `.env` (`src/core/env-trust.ts`): `GBRAIN_SURFACE` joins `CWD_DOTENV_PROTECTED_KEYS`. A shell export still sets the stdio surface; a repository's `.env` cannot widen it.
+ - Local-edit adoption (`src/core/persistence/local-edit-adoption.ts`): the stale-editor-save comparison trims and compares revisions in TypeScript, so it works on SQL_ASCII and LATIN1 databases. New doctor check `database_encoding` warns when a Postgres brain's `server_encoding` is not UTF8.
+ - Test databases: `docker-compose.ci.yml`, `docker-compose.test.yml` and every documented `docker run -p` publish on `127.0.0.1` only.
+ - Skills: `skills/conventions/untrusted-content.md` and the ingest skills describe the controls that ship (remote-read quoting in `transcript-quote.ts`, `TURN_CONTEXT_ENVELOPE`) and drop flag and fence names no code reads; text an agent ingests itself is stored at owner tier, unquoted.
+ - Tests: `test/access-on-behalf-of.test.ts`, `test/status-snapshot-source-scope.test.ts`, `test/link-origin-scope.test.ts`, `test/transcript-redaction-key-names.test.ts`, `test/env-trust.test.ts`, `test/test-db-loopback-ports.test.ts`, `test/adopt-local-edit.test.ts`, `test/doctor-database-encoding.test.ts`, `test/managed-sweep-refused-window-retry.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts`, `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/facts-entity-moved-7602.test.ts`, `test/untrusted-content-convention.test.ts` (PGLite and Postgres where an engine is involved).
+
+ ## [0.60.638.0] - 2026-11-10
+
+ **Atoms extracted from a world page never carry a fence row the page shows only to its owner, and `gbrain repair atom-fence-rows` finds and narrows atoms stored before.** A world page's facts table can hold rows marked `visibility: private`, and its takes table is never part of what a remote caller reads. Atom extraction, take proposals and the patterns phase read a page as a world reader sees it, so what they produce holds only world rows. Atoms an earlier version stored may still hold such a row: doctor `atom_fence_rows` counts them and names the read-only preview, and only `gbrain repair atom-fence-rows --apply --expect <hash>` makes the previewed atoms private. Nothing runs on upgrade.
+
+ ### Itemized changes
+
+ - `src/core/cycle/extract-atoms-input.ts`: a page's extraction input is its `publicBody` (facts rows other than world and the takes fence removed); the cap, the watermark and quote verification apply to that text, on the cycle phase and the managed path alike.
+ - `src/core/cycle/propose-takes.ts`: the extractor receives the page's `publicBody`, and a proposal that restates a take held by someone other than `world` is dropped before it is filed; the content hash, fence skip and dedup rows still read the stored body.
+ - `src/core/cycle/patterns.ts`: reflection excerpts in the subagent prompt and the quote-grounding sources are the reflection's `publicBody`.
+ - `src/core/repair/atom-fence-rows.ts` (new, registered in `repair/core.ts`, `repair/registry.ts`, `persistence/preview-approval.ts`): explicit-only, preview-bound kind; the preview lists each world atom with its source page and the row kinds and numbers it carries (never the row text) and changes nothing; the apply sets `visibility: private` on exactly the previewed set through a revision-bound put_page.
+ - `src/commands/doctor/checks/atom-fence-rows.ts` (new, a host-only `WAVE_CHECKS` entry, BRAIN category): `atom_fence_rows` warns with the count per source and the preview command.
+ - Docs: `docs/guides/repair.md#atom-fence-rows` (what is listed, the apply, cost), `skills/RESOLVER.md`, key-files rows in `core-cycle.md`, `hindsight.md`, `core-cycle-patterns.md` and `memory-purge.md`.
+ - Tests (PGLite and Postgres): `test/extract-atoms-world-fence-rows.test.ts` (cycle phase and managed brain: prompt, atoms and a remote read of each atom hold only world rows), `test/cycle-world-fence-rows.test.ts` (propose_takes input and proposals, patterns prompt and quote grounding), `test/repair-atom-fence-rows.test.ts` (doctor finding, preview changes nothing, apply without `--expect` refuses, apply narrows exactly the previewed atoms, unmanaged and managed).
+
+ ## [0.60.637.0] - 2026-11-10
+
+ **A file Git puts back after sync deleted its page brings the page back, and the retention purge never deletes a committed file.** On a managed brain, a commit that removed a Markdown file made sync soft-delete its page. When the same file came back (a `git revert`, switching to a branch and back, a collaborator's delete-then-restore, a file missing from disk for one working-tree sync), sync settled the path as "deleted, file unchanged" and left the page out of get, search and recall while `gbrain sync status` said synced. `gbrain pages purge-deleted --yes` then deleted the restored file from the checkout. Sync now tells a tombstone it made from a missing file apart from a person's delete and imports the file over it, so the same page comes back; a brain an older version left in that state heals on its next sync. The purge leaves a file committed at the source's last synced commit or at HEAD alone, unless a person's delete of the page never removed the file (for example because another page shared it). A page purge also stops leaving timeline text in the write journal.
+
+ ### Itemized changes
+
+ - `src/core/persistence/sync-pass.ts`, `sync-classify.ts`: the level read marks a tombstone a managed sync deletion made (its open `sync-delete-tombstone` record or uncompacted `managed_sync_delete` receipt); once its file is back with clean committed bytes it classifies `import` (the import revives the same page row), and a `file_drift` hold an older version raised over it re-runs. A person's tombstone keeps `deleted_same` / `deleted_edited`.
+ - `src/core/persistence/sync-pass-run.ts`: the selection fingerprint carries `sync_deleted_restore`, so the first sync after the upgrade reads the whole source once and brings back pages left deleted beside their file.
+ - `src/core/persistence/page-prepare.ts`, `sync-markers.ts`: a retention purge of a tombstone whose file is committed at the source's `last_commit` or HEAD removes no file: a sync-made tombstone defers (`revision_conflict`) to the sync that restores it; any other is purged database-only (`write_through.skipped: committed_file`), except a person's delete that made the tombstone and never removed its file (`write_through.written: false`, for example because another live page shared it), which still has the purge finish that removal. Publication re-checks, so a file committed while the purge was prepared is kept too. A sync-made tombstone defers only while its file is on disk; off disk (working-tree mode) it is purged database-only without a deletion marker, so the file's later return imports it. An unreadable checkout counts as committed; a checkout with no commit yet does not. Repo-less sources are unchanged.
+ - `src/core/persistence/page-purge.ts`: a page purge redacts the `entry` summary and source and the `bullet` text of the page's `add_timeline_entry` receipts, compacted ones included (up to 10,000 per page; past that `journal_sweep.complete` is false).
+ - Tests: `test/sync-restored-file-purge.test.ts` (PGLite and Postgres), `test/sync-classify-6712.test.ts`, `test/purge-eval-fixes.test.ts`.
+
+ ## [0.60.636.0] - 2026-11-10
+
+ **A fact or take no longer disappears when gbrain re-creates a `## Facts` or takes section that a page rewrite dropped.** When an agent rewrote a page without its facts or takes section, gbrain correctly kept those rows live until the user decided. But the next `remember`, `takes add`, fact extraction, `gbrain facts relink` or dream-cycle merge of a duplicate stub page into that page built a new section holding only its own row, and the write after that (a tag, a timeline entry, an append, or a get and put round trip) read the new section as the user's answer: the remembered facts expired and the takes were deleted, on repo-less and Git-backed brains alike. Those writers now render the held rows back into the section they create, so nothing is lost; a fact the user forgot, a take they removed, and rows retired by an explicit empty section stay withdrawn. `gbrain repair lost-fence-rows` previews the rows an older gbrain already lost this way and, after `--apply --expect <hash> --yes`, puts exactly those rows back from page history.
+
+ ### Itemized changes
+
+ - `src/core/facts/unfenced-facts.ts`: `heldFenceFactRows` lists the live rows a facts fence of the page held; `withHeldFactsFence` renders them into a new facts section when the page has none. Used by `remember` (`fence-fact-append.ts`), managed fact extraction (`persistence/facts-prepare.ts`, which also serves Google loops and the put backstop), `facts relink` (`relink-publish.ts`), unmanaged `writeFactsToFence` (`fence-write.ts`), cycle fact adoption (`planFence`) and the dream cycle's phantom redirect (`cycle/phantom-redirect.ts`, `cycle/phantom-redirect-managed.ts`).
+ - `src/core/persistence/takes-prepare.ts`: `heldTakeRows` reads the stored takes while the take fence is held `fence_absent`; a takes write that creates the fence renders them first (covers `takes add`, `takes propose --accept` and consolidation).
+ - `src/core/repair/lost-fence-rows.ts`: new explicit-only, preview-bound repair kind `lost-fence-rows`, registered in `repair/core.ts` and `repair/registry.ts`; `persistence/preview-approval.ts` accepts its approvals.
+ - Docs: `docs/guides/repair.md#lost-fence-rows`.
+ - Tests: `test/fence-absent-append-keeps-rows.test.ts` (remember, takes add, managed extraction and relink, each followed by a tag, timeline entry, append or round trip; forget, takes remove and an empty section stay withdrawn; a managed phantom redirect into the page keeps the held fact; repo-less and Git), `test/repair-lost-fence-rows.test.ts` (preview writes nothing, apply restores exactly the listed rows, deliberate removals and empty sections are not listed, a changed page is skipped).
+
+ ## [0.60.635.0] - 2026-11-10
+
+ **A connected agent can no longer change, or learn about, a page it is not allowed to read.** A remote write token that could not read a `visibility: private` page could still overwrite that page's stored raw data, add links to or from it and remove its links, and `extract_entities` would link new entity stubs to a source page the caller could not read, or add a timeline line to an existing person page it could not read. Each of those answers also differed from the answer for a page that does not exist, so a caller could tell which hidden pages exist. They now answer exactly as for a missing page and change nothing. `ontology_propose` refuses an entity page its caller cannot read and stores an observation no wider than that page. `get_ingest_log` no longer names pages its remote caller cannot read or the host's checkout path, and `get_health` no longer lists such a page among the most connected. An MCP read that names a source or filter parameter with a slip (`source` for `source_id`, `type` for `types`) now gets an error naming the right parameter instead of an answer drawn from every source the token can read. `gbrain serve --http` now applies the `/mcp` rate limits and body cap when `GBRAIN_HTTP_RATE_LIMIT_IP`, `GBRAIN_HTTP_RATE_LIMIT_TOKEN` or `GBRAIN_HTTP_MAX_BODY_BYTES` is set; before, only the legacy transport read them. Trusted local CLI calls are unchanged.
+
+ ### Itemized changes
+
+ - `src/core/persistence/page-visibility.ts`: `remoteTargetHidden` tests the caller's whole read policy (member access, then privacy with its grant and hatch), the policy `get_page` applies, instead of the member-access part alone; `remotePageAccess` and `remoteReadPolicySql` give the same test to a batch of slugs. `requireWritablePage` (so `put_raw_data`, `add_link` on either endpoint and the managed `add_timeline_entry` preflight) and `remove_link` use it; a delegated subagent write keeps its own privacy refusal.
+ - `src/core/ops/extraction.ts`, `src/core/enrichment-service.ts`, `src/core/trust/taint.ts`: `extract_entities` treats a source page its remote caller cannot read as missing (no backlink, no trust read from it), skips an entity whose page the caller cannot read (`skipped_reason: page_not_found`, under the slug its name maps to, nothing written) and carries on with the rest of the batch, follows a retired entity page's redirect only through pages the caller can read, and counts mentions only on pages the caller can read.
+ - `src/core/ops/chronicle.ts`: `ontology_propose` from a remote caller requires a readable entity page when one exists (a hidden one answers like `put_page`'s create on it) and tightens the observation's visibility to that page, as `remember` and `extract_facts` do.
+ - `src/core/ops/ingest-log.ts`: for remote callers, `get_ingest_log` shows a row only when every page it names (in `pages_updated`, or in `source_ref` for rows that name one page there) is a live page the caller can read, and shows `source_ref` without host paths (a sync row keeps only its commit, an import row reads `<local path>`).
+ - `src/core/ops/admin.ts`: `get_health`'s `most_connected` lists, for a remote caller, only pages its `get_page` would show.
+ - `src/mcp/validate-params.ts`, `src/mcp/dispatch.ts`: `narrowingUnknownParams`; a read rejects an unknown scope or filter parameter in warn mode too (`mcp.strict_params` keeps its default), and `source`, `sourceId`, `sources` and `sourceIds` suggest `source_id` / `source_ids`.
+ - `src/commands/serve-http-mcp.ts`: POST `/mcp` runs the IP bucket before the token lookup and the token bucket after it, each only while its env var is set, and passes `GBRAIN_HTTP_MAX_BODY_BYTES` (default the SDK's 4 MiB) to the transport; a value that is not a positive whole number is ignored with a warning. `SECURITY.md`, `docs/guides/memory-boundaries.md`, `docs/guides/remote-mcp.md` state the real defaults.
+ - Tests: `test/access-hidden-page-writes.test.ts` (PGLite and Postgres; repo-less and managed), `test/serve-http-mcp-limits.test.ts` (a live server), `test/validate-params.test.ts`.
+ - Also in this release (#9060): the chronicle long-conversation tests no longer fail when they run across midnight UTC, and the architecture file index describes the chronicle judged-input digest and the duplicate-events doctor check.
+
+ ## [0.60.634.0] - 2026-11-09
+
+ **Privacy, trust and access checks written in SQL now give the same answer as their TypeScript versions, so remote callers can't see a page through one path that another path hides.** Several rules are evaluated twice: once in TypeScript on a page already read, and once in SQL for list, search, backlink and scan queries. Postgres `btrim(x)` strips only spaces, while JavaScript's `trim()` strips every Unicode edge whitespace character, and Postgres `lower()` follows the database collation. A page marked private through the `access` or `confidentiality` field, with other whitespace around the value (a YAML block scalar keeps a trailing newline), was hidden from remote `get_page` but not from remote list and search. The fast page filters also skipped the full check for `type: question` pages and pages with a `pinned_question` key, which the full check treats as private.
+
+ ### Itemized changes
+
+ - `src/core/edge-whitespace.ts` (new): `EDGE_WHITESPACE`, exactly what JavaScript's `trim()` strips, `edgeTrimSql()`, and an ASCII-only lowercase for TypeScript and SQL. The generated SQL is plain ASCII, so it also runs on a Postgres database whose encoding is not UTF8; there the SQL side trims ASCII whitespace only.
+ - `src/core/search/private-visibility.ts`: `privacyAliasSql` trims and lowercases like the row-side check; `privatePagesFilterFragmentFast` and the caller fast path send question and `pinned_question` pages to the full check.
+ - `src/core/persistence/git-declared.ts`: `privacyClass` runs the lineage check for question pages too, so a question page built from a private input stays out of Git, as remote reads already hide it.
+ - `src/core/trust/channel.ts`, `src/core/trust/backfill.ts`: the frontmatter trust caps and the backfill's extractor marker trim the same whitespace as the TypeScript caps; the transcript-harness cap lowercases ASCII on both sides.
+ - `src/core/access/caller.ts` (local stdio member binding), `src/core/persistence/unbound-pages.ts` (database-only pages), `src/core/persistence/effect-journal.ts` (the `auto_link` / `mcp.remote_auto_links` gate), `src/core/repair/private-labels.ts` and `src/core/persistence/local-edit-adoption.ts` use the shared set.
+ - Behaviour: a page whose alias value carries such whitespace, or a question or pinned-question page without `visibility`, is now hidden from remote list, search and backlink reads as well as from `get_page`. Doctor and repair counts that use these checks may move to match. Nothing rewrites stored pages.
+ - Tests: `test/edge-whitespace-twins.test.ts` (PGLite and Postgres) holds each SQL check equal to its TypeScript side on generated inputs and checks remote list and search; `test/trust-claim.test.ts`, `test/trust-backfill.test.ts` and `test/remote-graph-freshness.test.ts` gain edge-whitespace cases.
+
+ ## [0.60.633.0] - 2026-11-09
+
+ ### Added
+
+ - `gbrain skills index build|status|remove` and `gbrain skills resolve`: an engine-free skill resolver that ranks a harness's skill catalog against one user turn and prints a short `<relevant_skills>` block (at most 5 suggestions, at most 400 tokens), so an agent with hundreds of skills sees the few that fit. Off by default; nothing changes until you build a catalog and call it. Works with no brain, on thin clients and while `gbrain serve` holds the PGLite lock. Word matching only (the BM25F ranker frozen by the Step 1 offline eval); nothing leaves the machine. Sessions never repeat a suggestion and share a 2,000-token budget (`skills.resolver.session_token_budget`). JSON contract in `docs/schemas/skill-resolver.v1.*.json`; library as `gbrain/skill-resolver` and, for Node, one dependency-free module built from the same source: `gbrain skills library` writes it to `GBRAIN_HOME/lib/gbrain-skill-resolver.mjs` and prints its sha256, and each release attaches `gbrain-skill-resolver.mjs` with a `.sha256`. Each suggestion carries `match_strength` (`named`, `name`, `triggers`, `routing`, `description` or `body`) so an adapter can drop weak matches. Guide: `docs/guides/skill-resolver.md`.
+ - `gbrain setup claude-code|codex --skill-loading resolve`: a per-turn hook lane (`GBRAIN_HOOK_LANE=skill-resolver`) that adds the resolver's block to every prompt, with the harness's own load line. Setup builds the user catalog first and writes the `skills.resolver.*` keys and the hook only when it found at least one skill (`skill_resolver_setup_incomplete` otherwise); `--skill-loading off` and `setup --remove` undo all of it. The lane runs in the hook process with no brain and no serve, exits within 50 ms with nothing printed when it cannot deliver, drops a block over `skills.resolver.lane_payload_chars` whole, and lets exactly one wiring deliver. Claude Code project skills get their own catalog, built in the background. `gbrain doctor` reports it as `skill_resolver`. Off by default; with it off, hook output and setup's files are unchanged. A `config.json` that holds only `skills.resolver` settings no longer reads as a Postgres brain. Release binaries are now built with the lane's worker as a second entrypoint.
+
+ ## [0.60.632.0] - 2026-11-09
+
+ **A page write that git could not commit because the file is flagged assume-unchanged or skip-worktree now stays in the write-through pending ledger.** gbrain's own page writes and `gbrain git commit-push --pending` asked `git status` which pending files were still uncommitted, and status does not show a flagged entry, so the write was left uncommitted, dropped from the ledger (doctor `dirty_age` never reported it and no later write retried it), and `--pending` answered `nothing_to_commit` with exit 0. A flagged file whose bytes differ from HEAD now counts as uncommitted.
+
+ | Situation | Before | After |
+ | --- | --- | --- |
+ | A page write to a flagged file | not committed, not in the ledger | not committed, kept in the ledger (the write itself fails `commit_paths_skipped`, as in 0.60.630.0); doctor reports it as `dirty_age` after 30 minutes |
+ | A later page write while a flagged file is in the ledger | the entry was settled away | the entry is committed beside the new write when git picks it up, and otherwise stays |
+ | `gbrain git commit-push --pending` with a flagged pending file | `nothing_to_commit`, exit 0 | `commit_paths_skipped` naming the file, exit 1; the ledger keeps it |
+ | A page write or `gbrain git commit-push` naming a modified skip-worktree file that is on disk | `git add` refused it: `commit_paths_invalid`, nothing committed, and a page write dropped the file from the ledger | the other paths are committed; the file is reported as skipped (`commit_paths_skipped`, reason `skip_worktree`, exit 1 from `commit-push`) and a page write keeps it in the ledger |
+
+ ### Itemized changes
+
+ - `src/core/git/commit-push.ts`: the pending-ledger check (`dirtyPaths`, used by the write-through commit, `--pending`, ledger settling and doctor `dirty_age`) also counts flagged entries whose bytes differ from HEAD, using the same check as the GST-2116 skipped-path detection (`flaggedChanges`), where an entry git cannot hash counts as changed instead of failing the check and a flagged gitlink is left out; `commitPaths` no longer hands `git add` a named skip-worktree file that is on disk (git refuses it and failed every named path), and reports it as skipped; the write-through commit notes its own flagged files that git left out in the ledger, and ledger settling keeps every entry when the check fails.
+ - Docs: `docs/guides/shared-checkout-git.md` (pending write-through section).
+ - Tests: `test/pending-ledger-flagged-gst2118.test.ts` (real git and the real CLI: a flagged write-through file stays in the ledger and doctor's dirty check sees it, a later write commits an older flagged entry instead of settling it away, `--pending` on a flagged file fails and keeps the entry, and a flagged entry git cannot hash is kept while a later write still commits, a write to a named skip-worktree file beside another page commits the other page and keeps the file for `--pending` to report, and an ordinary pending file as the control). Five of its six cases fail without the fix; the control passes.
+
+ ## [0.60.631.0] - 2026-11-09
+
+ **A long conversation that keeps growing is no longer re-extracted, and re-paid for, on every new message.** Automatic event extraction reads a page's title, date, attendees and the first 12,000 characters of its body. On a conversation longer than that, each new message recorded a new revision, and each revision paid for another extraction call on exactly the same text. The model words each event a little differently every time, event pages are named after that wording, and an extraction of a page longer than 12,000 characters never retired the previous one, so every run added a fresh copy of every event. One page could collect dozens of paid calls and hundreds of duplicate events. Now a revision that changes nothing extraction reads (text, title, date, attendees, privacy) makes no call and writes nothing (it records `judge_input_unchanged`); a window the judge keeps failing on (its answer cut off, unreadable, malformed or over the per-page spend cap) is paid for at most the page's attempt limit across all revisions, retries included, then records `judge_input_failed` until the text changes, a release changes the extractor, or a backfill asks again (a run a newer revision replaced, or a missing provider or price, never counts toward that limit); and a re-extraction that re-read all the text the page's live events came from (for example after a title change, or the first time a conversation grows past 12,000 characters) replaces those events instead of adding to them. An extraction that dropped proposals over `chronicle.max_events_per_page` is asked again when that setting or the timezone changes, and one that dropped proposals dated after the page's last day is asked again, once, when that day moves. A page whose opening text was edited still keeps its earlier events, as before. Text past the first 12,000 characters is still not extracted; incremental coverage of the tail is tracked in #9013. Reported by @andreineacsu.
+
+ **Doctor counts the duplicates earlier releases left.** The new `chronicle_duplicate_events` check (info) reports how many pages hold live events from earlier extraction runs beside their newest run's, and how many such events. It changes nothing; a preview-first repair that retires them is tracked in #9012.
+
+ ### Itemized changes
+
+ - `src/core/chronicle/execute.ts`: before the daily reservation, a row whose judge input digest equals that of the page's latest decided extracted generation (no ineligible revision or chronicle retirement since) finishes `skipped` / `judge_input_unchanged` with no call; an automatic row whose input already used the attempt limit without publishing finishes `failed` / `judge_input_failed` (a refused input stays `judge_refused`), with no call, summing `judge_input_failures` over every row of the page with that digest, the current revision's retries included (only a `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `budget_exhausted` or `judge_refused` attempt increments it); a truncated generation replaces the previous one only when every live chronicle event of the page is recorded by a ledger row whose judged window the new window starts with. Ended-invite projections and held results never count as judged, and each finish that judged writes the judged input outright, so a held retry clears what a failed attempt recorded (a row a newer revision replaced before its retry keeps it); a generation that dropped future-dated proposals records `cutoffInputHash` (the digest keyed to the screen's cutoff day).
+ - `src/core/chronicle/extract-events.ts`: `chronicleJudgedInput` (digest of the judge input with the body cut to `JUDGE_BODY_CHARS`, the extractor version, the depth page's visibility and source incarnation, the timezone and `chronicle.max_events_per_page`; the window and its sha256) and `cutoffInputHash`.
+ - Migration `v297` `chronicle_judge_window`: `chronicle_page_state.judge_input_hash`, `judge_window_chars`, `judge_window_hash` (nullable) and `judge_input_failures` (`NOT NULL DEFAULT 0`); no backfill, so existing rows start at no judged input and zero counted failures. A row recorded before it has no window, so that page's next revision is judged once more and stays additive.
+ - `src/core/chronicle/reasons.ts`, `src/core/error-registry.ts`: reason codes `judge_input_unchanged` and `judge_input_failed`.
+ - `src/core/chronicle/ledger-stats.ts`, `src/commands/doctor/checks/auto-chronicle.ts`: `readChronicleDuplicateEvents` and the `chronicle_duplicate_events` doctor check.
+ - Docs: `docs/guides/life-chronicle.md`, `docs/guides/error-codes.md`.
+ - Tests: `test/chronicle-long-conversation-8972.test.ts` with its Postgres arm `test/e2e/chronicle-long-conversation-8972-postgres.test.ts`; schema, migration and doctor goldens regenerated for the new columns and check.
+
+ ## [0.60.630.0] - 2026-11-09
+
+ **`gbrain git commit-push` and `scripts/brain-commit-push.sh` no longer report success when git left a named path uncommitted.** `git add` stages nothing and still exits 0 for a modified file flagged assume-unchanged or skip-worktree and for a file inside a nested Git repository, so the helper answered "nothing to commit" (or pushed the other paths) with exit 0, and the write sat uncommitted with nothing in any log. Now the other named paths are still committed (and, on a classic checkout, pushed), and the run exits 1 naming each skipped path and its reason: `writer_coordinator_required` for a page in a managed canonical worktree, which belongs to the persistence owner (save it through `put_page`), and the new `commit_paths_skipped` for anything else. The helper's own managed-checkout refusal now prints the operator contract (code, why, fix, next) instead of one line.
+
+ | Situation | Before | After |
+ | --- | --- | --- |
+ | A named file is flagged assume-unchanged (or skip-worktree under a named directory) and modified | `nothing to commit`, exit 0; the edit stays uncommitted | `commit_paths_skipped` (reason `assume_unchanged` / `skip_worktree`), exit 1; fix (ask the user): `git update-index --no-assume-unchanged -- <paths>`, and a separate `git update-index --no-skip-worktree -- <paths>` (given both flags, git clears only the first) |
+ | A named file sits inside an untracked nested repository | exit 0 with nothing committed; beside other paths, `git_unavailable` and nothing committed | the other paths are committed, then `commit_paths_skipped` (reason `not_staged`), exit 1 |
+ | The same on a managed canonical worktree, for a page | `nothing to commit; not pushed`, exit 0 | `writer_coordinator_required`, exit 1, naming each page; fix (ask the user): save it through `put_page` with the managed source (`gbrain put --source-id <source> <slug>`, `source_id` over MCP) |
+ | The push fails after a path was skipped | the push error alone | `commit_paths_skipped` still names each skipped path, with the push error beside it, exit 1 (the CLI; the helper without gbrain exits 4) |
+ | A gbrain write-through commit (`commitPathsLocked`) that git leaves a named path out of | the commit returned as saved | `commit_paths_skipped` after the rest is committed |
+ | `scripts/brain-commit-push.sh` without gbrain on the machine | `nothing to commit`, push, exit 0 | the push still runs, then `Error [commit_paths_skipped]` with each path, exit 1 |
+ | `scripts/brain-commit-push.sh` on a checkout marked managed | one line, `writer_coordinator_required: submit managed changes through persistence`, exit 1 | `Error [writer_coordinator_required]` with `Why:`, `Fix:` (put_page; `gbrain git commit-push` for files that are not pages) and `Next: ask_user`, exit 1 |
+
+ A skip-worktree file absent from disk (a sparse checkout), a flagged gitlink (its commit lives in the nested repository) and ignored files under a named directory are not reported; a named ignored file was already refused by `git add` (`commit_paths_invalid`). Existing brains get the new helper on the next `gbrain sources harden`.
+
+ ### Itemized changes
+
+ - `src/core/git/commit-push.ts`: after the commit step, `commitPaths` reads which named paths HEAD still lacks (flagged entries whose bytes on disk differ from HEAD, named files git did not index, and status entries with unstaged changes) and leaves an unindexed file out of `commit --only`, so it no longer fails the other paths. The check runs after the commit's index-restore block, so a failure there never stages a reversal of a commit that already landed. The managed `put_page` fix carries the managed source in its CLI argv and MCP arguments, so following it cannot write a same-slug page in another source. `commitAndPush` (classic, managed and remoteless) throws `commit_paths_skipped` or, for a page in a managed worktree, `writer_coordinator_required`, after committing and publishing the rest; `detail` carries the skipped paths, the commit and the pushed head.
+ - `src/core/brain-repo-durability.ts`: the rendered `scripts/brain-commit-push.sh` prints the operator contract on its managed refusal, and its fallback (no gbrain) runs the same check after its commit (NUL-separated listings, so a non-ASCII or quoted name is read exactly; a symlink is compared by its link text), leaves a file git did not index out of `commit --only`, and exits 1 with `commit_paths_skipped` after the push.
+ - `src/commands/git.ts`: when the run fails after the other paths were pushed, the push log still records that push.
+ - `src/core/error-registry.ts`: new code `commit_paths_skipped` (reasons `assume_unchanged`, `skip_worktree`, `not_staged`).
+ - Docs: `docs/guides/shared-checkout-git.md` (the `commit_paths_skipped` row, the `writer_coordinator_required` row, the fallback paragraph), `docs/guides/error-codes.md` (regenerated).
+ - Tests: `test/git-commit-push-skipped-paths-gst2116.test.ts` (the real CLI and the rendered helper against temp repositories, a bare remote and a managed-root registry: an assume-unchanged page, a nested-repository page beside a committable one, a skip-worktree entry under a named directory, a managed page and a managed non-page file, a remoteless checkout, a named directory inside a nested repository, a run with both flags, the helper's fallback (a non-ASCII path, a nested-repository file beside a committable page, a clean flagged symlink), the helper handing over to gbrain on a managed root, its managed refusal; a named directory beside a sparse entry and an ignored draft still commits with exit 0). Also: the write-through door, a push that fails after a skipped path (CLI and helper), a named assume-unchanged gitlink beside a committed page (the commit stands and no reversal is staged), and the managed fix's source. Sixteen of its eighteen cases fail on master; the two that pass there are the sparse-entry control and the gitlink case, which guards this change's own post-commit path.
+
+ ## [0.60.629.0] - 2026-11-09
+
+ **`gbrain repair file-drift` now agrees with sync on a held origin-twin page.** A legacy page left as an origin twin with no recorded file (no import record) could be held `file_drift` by sync while `repair file-drift --slug <slug>` reported `no_drift`. The hold's own suggested fix couldn't clear it, and scripts that use the preview as a drift check passed falsely. The preview now reads such a twin against its slug-path file, the same way sync imports it, and lists it with an apply command.
+
+ ### Itemized changes
+
+ - `src/core/persistence/drift-conflicts.ts`: `liveFileDrift` reads an adoptable origin twin with no recorded file against its slug-path file. A twin in a read-only mirror source, whose slug path no file can import as, whose slug-path file sync doesn't admit (outside its scope or under `sync.exclude`), or whose slug-path file another page records as its source path keeps `database_only`. A slug path several files import as keeps the earlier reading instead of reporting `slug_path_ambiguous`. A twin under a declared db_only path, which sync holds but no repair can adopt, reads `unknown` (`db_only_slug_path`) instead of passing as `no_drift`, and so does a slug-path file another page names only by file URI (`shared_origin`), since sync still imports it into the twin.
+ - `src/core/persistence/reconcile-state.ts`: the slug-path adoption check moves into one exported `adoptableSlugOrigin`, which reconcile and the drift preview now share. Reconcile's behaviour is unchanged.
+ - Applying either side to such a twin binds the slug-path file as its `source_path` and clears `origin_twin`. Maintenance writes to a twin whose slug-path file differs are now refused as drift, like any drifted page.
+ - Tests: `test/repair-file-drift-origin-twin-gbra108.test.ts` (PGLite, managed source, real git): a legacy page with no import record held by sync, previewed and applied for both `--prefer database` and `--prefer file`, after which a re-sync clears the hold; also mirror-read-only, db_only, non-importable slug path, missing file, shared-origin, excluded slug path, URI-only claimant and ambiguous slug path cases.
+
+ ## [0.60.628.0] - 2026-11-09
+
+ **A page a member-bound credential creates in a federated source is now readable only by that member.** A token or OAuth client bound to a member (`gbrain auth rescope --member <id>`) and granted `--sources <id>` for a federated source wrote its pages there with no readers. Every credential without a source grant reads `default` plus every federated source, so another member's no-grant token and an unbound token read those pages over `get_page`, `search`, `query`, `recall` and `list_pages`. Such a page is now written with `readable_by: [member:<id>]`, as a page the credential writes to `default` already was, and `POST /ingest` refuses the credential. A write source that is not federated keeps the audience its grants give it. Pages written before the upgrade keep their readers, and `gbrain access who-can-read <slug>` shows who reads one.
+
+ ### Itemized changes
+
+ - `src/core/source-resolver.ts`: `noGrantFloorReads` says whether a caller with no source grant reads a source unqualified: `default`, or a source in the federated set `noGrantFederatedScope` threads for that floor. It throws when the sources cannot be read.
+ - `src/core/persistence/page-visibility.ts`: `defaultSourceMemberWriter` keys on `noGrantFloorReads` instead of the literal `default`, so a member-bound write to a federated source is stamped too. A source table it cannot read refuses the write instead of publishing the page shared.
+ - `src/commands/serve-http-webhooks.ts`: the `POST /ingest` refusal names the credential's write source.
+ - Docs: `docs/guides/multi-source-brains.md`, `docs/tutorials/company-brain.md` (Model C), `docs/mcp/ADMIN.md`.
+ - Tests: `test/access-federated-member-writes.test.ts` (PGLite, and Postgres with `DATABASE_URL`): a member-bound token or OAuth client granted a federated source creates a page that another member and an unbound token, reading the federated set as the HTTP transports do, cannot read; with `default` isolated the floor is `default` alone and nothing is stamped; a streamed upload over the 24 MiB ceiling is kept to its member too; a write whose source config cannot be read is refused, not published unstamped; a non-federated source stays unstamped and out of unbound reads; a member-bound write cannot leave its granted source; `POST /ingest` refuses with nothing queued.
+
## [0.60.627.0] - 2026-11-09
**A webhook capture can no longer drop a page's readers (GST-2112).** `POST /ingest` wrote through a trusted local path whose only check was that the sender could read the page, so a member-bound token granted a source could replace a page whose `readable_by` named it with a body that named no readers, and every caller could then read the page. The route and the `ingest_capture` job now apply the remote `put_page` readers rule: a body that drops `readable_by` from a page that names readers, or names readers that leave out the sender, is refused `readable_by_invalid` (403 at the route, nothing queued; at write time for a job already queued). The job binds its write to the revision it checked, so readers added between the check and the write refuse the write with `revision_conflict` and the retry refuses `readable_by_invalid`. A capture already queued from a member-bound credential whose write source is `default` is refused `permission_denied` at write time, as the route refuses it before queueing. Bodies that keep the readers, and pages without readers, import as before.
diff --cc src/core/retry-matcher.ts
index 41ee72f347,a11e63b3c5..dde17b153f
--- a/src/core/retry-matcher.ts
+++ b/src/core/retry-matcher.ts
@@@ -112,31 -124,6 +124,20 @@@ export function isStatementTimeoutError
return /statement_timeout|canceling statement due to statement timeout/i.test(msg);
}
- /**
- * GST-2260: SQLSTATE 0A000 from RevalidateCachedQuery, "cached plan must not change result type": another session
- * changed a column of a table a prepared statement reads, so its cached result type no longer holds. The vendored
- * driver re-prepares every connection's statements after the first one, so the statement succeeds when it runs again;
- * inside a transaction that means re-running the whole transaction, which this error has already rolled back. Matched
- * on the routine, never the code alone: other 0A000 errors (an unsupported feature) are permanent.
- */
- export function isStalePlanError(err: unknown): boolean {
- return getCode(err) === '0A000' && (err as { routine?: unknown } | null)?.routine === 'RevalidateCachedQuery';
- }
-
+/**
+ * GST-2260: runs `transaction` once more when a stale plan aborted it. The abort rolled back every statement it ran, so
+ * the second run is safe only for a callback that does nothing but database work and in-memory computation: never wrap
+ * one that writes a file, calls the network or changes state that outlives the transaction.
+ */
+export async function retryOnStalePlan<T>(transaction: () => Promise<T>): Promise<T> {
+ try {
+ return await transaction();
+ } catch (error) {
+ if (!isStalePlanError(error)) throw error;
+ return transaction();
+ }
+}
+
/**
* SQLSTATE 55P03: lock_not_available.
* Postgres signals this when `lock_timeout` or `NOWAIT` would block.
diff --cc test/postgres-unit-arms.txt
index d42b6c3e3b,490bedc708..40d43565f1
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@@ -522,8 -537,8 +537,9 @@@ test/source-lifecycle-dry-run-physical-
test/source-retire-missing-checkout.test.ts
test/source-row-diagnostics.test.ts
test/sources-resolve-path.test.ts
+test/stale-plan-heal.test.ts
test/stats-health-source-scope.test.ts
+ test/status-snapshot-source-scope.test.ts
test/sync-absent-from-worktree-s27.test.ts
test/sync-admission-6712.test.ts
test/sync-apply-held-deletions-gbra133.test.ts
diff --cc test/stale-plan-heal.test.ts
index 6e1fde45bc,0000000000..b4ac6bcf2d
mode 100644,000000..100644
--- a/test/stale-plan-heal.test.ts
+++ b/test/stale-plan-heal.test.ts
@@@ -1,272 -1,0 +1,264 @@@
+/**
+ * GST-2260: a prepared `SELECT *` or `RETURNING *` goes stale when another process adds, renames or drops a column on
+ * its table, and Postgres answers its next execute with SQLSTATE 0A000 "cached plan must not change result type"
+ * (routine RevalidateCachedQuery). The vendored driver re-prepares and retries such a statement, which heals it outside
+ * a transaction; inside one the 0A000 has already aborted the transaction, so the caller saw it, once per statement shape
+ * per pooled connection (a `gbrain serve` refusing writes after `apply-migrations` ran in another process).
+ * 1. Protects: the first such error heals every pooled connection of the process, and the write paths that re-run an
+ * aborted transaction (retryWriteAdmission, the coordinator's transient classifier) re-run it, so a put_page after
+ * the migration succeeds with no caller-visible error.
+ * 2. Fails when: the error is not retried by the admission loop, or another pooled connection still holds its stale
+ * statement after the first one healed.
+ * 3. Existing coverage: none; test/access-ungranted-member-writes.test.ts flaked on it (a RENAME COLUMN and back).
+ * The two pure-database transactions outside those loops that a long-running process meets first (an OAuth token
+ * grant, a minion job's completion) run once more instead of failing a token request or a job that already ran.
+ * 4. Real seams: real Postgres, DDL from a second client, the engine's transaction and executeRaw, MCP dispatch, the
+ * OAuth provider and the minion queue.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import net from 'node:net';
+import type { AddressInfo } from 'node:net';
+import postgres from '#postgres';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
- import { retryWriteAdmission, STALE_PLAN_RETRIES } from '../src/core/persistence/admission-retry.ts';
++import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';
+import { transientDatabaseFailure } from '../src/core/persistence/coordinator.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { hashToken } from '../src/core/utils.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const url = process.env.DATABASE_URL;
+const caught = (p: Promise<unknown>) => p.then(() => null, (e: { code?: string; routine?: string }) => e);
+const outcomes = (settled: PromiseSettledResult<unknown>[]) => settled.map(s => s.status === 'fulfilled' ? 'ok' : (s.reason as { code?: string }).code);
+
+/** Each change alters the result type of `SELECT *` on the table; `step` counts the changes already made to it. */
+const CHANGES = [
+ ['ADD COLUMN', (t: string) => `ALTER TABLE ${t} ADD COLUMN added_${randomUUID().slice(0, 8)} text`],
+ ['RENAME COLUMN', (t: string, step: number) => step % 2 ? `ALTER TABLE ${t} RENAME COLUMN note_alt TO note` : `ALTER TABLE ${t} RENAME COLUMN note TO note_alt`],
+ ['DROP COLUMN', (t: string, step: number) => `ALTER TABLE ${t} DROP COLUMN ${step ? 'note' : 'spare'}`],
+] as const;
+
+describe('write admission and a stale plan that keeps coming back (GST-2260)', () => {
- test('it is re-run a bounded number of times and then rethrown as it was, never reported as contention', async () => {
- const stalePlan = Object.assign(new Error('cached plan must not change result type'), { code: '0A000', routine: 'RevalidateCachedQuery' });
- let attempts = 0;
- const thrown = await caught(retryWriteAdmission(randomUUID(), async () => { attempts++; throw stalePlan; }, 5000));
- expect(thrown).toBe(stalePlan);
- expect(attempts).toBe(STALE_PLAN_RETRIES + 1);
- });
-
+ test('another 0A000 is not a stale plan and is not retried', async () => {
+ const unsupported = Object.assign(new Error('FOR SHARE is not allowed with aggregate functions'), { code: '0A000', routine: 'CheckSelectLocking' });
+ let attempts = 0;
+ expect(await caught(retryWriteAdmission(randomUUID(), async () => { attempts++; throw unsupported; }, 5000))).toBe(unsupported);
+ expect(attempts).toBe(1);
+ });
+});
+
+describe.skipIf(!url)('a prepared SELECT * after another connection changes its table (GST-2260)', () => {
+ let admin: ReturnType<typeof postgres>;
+ const engines: PostgresEngine[] = [];
+ beforeAll(async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ admin = postgres(url!, { max: 1, prepare: false, onnotice: () => {} });
+ });
+ afterAll(async () => {
+ for (const engine of engines) await engine.disconnect().catch(() => {});
+ await admin.end({ timeout: 1 });
+ });
+
+ async function setup(poolSize: number, change: (t: string, step: number) => string) {
+ const table = 'stale_plan_' + randomUUID().replace(/-/g, '').slice(0, 12);
+ await admin.unsafe(`CREATE TABLE ${table} (id int PRIMARY KEY, scopes text[], note text, spare text); INSERT INTO ${table} VALUES (1, '{read}', 'n', 's')`);
+ const engine = new PostgresEngine();
+ engines.push(engine);
+ await engine.connect({ database_url: url!, poolSize });
+ const select = `SELECT * FROM ${table} WHERE id=$1 FOR SHARE`;
+ let step = 0;
+ return {
+ engine, select,
+ inTx: () => engine.transaction(tx => tx.executeRaw<{ id: number }>(select, [1])),
+ alter: () => admin.unsafe(change(table, step++)),
+ };
+ }
+
+ /** Prepares the statement on every pooled connection: `n` transactions hold their connections at once. */
+ async function primeEvery(engine: PostgresEngine, select: string, n: number) {
+ let arrived = 0;
+ let open!: () => void;
+ const barrier = new Promise<void>(resolve => { open = resolve; });
+ await Promise.all(Array.from({ length: n }, () => engine.transaction(async tx => {
+ await tx.executeRaw(select, [1]);
+ if (++arrived === n) open();
+ await barrier;
+ })));
+ }
+
+ test('a prepare: false pool (what a transaction-mode pooler URL gets) sends unnamed statements and is unchanged', async () => {
+ const { select, alter, inTx: preparedInTx } = await setup(1, CHANGES[0][1]);
+ const unnamed = postgres(url!, { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ const inTx = () => unnamed.begin(tx => tx.unsafe(select, [1]));
+ expect((await preparedInTx())[0]!.id).toBe(1);
+ for (let i = 0; i < 2; i++) {
+ expect(Array.from(await inTx() as Iterable<{ id: number }>)[0]!.id).toBe(1);
+ await alter();
+ }
+ expect(await caught(preparedInTx())).toMatchObject({ code: '0A000' });
+ expect(Array.from(await inTx() as Iterable<{ id: number }>)[0]!.id).toBe(1);
+ } finally { await unnamed.end({ timeout: 1 }); }
+ });
+
+ /** A TCP relay to the database that can hold the server's answers back, to deliver one connection's reply late. */
+ async function relay() {
+ const target = new URL(url!);
+ let held: Array<string | Buffer> | null = null;
+ let client: net.Socket | null = null;
+ const sockets: net.Socket[] = [];
+ const server = net.createServer(c => {
+ client = c;
+ const s = net.connect(Number(target.port || 5432), target.hostname);
+ sockets.push(c, s);
+ c.on('data', d => s.write(d));
+ s.on('data', d => { if (held) held.push(d); else c.write(d); });
+ c.on('close', () => s.destroy()); s.on('close', () => c.destroy());
+ c.on('error', () => {}); s.on('error', () => {});
+ });
+ const port = await new Promise<number>(resolve => server.listen(0, '127.0.0.1', () => resolve((server.address() as AddressInfo).port)));
+ const relayed = new URL(url!); relayed.hostname = '127.0.0.1'; relayed.port = String(port);
+ return {
+ url: relayed.toString(),
+ hold() { held = []; },
+ release() { const out = held ?? []; held = null; for (const d of out) client!.write(d); },
+ close() { for (const s of sockets) s.destroy(); server.close(); },
+ };
+ }
+
+ test('a statement described before the change but answered after the pool healed is not kept as prepared', async () => {
+ const { select, alter } = await setup(1, CHANGES[0][1]);
+ const types = new Map();
+ const late = await relay();
+ const a = postgres(url!, { max: 1, shared_types: types, onnotice: () => {} });
+ const b = postgres(late.url, { max: 1, shared_types: types, onnotice: () => {} });
+ try {
+ expect(Array.from(await a.unsafe(select, [1], { prepare: true }) as Iterable<{ id: number }>)[0]!.id).toBe(1);
+ await b.unsafe('SELECT 1');
+ late.hold();
+ const described = b.unsafe(select, [1], { prepare: true }).execute();
+ await new Promise(resolve => setTimeout(resolve, 300));
+ await alter();
+ expect(Array.from(await a.unsafe(select, [1], { prepare: true }) as Iterable<{ id: number }>)[0]!.id).toBe(1);
+ const unrelated = b.unsafe('SELECT 2 AS n').execute();
+ late.release();
+ await described;
+ await unrelated;
+ const inTx = await caught(b.begin(tx => tx.unsafe(select, [1], { prepare: true })));
+ expect(inTx).toBeNull();
+ } finally {
+ await a.end({ timeout: 1 });
+ await b.end({ timeout: 1 });
+ late.close();
+ }
+ });
+
+ for (const [name, change] of CHANGES) {
+ test(`${name}: the in-transaction stale-plan error is retryable and the admission loop re-runs it with no caller-visible error`, async () => {
+ const { inTx, alter } = await setup(1, change);
+ expect((await inTx())[0]!.id).toBe(1);
+ await alter();
+ expect((await retryWriteAdmission(randomUUID(), () => inTx(), 5000))[0]!.id).toBe(1);
+ await alter();
+ const error = await caught(inTx());
+ expect(error).toMatchObject({ code: '0A000', routine: 'RevalidateCachedQuery' });
+ expect(transientDatabaseFailure(error)).toBe(true);
+ expect((await inTx())[0]!.id).toBe(1);
+ });
+
+ test(`${name}: after one pooled connection healed, the other pooled connections do not fail`, async () => {
+ const { engine, select, inTx, alter } = await setup(3, change);
+ await primeEvery(engine, select, 3);
+ await alter();
+ expect((await engine.executeRaw<{ id: number }>(select, [1]))[0]!.id).toBe(1);
+ expect(outcomes(await Promise.allSettled([inTx(), inTx(), inTx()]))).toEqual(['ok', 'ok', 'ok']);
+ await primeEvery(engine, select, 3);
+ await alter();
+ expect(await caught(inTx())).toMatchObject({ code: '0A000', routine: 'RevalidateCachedQuery' });
+ expect(outcomes(await Promise.allSettled([inTx(), inTx(), inTx()]))).toEqual(['ok', 'ok', 'ok']);
+ });
+ }
+});
+
+describe.skipIf(!url)('put_page after another connection adds a column to access_tokens (GST-2260)', () => {
+ let engine: PostgresEngine;
+ let close: () => Promise<void>;
+ let databaseUrl: string;
+ let token: string;
+ beforeAll(async () => {
+ ({ engine, close, databaseUrl } = await isolatedPersistencePostgres(url!));
+ token = (await mintLegacyToken(engine, { name: 'writer-example', scopes: ['read', 'write'], takesHolders: ['world'] })).token;
+ }, 240_000);
+ afterAll(async () => { if (engine) await disposePersistenceConsumer(engine); await close?.(); }, 60_000);
+
+ async function verify() {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ return await provider.verifyAccessToken(token) as unknown as AuthInfo;
+ }
+ async function put(slug: string, auth: AuthInfo) {
+ const out = await dispatchToolCall(engine, 'put_page', { slug, content: ['---', 'type: note', 'title: Stale plan', '---', '# Stale plan', '', 'Body ' + slug + '.'].join('\n'), request_id: randomUUID() },
+ { remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? 'default', takesHoldersAllowList: ['world'] });
+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n') };
+ }
+
+ /**
+ * Several writes in a row, so the token read is prepared on most of the pool's connections before the column changes.
+ * The token is verified once, before the change, so the first statement that meets the stale plan is the write's own
+ * token read inside its admission transaction (a verify outside a transaction would heal the pool first).
+ */
+ test('a column added between writes leaves every later write with no error', async () => {
+ const auth = await verify();
+ for (let i = 0; i < 4; i++) expect(await put('notes/stale-plan-before-' + i, auth)).toMatchObject({ isError: false });
+ const other = postgres(databaseUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try { await other.unsafe(`ALTER TABLE access_tokens ADD COLUMN stale_plan_probe_${randomUUID().slice(0, 8)} text`); }
+ finally { await other.end({ timeout: 1 }); }
+ const after: Array<{ isError: boolean; text: string }> = [];
+ for (let i = 0; i < 4; i++) after.push(await put('notes/stale-plan-after-' + i, auth));
+ expect(after.filter(out => out.isError).map(out => out.text)).toEqual([]);
+ const [row] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE slug LIKE 'notes/stale-plan-%' AND deleted_at IS NULL");
+ expect(row!.n).toBe(8);
+ }, 240_000);
+});
+
+describe.skipIf(!url)('pure-database transactions outside the write paths after another connection adds a column (GST-2260)', () => {
+ let engine: PostgresEngine;
+ let close: () => Promise<void>;
+ let databaseUrl: string;
+ beforeAll(async () => { ({ engine, close, databaseUrl } = await isolatedPersistencePostgres(url!, 'instance', 1)); }, 240_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+ async function addColumn(table: string) {
+ const other = postgres(databaseUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try { await other.unsafe(`ALTER TABLE ${table} ADD COLUMN stale_plan_probe_${randomUUID().slice(0, 8)} text`); }
+ finally { await other.end({ timeout: 1 }); }
+ }
+
+ test('an OAuth client-credentials grant whose locked client read meets the stale plan still issues a token', async () => {
+ const secret = 'stale-plan-secret-' + randomUUID();
+ await engine.executeRaw(`INSERT INTO oauth_clients (client_id, client_secret_hash, client_name, redirect_uris, grant_types, scope, token_endpoint_auth_method,
+ client_id_issued_at) VALUES ('stale-plan-client', $1, 'stale-plan-client', '{}', '{client_credentials}', 'read write', 'client_secret_post', 0)`, [hashToken(secret)]);
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ expect((await provider.exchangeClientCredentials('stale-plan-client', secret, 'read')).access_token).toStartWith('gbrain_at_');
+ await addColumn('oauth_clients');
+ expect((await provider.exchangeClientCredentials('stale-plan-client', secret, 'read')).access_token).toStartWith('gbrain_at_');
+ }, 60_000);
+
+ test('a minion job whose completion meets the stale plan is completed, not failed after it ran', async () => {
+ const queue = new MinionQueue(engine);
+ const run = async (token: string, before?: () => Promise<void>) => {
+ await queue.add('sync', { probe: token });
+ const claimed = await queue.claim(token, 30_000, 'default', ['sync']);
+ expect(claimed).not.toBeNull();
+ await before?.();
+ return queue.completeJob(claimed!.id, token, { done: token });
+ };
+ expect((await run('stale-plan-first'))?.status).toBe('completed');
+ expect((await run('stale-plan-second', () => addColumn('minion_jobs')))?.status).toBe('completed');
+ }, 60_000);
+});