Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Document the stale-plan heal in the changelog and key-files index
garrytanf3e5944f6e5a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8b1d8ab6f4..8e4e290b37 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers 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 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.++### Itemized changes++- `vendor/postgres` (`patches/[email protected]`): the first `RevalidateCachedQuery` error starts a process-wide plan generation; each connection drops its prepared statements before it builds its next query.+- `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 retries a stale plan within its existing budget, and publication and effects release a claim it aborted, as they do for contention.+- `src/core/oauth-grants.ts`, `src/core/minions/queue.ts`: the client-locked OAuth grant transaction and `completeJob` / `failJob` run once more after a stale plan.+- Tests: `test/stale-plan-heal.test.ts` (Postgres; listed in `test/postgres-unit-arms.txt`).+## [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 --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 31e304dce8..9012232caa 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`. #7240: `add` passes job data through `jsonbSafeJson` (text-safe.ts: lone UTF-16 surrogates and U+0000 become U+FFFD), because Postgres refuses either inside a JSONB value (22P02/22P05) and one such character refused the whole insert; `failJob` takes an optional `result` (a refused job's `refusal`, #7239).+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`. #7240: `add` passes job data through `jsonbSafeJson` (text-safe.ts: lone UTF-16 surrogates and U+0000 become U+FFFD), because Postgres refuses either inside a JSONB value (22P02/22P05) and one such character refused the whole insert; `failJob` takes an optional `result` (a refused job's `refusal`, #7239). GST-2260: `completeJob` and `failJob` run their database-only transaction once more when a stale plan aborted it (`retryOnStalePlan`), so a column another process added to `minion_jobs` never fails a job whose handler already ran (`test/stale-plan-heal.test.ts`).- `src/core/minions/queue-families.ts` — `queueFamilyStats(engine, since)` behind `MinionQueue.getStats().by_queue`: one row per queue (`waiting_now`/`active_now` now; `total`/`completed`/`failed`/`dead` among rows created in the window, the `by_type` semantics), with every per-run `dream-inline-*` queue folded into one `dream-inline` row whose `queues` counts them. `gbrain jobs stats` prints a line per row (`dream-inline (N queues)`) and carries `by_queue` in `--json`; `get_job_stats` spreads it too. `--queue <name>` still scopes the wedge block to one queue. Test: `test/jobs-stats-private-queue.serial.test.ts`.diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex a78bc19c4b..ce053615a6 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -8,7 +8,7 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `large_file:stage_streaming` (after each piece `stageStreamedContent` writes to a stage's in-progress name), `effect_recovery:before_stage` / `effect_recovery:staged` (a streamed, version 2 withdrawal mirror: once its record is durable, before its file is streamed into the publication stage, and after that step, before the recovery transaction renames the stage), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10; GBRA-130 C-1, C-4), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk|withdrawn --yes`, a non-interactive apply without `--yes` exits 3; a `--keep` some approved record does not offer refuses `recovery_choice_refused` in the kind's plan before anything runs). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version: a page record (`target: 'page'`) or a v2 shared-skill bundle record (`target: 'skill_bundle'`, every file of the bundle; a file matches a recorded version only when `bundleFileHash` also accepts its mode and shape). A bundle record `recoveryFiles` cannot read is listed in `refused` as `recovery_bundle_unsupported` (residual `bundle_refused`; named with `--request-id` it throws with the same ask_user fix). Every withdrawal-mirror effect recovery on the worktree whose file is not a regular file holding its pre-withdrawal or withdrawn bytes is an item too (`target: 'withdrawal_mirror'`, id `effect:<id>`, `effect_id`, the forget's `request_id`; its file view adds `withdrawn`, the recorded post-withdrawal fingerprint, and its only choice is `withdrawn`); a record without usable withdrawn bytes, or bound to another owner epoch, root or incarnation, is listed in `refused` as `recovery_effect_unsupported` (residual `effect_recovery`) with `fix` `{ ask_user, argv: gbrain repair stuck-recovery --source <id> --request-id <request> }` and a `user_message`, and named with `--request-id` it throws with that fix; a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior (an effect's `withdrawn`), disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. A record whose prior file is over the single-string ceiling (`staging.before`) resolves the same way in bounded memory: the disk file and the staged copy are hashed in pieces (the copy's state, `verified`, `missing` or `mismatched`, is in the prior view and the digest), backups are kernel copies checked by streamed hash, the diff file is a summary (both fingerprints, the first differing byte, a window of at most 1 KiB; `cmp` reproduces it), `--keep prior` runs recovery's `restoreBeforeStage` after `cleanupRecoveryStaging(keepBefore)`, and `--keep disk` backs up a mismatched copy (`<index>.prior-stage`) and removes it before abandoning. `--keep prior` without a verified copy refuses `recovery_prior_stage_unavailable` (registry entry; its fix is the `--keep disk` apply under the same hash). An effect item resolves through `resolveEffectRecovery` under the same lock and journal (key `effect:<id>:<preview hash>`): `backed_up` (the edited bytes beside the withdrawn bytes and their diff), `written` (first `rebaseStaleEffectRecovery` (`effect-recovery.ts`): when a later withdrawal moved the page past the record, the record is rebased under its page lock on the latest snapshot's `mirrorContent` bytes (the rendering `mirrorPage` itself writes), its publication stage and reserved bytes following them, and the journal stores the rebased `identity` in the same transaction, so the recorded bytes never put a later-withdrawn fact back on disk and a rerun resumes; a page deleted, replaced or segmented meanwhile refuses `recovery_effect_unsupported` with nothing written; then `upgradeRecoveryStaging` `forward` and the record's `after` bytes published at its publication stage, mode restored), then `claimAndRecoverEffect` (`effects.ts`, the resident pass's own claim + `recoverEffectPublication` + failure recording) materializes the page, clears the record and advances the effect's cursor, and `trueUpRequests` settles the forget's receipt; `--keep disk`/`prior` on it refuse `recovery_choice_refused`, since keeping the edited or pre-withdrawal bytes would let the next sync re-import the forgotten fact. A bundle's `--keep prior` writes the prior bytes of its edited files and `recoverPublication` restores the rest; `--keep disk` keeps every file and abandons the publication; both back up every file first. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`, `test/pathological/c1-effect-stuck-recovery.test.ts` and `test/pathological/c4-bundle-stuck-recovery.test.ts` (both engines; the effect probe asserts the forgotten fact stays forgotten after the resolution, a commit and a sync).- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`). A path segment over 255 bytes, or `ENAMETOOLONG` from the lookup, refuses `invalid_params` with detail `file_name_too_long` and a fix naming a slug whose segments fit 240 bytes (`test/pathological/b12-slug-segment-bytes.test.ts`).-- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. #6355: a session that drops under the attempt (`isConnectionLoss` in `retry-matcher.ts`: connection-class SQLSTATEs, postgres.js's connection codes, `57P01`/`57P02`/`57P03`, the socket errnos) re-runs the attempt after `CONNECTION_LOSS_RETRY_MS` (100/300/900 ms), which is safe because every attempt reads the retained request id first and replays an admitted row; when the session keeps dropping the caller gets `writeOutcomeUnknown` (`write_outcome_unknown`, `reason: connection_lost`, fix: read the request by id), never the raw socket error the crash robot's receipt oracle took for a refusal while the write committed (`test/persistence-admission-connection-loss.test.ts`, forced probes: a lost COMMIT acknowledgment; a dead lent transaction used once with the pool finishing the write). The optional `recover(error)` hook runs before each re-run; `admitWrite` uses it to rebuild the pool (`engine.reconnect`) and to move the re-run from a lent transaction (the consumer's lane, `onPersistenceLane`) to `engine.transaction`, since a dropped reservation fails every later use the same way ("Connection is no longer owned"). Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention. #6278 (B7): also the outstanding-request cap's `detail` format (`outstandingCapacityDetail`, `outstanding=N limit=M`, stamped by `journal.ts` `capacityError`) and its readers `isWriteCapacityWait` / `outstandingCapacityOf`, which the managed drain and `sync-run.ts`'s failure ledger use to tell a refusal that clears by itself from a cumulative cap. #8621: `waitOutRefreshFence` re-runs an interactive write's whole admission while a refresh fence refuses it (`worktree_refreshing`; 250 ms to 2 s backoff, `REFRESH_FENCE_WAIT_MS` = 10 s cap shared by every item of a `remember` batch via `withRefreshFenceBudget`, lowered by an explicit `wait_ms`); background writes and the managed sync are not waited for (`test/write-refusal-refresh-fence-8621.test.ts`).+- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. #6355: a session that drops under the attempt (`isConnectionLoss` in `retry-matcher.ts`: connection-class SQLSTATEs, postgres.js's connection codes, `57P01`/`57P02`/`57P03`, the socket errnos) re-runs the attempt after `CONNECTION_LOSS_RETRY_MS` (100/300/900 ms), which is safe because every attempt reads the retained request id first and replays an admitted row; when the session keeps dropping the caller gets `writeOutcomeUnknown` (`write_outcome_unknown`, `reason: connection_lost`, fix: read the request by id), never the raw socket error the crash robot's receipt oracle took for a refusal while the write committed (`test/persistence-admission-connection-loss.test.ts`, forced probes: a lost COMMIT acknowledgment; a dead lent transaction used once with the pool finishing the write). The optional `recover(error)` hook runs before each re-run; `admitWrite` uses it to rebuild the pool (`engine.reconnect`) and to move the re-run from a lent transaction (the consumer's lane, `onPersistenceLane`) to `engine.transaction`, since a dropped reservation fails every later use the same way ("Connection is no longer owned"). Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention. #6278 (B7): also the outstanding-request cap's `detail` format (`outstandingCapacityDetail`, `outstanding=N limit=M`, stamped by `journal.ts` `capacityError`) and its readers `isWriteCapacityWait` / `outstandingCapacityOf`, which the managed drain and `sync-run.ts`'s failure ledger use to tell a refusal that clears by itself from a cumulative cap. #8621: `waitOutRefreshFence` re-runs an interactive write's whole admission while a refresh fence refuses it (`worktree_refreshing`; 250 ms to 2 s backoff, `REFRESH_FENCE_WAIT_MS` = 10 s cap shared by every item of a `remember` batch via `withRefreshFenceBudget`, lowered by an explicit `wait_ms`); background writes and the managed sync are not waited for (`test/write-refusal-refresh-fence-8621.test.ts`). GST-2260: a stale plan (`isStalePlanError`: 0A000 from `RevalidateCachedQuery`, a prepared `SELECT *` or `RETURNING *` whose table another process changed) is a confirmed rollback and is retried like contention; `coordinator.ts` `transientDatabaseFailure` releases a publication or effect it aborted the same way (`test/stale-plan-heal.test.ts`).- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. v0.60.290.0 reads a version 2 record as version 1 (`Buffer.from(null)`, untyped `effect_unavailable` on every attempt, never parks) but never deletes it or its stage, so `mirrorPage` writes none while that binary could claim it (next entry). Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `rebaseStaleEffectRecovery` (the `--keep withdrawn` rebase), `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); the stuck-recovery preview (`recovery-resolve.ts` `scanStuckRecoveries`) lists such a record refused with that code and fix; `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code, or `withdrawal_mirror_failed` for the Git/embedding siblings parked behind the mirror (re-armed once it commits), once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex e74f557274..1264f10c23 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`. #6355: `closed()` settles a startup's internal query (the array-types fetch) and clears its saved error before reconnecting for `initial`, so a backend terminated during startup neither hands the caller's first statement a stale `57P01` on the fresh connection nor leaves an unhandled rejection (`fetchArrayTypes` also swallows its own failure); it clears the pending write buffer and its immediate handle, so a close that catches a buffered statement does not leave the next StartupMessage appended and unscheduled (a pool slot stuck at `CONNECT_TIMEOUT`); pinned by `test/postgres-driver-startup-death.test.ts` against a scripted wire-protocol server. A query cancelled after it was written stays current until its own ReadyForQuery, so its answer is never read for the next query, and rejects `57014`; no server cancel is sent for it while statements are pipelined behind it, because a CancelRequest stops whatever the backend is running (pinned by `test/e2e/postgres-driver-cancel-pipeline.test.ts`, direct and PgBouncer). A statement answer that arrives with no current query retires the connection with `CONNECTION_DESYNC` and calls `ondesync({ message, connection, statement })`; `PoolIncidentCounter` logs `pg_connection_desync` (pinned by `test/e2e/postgres-driver-desync-tripwire.test.ts`). #6930: `array_types` hands every pool for one database target the array types the process's first connection fetched, so later connections skip the pg_type round trip; `transaction_pipeline` pipelines on a connection its owner holds (`sql.begin`, `sql.reserve`) while every statement in flight leaves it inside a transaction and never behind COMMIT/ROLLBACK/END/ABORT/PREPARE TRANSACTION, so a transaction-mode pooler URL (`max_pipeline` 0, `db.transactionPipelineOptions`, `GBRAIN_PG_TXN_PIPELINE=0` off) keeps #6543's boundary; pinned by `test/pathological/pg-round-trips-6930.test.ts` and `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`.+- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`. #6355: `closed()` settles a startup's internal query (the array-types fetch) and clears its saved error before reconnecting for `initial`, so a backend terminated during startup neither hands the caller's first statement a stale `57P01` on the fresh connection nor leaves an unhandled rejection (`fetchArrayTypes` also swallows its own failure); it clears the pending write buffer and its immediate handle, so a close that catches a buffered statement does not leave the next StartupMessage appended and unscheduled (a pool slot stuck at `CONNECT_TIMEOUT`); pinned by `test/postgres-driver-startup-death.test.ts` against a scripted wire-protocol server. A query cancelled after it was written stays current until its own ReadyForQuery, so its answer is never read for the next query, and rejects `57014`; no server cancel is sent for it while statements are pipelined behind it, because a CancelRequest stops whatever the backend is running (pinned by `test/e2e/postgres-driver-cancel-pipeline.test.ts`, direct and PgBouncer). A statement answer that arrives with no current query retires the connection with `CONNECTION_DESYNC` and calls `ondesync({ message, connection, statement })`; `PoolIncidentCounter` logs `pg_connection_desync` (pinned by `test/e2e/postgres-driver-desync-tripwire.test.ts`). #6930: `array_types` hands every pool for one database target the array types the process's first connection fetched, so later connections skip the pg_type round trip; `transaction_pipeline` pipelines on a connection its owner holds (`sql.begin`, `sql.reserve`) while every statement in flight leaves it inside a transaction and never behind COMMIT/ROLLBACK/END/ABORT/PREPARE TRANSACTION, so a transaction-mode pooler URL (`max_pipeline` 0, `db.transactionPipelineOptions`, `GBRAIN_PG_TXN_PIPELINE=0` off) keeps #6543's boundary; pinned by `test/pathological/pg-round-trips-6930.test.ts` and `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`. GST-2260: the first `RevalidateCachedQuery` error (0A000, a prepared `SELECT *` or `RETURNING *` whose table another session changed) starts a process-wide plan generation, and every connection drops its prepared statements before its next query, so one migration costs one failed statement per process instead of one per pooled connection (`test/stale-plan-heal.test.ts`).- `src/core/pg-type-cache.ts` — the store `shared_types` uses: one `SharedParameterTypes` Map per database target in this process (`sharedParameterTypes(url)`), keyed by SHA-256 digests of the driver's (types, SQL) key, and saved under `<gbrain home>/cache/pg-types/` (0600) for the next process. `db.checkPoolAndLoadSharedTypes` reads its scope (`server_version_num`, `config.version`, and the database as the server names it, so a proxy and a direct URL share a file) in each new pool's connection check and loads it; a different scope is ignored and replaced, a migration's `clearSharedTypes` deletes the file. `GBRAIN_PG_TYPE_CACHE_PERSIST=0` keeps it in-process. Pinned by `test/pg-type-cache.test.ts` and the new-process case in `test/e2e/postgres-shared-types.test.ts`. #6930: `sharedArrayTypes(url)` is the per-target, in-process-only `array_types` store (extension OIDs belong to one catalog); `GBRAIN_PG_TYPE_CACHE=0` turns it off and `clearSharedTypes` empties it.- `src/core/engine-sql/` — one SQL implementation per migrated storage domain (the domains are the `migrated` rows of `scripts/engine-sql-baseline.tsv`), run by both engines through one executor contract:diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex eb1e400d51..838e1d95f3 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/guardrails.ts` — vendor-neutral content guardrail seams (`registerGuardrailProvider`, `classify`). `loadGuardrailProvidersFromEnv(env = process.env, opts?: { cwd, skipCwdCheck })` accepts ONLY an absolute path or a `~/` path for `GBRAIN_GUARDRAILS_MODULE`; cwd-relative specs (`./`, `../`, bare `.`) and bare package specifiers (`pkg`, `@scope/pkg`, `pkg/sub` — in the compiled binary Bun's module walk-up starts at the cwd, so a hostile checkout's `node_modules/<name>/` would load) throw `GuardrailLoadError` before any import, and when `env` is `process.env` (or `opts.cwd` is given) a spec that a cwd .env file assigns is refused via `cwdDotenvAssignsKey` (message composed from env-trust's `CWD_DOTENV_REMEDIATION`) unless `opts.skipCwdCheck` (preflight's cwd == config-dir case). node:path/url/os are static imports. Registration is counted by EVENTS against a pre-import baseline so import-time side-effect registration and same-id replacement are accepted (#3688 residual). Pinned by `test/guardrails.test.ts` + `test/guardrails-env-load.test.ts`.-- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positive `oauth_clients.token_ttl` override, else the server default) at `TOKEN_TTL_MAX_SECONDS` from `src/core/grants/model.ts`, so a stored or configured lifetime above 90 days never mints a longer token (`test/oauth-token-ttl-clamp.test.ts`, both engines). `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. #6202 first-consent source choice: `begin()` marks a request `sourceChoice.editable` only for a self-registered client's first consent (`registered_via='dcr'`, set by the DCR insert and by migration `oauth_client_registered_via` as a nullable column; `grant_revision = 0`; no `client_credentials`; a source grant) and offers the active sources; `decide(id, approve, choice?)` refuses a choice on a denial, a read-only request or an unoffered source with 403 before claiming the request, and for an editable request calls `recordFirstConsentInTransaction` (`grants/service.ts`) inside the locked transaction before the code insert: revision 0 → 1 with an `action='consent'`, `actor='owner'` audit row even for an unchanged source, the final source share-locked and required active on every first consent, changed or not (a `GrantError` maps to 409 `client_policy_changed`, request terminal). `registered_via` is part of `policyDigest`. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions (the POST body allows `source_id` only as a string on `approve`; any other key or shape is 403 `invalid_consent`), and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell; for an editable request the write source is a select of the offered sources (read sources mirror it) and `source_id` is posted only when it differs from the current source. Tests: `test/oauth-owner-consent.test.ts`, `test/oauth-consent-security.test.ts`, `test/oauth-client-registered-via-migration.test.ts`, `test/e2e/oauth-owner-consent-source-postgres.test.ts`, `test/e2e/oauth-client-registered-via-postgres.test.ts`, `admin/e2e/admin.pw.ts`.+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positive `oauth_clients.token_ttl` override, else the server default) at `TOKEN_TTL_MAX_SECONDS` from `src/core/grants/model.ts`, so a stored or configured lifetime above 90 days never mints a longer token (`test/oauth-token-ttl-clamp.test.ts`, both engines). `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. #6202 first-consent source choice: `begin()` marks a request `sourceChoice.editable` only for a self-registered client's first consent (`registered_via='dcr'`, set by the DCR insert and by migration `oauth_client_registered_via` as a nullable column; `grant_revision = 0`; no `client_credentials`; a source grant) and offers the active sources; `decide(id, approve, choice?)` refuses a choice on a denial, a read-only request or an unoffered source with 403 before claiming the request, and for an editable request calls `recordFirstConsentInTransaction` (`grants/service.ts`) inside the locked transaction before the code insert: revision 0 → 1 with an `action='consent'`, `actor='owner'` audit row even for an unchanged source, the final source share-locked and required active on every first consent, changed or not (a `GrantError` maps to 409 `client_policy_changed`, request terminal). `registered_via` is part of `policyDigest`. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions (the POST body allows `source_id` only as a string on `approve`; any other key or shape is 403 `invalid_consent`), and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell; for an editable request the write source is a select of the offered sources (read sources mirror it) and `source_id` is posted only when it differs from the current source. GST-2260: `locked()` runs its transaction once more when a stale plan (`isStalePlanError`, `retryOnStalePlan` in `retry-matcher.ts`) aborted it, since every callback is database work only (`test/stale-plan-heal.test.ts`). Tests: `test/oauth-owner-consent.test.ts`, `test/oauth-consent-security.test.ts`, `test/oauth-client-registered-via-migration.test.ts`, `test/e2e/oauth-owner-consent-source-postgres.test.ts`, `test/e2e/oauth-client-registered-via-postgres.test.ts`, `admin/e2e/admin.pw.ts`.- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and reads the token's source, operation and takes-holder grant through `resolveTokenGrant` (`src/core/grants/legacy-token.ts`, shared with the legacy HTTP transport so the two transports cannot drift; a legacy-shape row converts to the grant columns on that read; `[]` takes-holders preserved as explicit deny-all, NULL → the `/mcp` dispatch site's fail-closed `['world']`). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).