Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

persistence: deferred counts as an open request where work must not be lost or skipped; state audit test; goldens

garrytan79bcc241a7c2
diff --git a/docs/designs/REFRESH_WRITE_BARRIER.md b/docs/designs/REFRESH_WRITE_BARRIER.md
index ab55030b52..0161bec928 100644
--- a/docs/designs/REFRESH_WRITE_BARRIER.md
+++ b/docs/designs/REFRESH_WRITE_BARRIER.md
@@ -105,8 +105,8 @@ plus two triggers:
- **Deferred-row guard** (BEFORE UPDATE on persistence_requests, a new function and trigger; the
shipped request protocol guard bodies are untouched): a row may leave `deferred` only to
`running` (and only when its refresh is released and the session declares
- `gbrain.refresh_barrier = '1'`, which only a new claim statement sets), or to `failed` /
- `cancelled` (expiry, cancel). Nothing moves a row into `deferred` except its insert. This is a
+ `gbrain.refresh_barrier = '1'`, which only a new claim statement sets), or to `conflict` /
+ `failed` / `cancelled` (a topology change, expiry, cancel). Nothing moves a row into `deferred` except its insert. This is a
backstop; no older code path selects the state.
No request protocol version changes. Deferred rows keep `protocol_version = 1`, so replay identity
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6a39fdaaa7..82c9bd24fd 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1296,6 +1296,16 @@ More: [docs/guides/ambient-recall.md#replay-after-a-degraded-wake](../../docs/gu
More: [docs/guides/troubleshooting.md#doctor-ops-tier](../../docs/guides/troubleshooting.md#doctor-ops-tier)
+### downgrade_blocked_deferred_writes
+
+<a id="downgrade_blocked_deferred_writes"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Writes deferred behind a worktree refresh are still waiting, and an older gbrain cannot drain them. | A release before the refresh write barrier never claims a deferred write, so after a downgrade those writes wait until the next upgrade. Safety does not depend on this check; liveness does. | Turn the barrier off (gbrain config set persistence.refresh_barrier false), wait until gbrain upgrade --check-downgrade exits 0, then downgrade. | host_admin | `repeat the read that failed` | 3 | no |
+
+More: [docs/guides/write-refusals.md#deferred-writes](../../docs/guides/write-refusals.md#deferred-writes)
+
### drain_holder_stalled
<a id="drain_holder_stalled"></a>
@@ -3876,6 +3886,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
More: [docs/guides/retrieval-feedback.md#ref_not_in_answer](../../docs/guides/retrieval-feedback.md#ref_not_in_answer)
+### refresh_barrier_expired
+
+<a id="refresh_barrier_expired"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A write that waited behind a worktree refresh was not applied, because the refresh was still unfinished after the barrier's wait limit. | With persistence.refresh_barrier on, a page write that reaches a refreshing checkout is accepted and waits for the refresh to end. A refresh that never ends (a stuck member sync, a host that stopped) would hold those writes forever, so the owner finishes each one failed after persistence.refresh_barrier_max_wait_ms (15 minutes by default). Nothing was applied. | Check the refresh with gbrain sources writer status --source <id> --json, then submit the write again with a new request_id. | provider | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/write-refusals.md#deferred-writes](../../docs/guides/write-refusals.md#deferred-writes)
+
### refresh_dirty
<a id="refresh_dirty"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index e3f897bf2f..6efcec2a31 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -573,7 +573,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.
| <a id="refresh_sync_timeout"></a>`refresh_sync_timeout` | `refresh_sync_timeout` | Reported per source in a refresh's `sync_blocked`, not as a refusal: the source's managed sync committed nothing within its share of the refresh sync budget (each member gets an equal share of what is left; `sources.refresh_sync_budget_ms`, `GBRAIN_REFRESH_SYNC_BUDGET_MS`, default 5 min), for example because no consumer claimed its write. The message names that write and its state. The checkout is at the upstream commit, the refresh completed and released its lock, and the source is behind until its next sync. A sync stopped by the drain's own rules is reported with that stop's code instead (`drain_stalled` and the others). | Run the `resume` command (`gbrain sync --source <source> --no-pull`). If it stalls the same way, check the write it names with `gbrain sources writer status <source> --json`. |
| <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout), or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. | Retry `gbrain sources refresh <source>`. |
| <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. Writer status reads HEAD and names the one step left when HEAD already sits at one of those commits: `--resume` at the upstream commit, `--abandon` at the start commit when no member source has synced past it. When one has (its `last_commit` is set and is neither the start commit nor an ancestor of it; a commit git cannot find counts too), `--abandon` refuses with this code and changes nothing, because the next sync would roll that member's pages back; `--resume` refuses too, and both name the one way out that keeps those pages: the fix (`next: ask_user`) previews with `git -C <checkout> status --short`, fast-forwards the checkout with `git merge --ff-only` to the commit the members synced (the upstream commit, or a later one a member already synced; it keeps uncommitted edits and refuses if one overlaps an incoming file), then runs `--resume`. When git refuses, the fix names a hard reset to that commit instead (destructive: it discards local commits and uncommitted edits not in that commit). `--resume` finishes a `recovery_required` refresh whose HEAD is the upstream commit or descends from it, unless a member synced a commit on this refresh's line (or one git cannot place) that HEAD does not contain; then it refuses with the same fast-forward fix. |
-| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not journaled. `detail` is `retry_after_ms=1000`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s, or its explicit `wait_ms` if lower, before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
+| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not journaled. `detail` is `retry_after_ms=1000`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s, or its explicit `wait_ms` if lower, before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. With `persistence.refresh_barrier` on, a single page or memory write waits behind the refresh instead ([deferred writes](#deferred-writes)). | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
A refresh is recorded in `persistence_worktree_refreshes` and survives a crash.
When the owner restarts it finishes the deterministic steps on its own: an
@@ -594,6 +594,37 @@ any other refusal keeps the stored command string in `fix`. Doctor
reports `worktree_refresh_stuck` for a refresh active longer than 15 minutes,
with the resume command.
+### Deferred writes
+
+With `persistence.refresh_barrier` on (`gbrain config set persistence.refresh_barrier true`, or
+`GBRAIN_REFRESH_BARRIER=1`; off by default), a single page or memory write (put, edit, rename, delete,
+append, remember, forget) that reaches a checkout while a refresh is draining, fenced, merging or
+syncing it is accepted and waits for the refresh instead of being refused `worktree_refreshing`:
+
+- The caller gets a pending receipt at once: the CLI exits 10 (`write_pending`); MCP answers
+ `isError: false` with `status: "pending"`, `request_id`, `receipt` (state `queued`),
+ `deferred: { refresh_id }` and `next` (`get_write_request` / `gbrain write-request <id>`).
+ Replaying the same request ID returns the same receipt.
+- When the refresh ends, the owner publishes the write in arrival order. If the refresh changed a file
+ the write would publish, the write ends `conflict` with `revision_conflict` naming the refresh and
+ the files, and nothing is applied: a refreshed page is never overwritten. Read the page again and
+ submit the change with a new request ID. A credential that no longer grants the write ends it
+ `permission_denied`.
+- <a id="refresh_barrier_expired"></a>A write whose refresh is still unfinished after
+ `persistence.refresh_barrier_max_wait_ms` (default 15 minutes) ends `failed` with
+ `refresh_barrier_expired`, nothing applied. Check the refresh with
+ `gbrain sources writer status --source <source> --json`, then submit again with a new request ID.
+- Still refused as before: batches (`put_pages`, `remember` with `items`), jobs, skill bundles,
+ a refresh in `recovery_required`, more than `persistence.refresh_barrier_max_deferred` (default
+ 1000) writes waiting on one refresh, and any brain where a live consumer on the owner host runs a
+ release without the barrier. Repo-less brains and database-only sources never wait.
+- `gbrain sources writer status --json` shows `deferred: { count, oldest_age_ms, refresh_id }` on
+ each active refresh.
+- <a id="downgrade_blocked_deferred_writes"></a>Before installing an older release, turn the barrier
+ off and wait for `gbrain upgrade --check-downgrade` to exit 0. It exits 3 with
+ `downgrade_blocked_deferred_writes` (count and oldest age) while deferred writes remain, because an
+ older release never drains them.
+
## Managed sync drain stops
`gbrain sync` on a managed brain keeps going until the source's cursor is done
diff --git a/src/commands/doctor/checks/owner-host-stale.ts b/src/commands/doctor/checks/owner-host-stale.ts
index e7544be8fa..d13682650b 100644
--- a/src/commands/doctor/checks/owner-host-stale.ts
+++ b/src/commands/doctor/checks/owner-host-stale.ts
@@ -23,7 +23,7 @@ export async function ownerHostStaleCheck(engine: BrainEngine): Promise<Check> {
const open = await engine.executeRaw<{ worktree_id: string; open_writes: number; oldest_open: string | Date; source_ids: string[] | null }>(`
SELECT r.worktree_id::text AS worktree_id, count(*)::int AS open_writes, min(r.created_at) AS oldest_open,
(SELECT array_agg(b.source_id ORDER BY b.source_id) FROM persistence_source_bindings b WHERE b.worktree_id=r.worktree_id) AS source_ids
- FROM persistence_requests r WHERE r.worktree_id IS NOT NULL AND r.state IN ('queued','running','recovering')
+ FROM persistence_requests r WHERE r.worktree_id IS NOT NULL AND r.state IN ('queued','deferred','running','recovering')
GROUP BY r.worktree_id`);
const owners = await ownerActivity(engine, open.map(row => row.worktree_id));
const stale = open.flatMap(row => {
diff --git a/src/commands/doctor/checks/persistence-capacity.ts b/src/commands/doctor/checks/persistence-capacity.ts
index 6eb3ea3f4c..a5ff8f1a50 100644
--- a/src/commands/doctor/checks/persistence-capacity.ts
+++ b/src/commands/doctor/checks/persistence-capacity.ts
@@ -42,7 +42,7 @@ export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Che
const principal = /^principal:([^:]+):(.+)$/.exec(row.scope);
const stalled = `count(*) FILTER (WHERE created_at <= now()-interval '${OUTSTANDING_STALL_S} seconds')`;
const holders = await engine.executeRaw<{ source_id: string; n: number | string; stalled: number | string }>(`SELECT source_id,count(*) AS n,${stalled} AS stalled
- FROM persistence_requests WHERE state IN ('queued','running','recovering')${principal ? ' AND principal_kind=$1 AND principal_id=$2' : ''}
+ FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering')${principal ? ' AND principal_kind=$1 AND principal_id=$2' : ''}
GROUP BY source_id ORDER BY ${stalled} DESC,count(*) DESC,source_id LIMIT 3`,
principal ? [principal[1], principal[2]] : []);
if (!holders.length || Number(holders[0].stalled) === 0) continue;
diff --git a/src/commands/serve-http-admin-api.ts b/src/commands/serve-http-admin-api.ts
index 46890304b7..fe6721d6ba 100644
--- a/src/commands/serve-http-admin-api.ts
+++ b/src/commands/serve-http-admin-api.ts
@@ -86,7 +86,7 @@ export async function queryHealthIndicators(engine: BrainEngine): Promise<{
// reported as pending in the last 24 hours later ended without committing.
const [pending] = await sql`SELECT count(*)::int AS count,
COALESCE(floor(extract(epoch FROM now() - min(created_at))), 0)::int AS oldest_age_seconds
- FROM persistence_requests WHERE state IN ('queued', 'running', 'recovering')`;
+ FROM persistence_requests WHERE state IN ('queued', 'deferred', 'running', 'recovering')`;
const [laterFailed] = await sql`SELECT count(DISTINCT r.id)::int AS count FROM mcp_request_log l
JOIN persistence_requests r ON r.request_id::text = l.params->>'write_request_id'
WHERE l.status = 'accepted_pending' AND l.created_at > now() - interval '24 hours'
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4e42d0dfff..9ee21a442f 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -81,7 +81,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--check-downgrade', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -138,7 +138,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],
'trust': ['--accept-all', '--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-downgrade', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
diff --git a/src/core/company-brain/runtime.ts b/src/core/company-brain/runtime.ts
index 56c1bb0f26..a644d477c3 100644
--- a/src/core/company-brain/runtime.ts
+++ b/src/core/company-brain/runtime.ts
@@ -209,7 +209,7 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
}
const verified = await verifyCompanyBrain(engine, input.sourceId, plan, pack, opts.signal);
const failures = verified.failures;
- const [pending] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')", [input.sourceId]);
+ const [pending] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','deferred','running','recovering')", [input.sourceId]);
const pendingWrites = Number(pending?.count ?? 0);
if (failures || pendingWrites) {
receipt = await recordSourceIngestionOutcome(engine, { ...mutation(), outcome: 'incomplete', diagnostic: failures ? 'verification_failed' : 'pending_writes', counts: { verificationFailures: failures, pendingWrites } });
@@ -228,7 +228,7 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
`Another write touched source ${input.sourceId} while it was being verified, so completion was not recorded. Resume with ${resumeCommand(input)} to verify again.`,
{ fix: resumeFix(input, `Re-runs verification for source ${input.sourceId} against its approved commit.`) });
}
- const [pending] = await tx.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering') LIMIT 1", [input.sourceId]);
+ const [pending] = await tx.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','deferred','running','recovering') LIMIT 1", [input.sourceId]);
if (pending) {
throw opError('pending_writes', 'A pending source write prevents verified completion.',
`Source ${input.sourceId} has a queued or running write. Check the source's writer, let the write finish, then resume with ${resumeCommand(input)}.`,
diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.ts
index b880326138..1907ed1814 100644
--- a/src/core/engine-sql/page-body.ts
+++ b/src/core/engine-sql/page-body.ts
@@ -40,7 +40,7 @@ import { RELEASE_STAGED_CTE } from '../persistence/limits.ts';
export const LIVE_STAGING_STATES = ['open', 'sealed', 'prepared'];
const TERMINAL_STAGING_STATES = ['committed', 'aborted', 'expired'];
-const NON_TERMINAL_REQUEST_STATES = ['queued', 'running', 'recovering'];
+const NON_TERMINAL_REQUEST_STATES = ['queued', 'deferred', 'running', 'recovering'];
const hex = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex');
const bytes = (value: unknown): Uint8Array => {
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index 59dd576886..cfa3147724 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -243,7 +243,7 @@ async function derivationSweep(fn: () => Promise<void>, factId: number, sourceId
async function assertNoPendingPublication(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages'], ownRequest: string): Promise<void> {
if (!pages.length) return;
const [blocked] = await tx.executeRaw<{ request_id: string; slug: string; state: string }>(`SELECT r.request_id::text,r.slug,r.state FROM persistence_requests r
- WHERE r.source_id=$1 AND r.id<>$3::uuid AND r.slug=ANY($2::text[]) AND (r.recovery IS NOT NULL OR r.state IN ('queued','running','recovering'))
+ WHERE r.source_id=$1 AND r.id<>$3::uuid AND r.slug=ANY($2::text[]) AND (r.recovery IS NOT NULL OR r.state IN ('queued','deferred','running','recovering'))
UNION ALL SELECT r.request_id::text,COALESCE(t->>'slug',r.slug),e.state FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(e.data->'targets','[]'::jsonb)) t
WHERE e.source_id=$1 AND e.request_id<>$3::uuid AND e.kind='withdrawal-mirror' AND (e.state<>'committed' OR e.recovery IS NOT NULL) AND t->>'slug'=ANY($2::text[])
diff --git a/src/core/generations/managed.ts b/src/core/generations/managed.ts
index 26de087b5c..c5cba546aa 100644
--- a/src/core/generations/managed.ts
+++ b/src/core/generations/managed.ts
@@ -238,7 +238,7 @@ export async function listOrphanCandidates(db: BrainEngine, sourceIds: readonly
`SELECT a.source_id, a.kind, a.owner_key, a.id AS activation_id, m->>'slug' AS slug, a.created_at::text AS created_at
FROM derived_generation_activations a CROSS JOIN LATERAL jsonb_array_elements(a.members) m
WHERE a.state='pending' AND a.source_id=ANY($1::text[]) AND ($2::text IS NULL OR a.kind=$2) AND m->>'action'='create'
- AND NOT EXISTS (SELECT 1 FROM persistence_requests r WHERE r.request_id=a.id::uuid AND r.state IN ('queued','running','recovering'))
+ AND NOT EXISTS (SELECT 1 FROM persistence_requests r WHERE r.request_id=a.id::uuid AND r.state IN ('queued','deferred','running','recovering'))
AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id AND p.slug=m->>'slug' AND p.deleted_at IS NULL)
AND NOT EXISTS (SELECT 1 FROM derived_generation_items i JOIN derived_generations g ON g.id=i.generation_id
WHERE g.source_id=a.source_id AND g.kind=a.kind AND g.state='live' AND i.item_key=m->>'slug' AND i.action<>'retired')
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index efd5a01455..9dc285709f 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -91,7 +91,7 @@ export function untiledSql(p: string, t: string): string {
/** The staging `s` (an alias of page_body_stagings) is live in stagingNeedsTextSql's sense: a write that may still publish it. */
export function liveStagingSql(s: string): string {
return `(${s}.state IN ('open','sealed','prepared')
- OR EXISTS (SELECT 1 FROM persistence_requests rq WHERE rq.state IN ('queued','running','recovering')
+ OR EXISTS (SELECT 1 FROM persistence_requests rq WHERE rq.state IN ('queued','deferred','running','recovering')
AND rq.intent->'body_ref'->>'staging_id' = ${s}.id::text))`;
}
diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.ts
index 1b55061ca5..867541ec6e 100644
--- a/src/core/persistence/activation.ts
+++ b/src/core/persistence/activation.ts
@@ -243,7 +243,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
await tx.executeRaw('LOCK TABLE gbrain_cycle_locks IN SHARE ROW EXCLUSIVE MODE');
const legacyLocks = await inspectLegacyWriterLocks(tx);
if (legacyLocks.some(row => !opts.cleanupDeadLocalLocks || row.liveness !== 'dead_eligible')) throw quiescence();
- if ((await tx.executeRaw(`SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1`)).length
+ if ((await tx.executeRaw(`SELECT id FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL LIMIT 1`)).length
|| (await tx.executeRaw('SELECT id FROM persistence_effects WHERE recovery IS NOT NULL LIMIT 1')).length) throw await notQuiescedError(tx, quiescence().message, { queuedEffects: false });
if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, drift_audit: driftAudit, git_durability: gitDurabilityListing(bindings), ...await gitDurabilityWarnings(bindings), ...databaseOnlyListing };
for (const row of legacyLocks) {
diff --git a/src/core/persistence/applied-watermark.ts b/src/core/persistence/applied-watermark.ts
index 48c4797c7d..3c99bb5285 100644
--- a/src/core/persistence/applied-watermark.ts
+++ b/src/core/persistence/applied-watermark.ts
@@ -88,7 +88,7 @@ export async function readWriteWatermark(engine: Pick<BrainEngine, 'executeRaw'>
const [row] = await engine.executeRaw<{ last_commit: string | null; last_sync_at: unknown; pending_min: number | string | null;
pending_count: number | string; pending_since: unknown }>(`SELECT s.last_commit, s.last_sync_at, p.pending_min, p.pending_count, p.pending_since
FROM sources s LEFT JOIN LATERAL (SELECT min(r.sequence) AS pending_min, count(*) AS pending_count, min(r.created_at) AS pending_since FROM persistence_requests r
- WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.state IN ('queued','running','recovering')) p ON true WHERE s.id=$1`, [sourceId]);
+ WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.state IN ('queued','deferred','running','recovering')) p ON true WHERE s.id=$1`, [sourceId]);
const [newest] = row?.pending_min == null ? await engine.executeRaw<{ sequence: number | string | null }>('SELECT max(sequence) AS sequence FROM persistence_requests') : [];
const through = row?.pending_min != null ? Number(row.pending_min) - 1 : newest?.sequence == null ? null : Number(newest.sequence);
return {
diff --git a/src/core/persistence/blocking-effects.ts b/src/core/persistence/blocking-effects.ts
index 0cad39f4db..656a95f695 100644
--- a/src/core/persistence/blocking-effects.ts
+++ b/src/core/persistence/blocking-effects.ts
@@ -33,7 +33,7 @@ export function blockingEffectHint(effect: BlockingEffect): string {
export async function notQuiescedError(tx: SqlEngine, message: string, opts: { queuedEffects: boolean }): Promise<OperationError> {
const [request] = await tx.executeRaw<{ request_id: string; source_id: string; slug: string; operation: string; state: string }>(
`SELECT request_id::text AS request_id,source_id,slug,operation,state FROM persistence_requests
- WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL ORDER BY sequence LIMIT 1`);
+ WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL ORDER BY sequence LIMIT 1`);
if (request) return new OperationError('writer_not_quiesced', message, `${WRITER_INSPECTION_HINT} Blocking request ${request.request_id} `
+ `(${request.operation}, ${request.state}) for source ${request.source_id}, page ${request.slug}. Inspect it with: ${inspect(request.source_id)}. `
+ 'Let the resident owner publish or recover it, then retry.');
diff --git a/src/core/persistence/connector-checkpoint-migration.ts b/src/core/persistence/connector-checkpoint-migration.ts
index 2643663276..9706f266f7 100644
--- a/src/core/persistence/connector-checkpoint-migration.ts
+++ b/src/core/persistence/connector-checkpoint-migration.ts
@@ -62,7 +62,7 @@ const orphanPredicate = (first: number) => {
((c.op='managed-connector' AND NOT (c.fingerprint = ANY(${k}::text[])))
OR (c.op='managed-connector-retry' AND NOT (COALESCE(c.completed_keys->0->>'checkpointKey','') = ANY(${k}::text[]))))
AND NOT EXISTS (SELECT 1 FROM persistence_requests r
- WHERE (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL)
+ WHERE (r.state IN ('queued','deferred','running','recovering') OR r.recovery IS NOT NULL)
AND (r.intent->>'kind' LIKE 'connector\\_v2\\_%' OR r.intent->>'kind' LIKE 'managed\\_connector\\_%')
AND (r.intent->>'checkpointKey' = c.fingerprint OR r.intent->>'checkpointKey' = c.completed_keys->0->>'checkpointKey'
OR r.request_id::text = c.completed_keys->0->>'requestId'))
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 6f889c781c..6d274cdb26 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -556,7 +556,7 @@ export class ManagedConnectorSync {
}
private async retryBlocker(engine: BrainEngine): Promise<WriteRequest | undefined> {
const [row] = await engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
- WHERE ((r.source_id=$1 OR r.worktree_id=$2::uuid) AND (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL))
+ WHERE ((r.source_id=$1 OR r.worktree_id=$2::uuid) AND (r.state IN ('queued','deferred','running','recovering') OR r.recovery IS NOT NULL))
OR EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.recovery IS NOT NULL
AND (e.source_id=$1 OR e.worktree_id=$2::uuid)) ORDER BY r.sequence LIMIT 1`, [this.sourceId, this.binding?.worktree_id ?? null]);
return row;
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index f81c7ccdac..049d094fd9 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -107,7 +107,7 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
exit: 'gbrain sources writer unlock' });
const requests = await engine.executeRaw<{ request_id: string; source_id: string; slug: string; operation: string; state: string; recovering: boolean }>(
`SELECT request_id::text AS request_id, source_id, slug, operation, state, recovery IS NOT NULL AS recovering FROM persistence_requests
- WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL ORDER BY sequence LIMIT 50`);
+ WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL ORDER BY sequence LIMIT 50`);
for (const r of requests) {
blockers.push({ kind: 'request', id: r.request_id, source_id: r.source_id, detail: `${r.operation} ${r.state}${r.recovering ? ', recovering' : ''} (${r.source_id}:${r.slug})`,
exit: r.state === 'queued' && !r.recovering ? `gbrain cancel-write-request ${r.request_id} (MCP: cancel_write_request), or wait for the owner to publish it`
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 9344b5c60d..2122c2e53c 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -151,7 +151,7 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
COUNT(r.id) FILTER (WHERE r.state='queued')::integer AS queued,
COUNT(r.id) FILTER (WHERE r.state='running')::integer AS running,
COUNT(r.id) FILTER (WHERE r.state='recovering')::integer AS recovering,
- MIN(r.created_at) FILTER (WHERE r.state IN ('queued','running','recovering')) AS oldest_request_at,
+ MIN(r.created_at) FILTER (WHERE r.state IN ('queued','deferred','running','recovering')) AS oldest_request_at,
(MAX(r.sequence) FILTER (WHERE r.state='committed'))::text AS last_completed_sequence,
COALESCE((SELECT c.recovery_bytes FROM persistence_counters c WHERE c.key='worktree:'||w.id::text),0)::text AS recovery_bytes,
(SELECT COUNT(*)::integer FROM persistence_effects e WHERE e.worktree_id=w.id AND e.recovery IS NOT NULL) AS recovering_effects
@@ -163,11 +163,11 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
operation: string; intent_kind: string | null; preparation_attempts: number | null } & Omit<ClaimRow, 'state'>>(
`SELECT request_id,worktree_id,source_id,state,blocked_reason,error_code,created_at,claim_phase,execution_token,claim_expires_at<now() AS claim_lapsed,publication_started,
operation,intent->>'kind' AS intent_kind,preparation_attempts,id::text AS id
- FROM persistence_requests WHERE state IN ('queued','running','recovering') OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);
+ FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);
const queue = await engine.executeRaw(`SELECT state,COUNT(*)::integer AS count,COALESCE(SUM(intent_bytes),0)::text AS intent_bytes,
MIN(created_at) AS oldest_request_at,
MAX(EXTRACT(EPOCH FROM (now()-created_at))*1000)::bigint::text AS oldest_age_ms
- FROM persistence_requests WHERE state IN ('queued','running','recovering') GROUP BY state ORDER BY state`);
+ FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') GROUP BY state ORDER BY state`);
const effects = await engine.executeRaw(`SELECT e.kind,e.state,COUNT(*)::integer AS count,MIN(r.created_at) AS oldest_at
FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
WHERE e.state<>'committed' AND NOT (e.data ? 'settled') GROUP BY e.kind,e.state ORDER BY e.kind,e.state`);
diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.ts
index 49dcdc4447..b411460467 100644
--- a/src/core/persistence/engine-graduation.ts
+++ b/src/core/persistence/engine-graduation.ts
@@ -655,7 +655,7 @@ async function quiesceFresh(run: Run, input: PlanInputs, expect: string): Promis
run.m.source = plan.source;
run.m.triggerBypass = plan.triggerBypass!;
const [pending] = await run.source!.executeRaw<{ request_id: string | null }>(
- `SELECT request_id::text AS request_id FROM persistence_requests WHERE state IN ('queued','running','recovering') ORDER BY sequence LIMIT 1`).catch(() => [{ request_id: null }]);
+ `SELECT request_id::text AS request_id FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') ORDER BY sequence LIMIT 1`).catch(() => [{ request_id: null }]);
run.m.replayRequestId = pending?.request_id ?? null;
save(run);
}
diff --git a/src/core/persistence/graduation-drain.ts b/src/core/persistence/graduation-drain.ts
index b396a7aeb9..222f637d59 100644
--- a/src/core/persistence/graduation-drain.ts
+++ b/src/core/persistence/graduation-drain.ts
@@ -16,7 +16,7 @@ import type { GraduationBlocker } from './engine-graduation.types.ts';
const PENDING_REQUESTS_SQL = `SELECT r.request_id::text AS request_id, r.source_id, r.operation, r.state,
r.recovery IS NOT NULL AS recovering, r.blocked_reason, w.owner_host_id::text AS owner_host_id
FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id = r.worktree_id
- WHERE r.state IN ('queued', 'running', 'recovering') OR r.recovery IS NOT NULL
+ WHERE r.state IN ('queued', 'deferred', 'running', 'recovering') OR r.recovery IS NOT NULL
ORDER BY r.sequence`;
const TERMINAL = new Set(['committed', 'conflict', 'failed', 'cancelled']);
@@ -127,7 +127,7 @@ export async function drainForGraduation(source: BrainEngine, opts: { timeoutMs:
try {
while (Date.now() < deadline) {
const [row] = await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests
- WHERE request_id::text = ANY($1::text[]) AND (state IN ('queued', 'running', 'recovering') OR recovery IS NOT NULL)`, [pending]);
+ WHERE request_id::text = ANY($1::text[]) AND (state IN ('queued', 'deferred', 'running', 'recovering') OR recovery IS NOT NULL)`, [pending]);
if (Number(row?.n ?? 0) === 0) break;
consumer.wake();
await new Promise(resolve => setTimeout(resolve, pollMs));
@@ -136,7 +136,7 @@ export async function drainForGraduation(source: BrainEngine, opts: { timeoutMs:
await consumer.stop();
}
const terminal = await source.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests
- WHERE request_id::text = ANY($1::text[]) AND state NOT IN ('queued', 'running', 'recovering') AND recovery IS NULL ORDER BY sequence`, [pending]);
+ WHERE request_id::text = ANY($1::text[]) AND state NOT IN ('queued', 'deferred', 'running', 'recovering') AND recovery IS NULL ORDER BY sequence`, [pending]);
const blockers = (await graduationBlockers(source, opts.hostId))
.map(b => lastError && b.kind === 'request' ? { ...b, detail: `${b.detail}; last drain error ${lastError}` } : b);
return { drained: terminal.map(r => r.request_id), blockers };
diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.ts
index 20a25afd68..b7634ba51e 100644
--- a/src/core/persistence/intent-redaction.ts
+++ b/src/core/persistence/intent-redaction.ts
@@ -67,7 +67,7 @@ async function sweepChunk(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: str
ids: readonly string[] | null = null, exclude: string | null = null): Promise<{ rows: ChunkRow[]; scanned: number; last: string | null }> {
const rows = await engine.executeRaw<SweepRow>(`WITH chunk AS MATERIALIZED (
SELECT id,principal_kind,principal_id,sequence,
- (state IN ('queued','running','recovering') OR recovery IS NOT NULL) AS pending,
+ (state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL) AS pending,
lower(COALESCE(intent::text,'')) AS i,lower(COALESCE(outcome::text,'')) AS o,lower(COALESCE(error_detail::text,'')) AS d,lower(COALESCE(error_message,'')) AS m
FROM persistence_requests WHERE source_id=$1 AND sequence>$2::bigint AND ($3::bigint IS NULL OR sequence<=$3::bigint)
AND ($6::uuid[] IS NULL OR id=ANY($6::uuid[])) AND ($7::uuid IS NULL OR id<>$7::uuid)
@@ -233,7 +233,7 @@ export async function findRequestsForSlugs(engine: BrainEngine, sourceId: string
export async function findRequestsHoldingStagings(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, stagingIds: readonly string[]): Promise<IntentRedactionTarget[]> {
if (!stagingIds.length) return [];
return engine.executeRaw<IntentRedactionTarget>(`SELECT id::text AS id,principal_kind,principal_id FROM persistence_requests
- WHERE source_id=$1 AND state IN ('queued','running','recovering') AND intent->'body_ref'->>'staging_id'=ANY($2::text[]) ORDER BY sequence`, [sourceId, [...stagingIds]]);
+ WHERE source_id=$1 AND state IN ('queued','deferred','running','recovering') AND intent->'body_ref'->>'staging_id'=ANY($2::text[]) ORDER BY sequence`, [sourceId, [...stagingIds]]);
}
/**
diff --git a/src/core/persistence/orphan-bindings.ts b/src/core/persistence/orphan-bindings.ts
index 8b6e5ca48e..c1c361692e 100644
--- a/src/core/persistence/orphan-bindings.ts
+++ b/src/core/persistence/orphan-bindings.ts
@@ -20,7 +20,7 @@ const ORPHANS = `SELECT b.source_id, b.source_incarnation::text AS source_incarn
CASE WHEN s.id IS NULL THEN 'source_removed' ELSE 'incarnation_replaced' END AS reason,
(SELECT COUNT(*)::int FROM persistence_requests r
WHERE r.source_id = b.source_id AND r.source_incarnation = b.source_incarnation
- AND r.state IN ('queued','running','recovering')) AS pending_requests
+ AND r.state IN ('queued','deferred','running','recovering')) AS pending_requests
FROM persistence_source_bindings b
LEFT JOIN sources s ON s.id = b.source_id
WHERE s.id IS NULL OR s.incarnation <> b.source_incarnation`;
@@ -39,7 +39,7 @@ export async function deleteOrphanBinding(engine: Pick<BrainEngine, 'executeRaw'
WHERE b.source_id = $1 AND b.source_incarnation = $2::uuid
AND NOT EXISTS (SELECT 1 FROM sources s WHERE s.id = b.source_id AND s.incarnation = b.source_incarnation)
AND NOT EXISTS (SELECT 1 FROM persistence_requests r WHERE r.source_id = b.source_id
- AND r.source_incarnation = b.source_incarnation AND r.state IN ('queued','running','recovering'))
+ AND r.source_incarnation = b.source_incarnation AND r.state IN ('queued','deferred','running','recovering'))
RETURNING b.source_id`,
[binding.source_id, binding.source_incarnation],
);
diff --git a/src/core/persistence/owner-activity.ts b/src/core/persistence/owner-activity.ts
index 5b2f85ad02..989885a402 100644
--- a/src/core/persistence/owner-activity.ts
+++ b/src/core/persistence/owner-activity.ts
@@ -53,7 +53,7 @@ export async function ownerActivity(engine: BrainEngine, worktreeIds: readonly s
(SELECT max(x.completed_at) FROM sources s CROSS JOIN LATERAL (SELECT r.completed_at FROM persistence_requests r
WHERE r.worktree_id=w.id AND r.source_incarnation=s.incarnation AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%'
ORDER BY r.completed_at DESC LIMIT 1) x)) AS last_active,
- (SELECT min(r.created_at) FROM persistence_requests r WHERE r.worktree_id=w.id AND r.state IN ('queued','running','recovering')) AS oldest_open
+ (SELECT min(r.created_at) FROM persistence_requests r WHERE r.worktree_id=w.id AND r.state IN ('queued','deferred','running','recovering')) AS oldest_open
FROM persistence_worktrees w
WHERE w.id::text = ANY($1::text[]) AND w.owner_host_id IS NOT NULL`, [ids, CONSUMER_LAPSED_MS],
{ signal: engine.kind === 'postgres' ? opts.signal : undefined });
diff --git a/src/core/persistence/page-upload.ts b/src/core/persistence/page-upload.ts
index 35774825d4..bbd20e0762 100644
--- a/src/core/persistence/page-upload.ts
+++ b/src/core/persistence/page-upload.ts
@@ -109,7 +109,7 @@ export interface UploadRow {
const LIVE = `'{${LIVE_STAGING_STATES.join(',')}}'::text[]`;
/** The session `s` is named by an unfinished write (its staged body is a GC root until that write ends). */
-const REQUEST_HELD_SQL = `EXISTS (SELECT 1 FROM persistence_requests r WHERE r.state IN ('queued','running','recovering')
+const REQUEST_HELD_SQL = `EXISTS (SELECT 1 FROM persistence_requests r WHERE r.state IN ('queued','deferred','running','recovering')
AND r.intent->'body_ref'->>'staging_id' = s.id::text)`;
/**
* The session `s` expires: an open session past either deadline, a sealed (committing) one only past its hard deadline,
diff --git a/src/core/persistence/repair-busy.ts b/src/core/persistence/repair-busy.ts
index 2158cfbec9..e0650c7456 100644
--- a/src/core/persistence/repair-busy.ts
+++ b/src/core/persistence/repair-busy.ts
@@ -55,7 +55,7 @@ export async function loadRepairBusySet(engine: BrainEngine, sourceId: string, i
try {
const pending = await engine.executeRaw<PendingRow>(`SELECT slug, intent->>'path' AS path, intent->>'sourcePath' AS source_path,
intent->'renameFrom'->>'slug' AS rename_slug, intent->'renameFrom'->>'sourcePath' AS rename_source_path
- FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL)`, [sourceId]);
+ FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL)`, [sourceId]);
for (const row of pending) { add(row.path, row.slug); add(row.source_path); add(row.rename_source_path, row.rename_slug); }
const cursors = await engine.executeRaw<CursorRow>(`SELECT completed_keys->0->>'runId' AS run_id, completed_keys->0->>'index' AS index
FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'
diff --git a/src/core/persistence/skill-activation.ts b/src/core/persistence/skill-activation.ts
index 3645bcd732..66474ef667 100644
--- a/src/core/persistence/skill-activation.ts
+++ b/src/core/persistence/skill-activation.ts
@@ -60,7 +60,7 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,
row.owner_host_id, String(row.owner_epoch), String(row.topology_generation), row.relative_path, row.local_path, row.coordination_path]));
if (identity(current) !== identity(initial)
|| (await tx.executeRaw(`SELECT id FROM gbrain_cycle_locks WHERE ${NOT_PAGE_EMBEDDING_LEASE} LIMIT 1`)).length) throw quiescence();
- if ((await tx.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length
+ if ((await tx.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length
|| (await tx.executeRaw("SELECT id FROM persistence_effects WHERE state IN ('queued','running') OR recovery IS NOT NULL LIMIT 1")).length) {
throw await notQuiescedError(tx, quiescence().message, { queuedEffects: true });
}
diff --git a/src/core/persistence/topology-locks.ts b/src/core/persistence/topology-locks.ts
index 82ffdd8796..f8c61799dc 100644
--- a/src/core/persistence/topology-locks.ts
+++ b/src/core/persistence/topology-locks.ts
@@ -151,7 +151,7 @@ export async function topologyCanonicalStamp(tx:BrainEngine,worktreeId:string):P
export async function settleTopologyRequests(tx: BrainEngine, sources: string[], worktrees: string[], principal: string): Promise<number> {
const requests = await tx.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests
WHERE (source_id=ANY($1::text[]) OR worktree_id=ANY($2::uuid[]))
- AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) ORDER BY sequence`, [sources,worktrees]);
+ AND (state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL) ORDER BY sequence`, [sources,worktrees]);
const busy = requests.find(row => row.state === 'running' || row.state === 'recovering' || row.recovery != null);
if (busy) {
throw opError('write_pending', 'Publication must finish or recover before source lifecycle can proceed.',
@@ -167,7 +167,7 @@ export async function settleTopologyRequests(tx: BrainEngine, sources: string[],
`Effect ${blocked.id} on source ${source} (a queued withdrawal mirror, a running effect or one holding a recovery record) has not finished, so the lifecycle change rolled back and nothing changed. The owner's effect worker settles it; check it with the command in fix, which lists it with its page and request. Then run the same lifecycle command again with the same request_id.`,
{fix:ownerStatusFix(source)});
}
- const pending = requests.filter(row => row.state === 'queued');
+ const pending = requests.filter(row => row.state === 'queued' || row.state === 'deferred');
// Revocation and publication use the same principal rows. Administrative
// invalidation may terminate revoked work but still respects guard ordering.
const principals = new Map(pending.map(row => [`${row.principal_kind}:${row.principal_id}`,requestPrincipal(row)]));
diff --git a/src/core/persistence/write-applied.ts b/src/core/persistence/write-applied.ts
index 5159ad11cb..3e347697ed 100644
--- a/src/core/persistence/write-applied.ts
+++ b/src/core/persistence/write-applied.ts
@@ -25,7 +25,7 @@ export interface WriteApplied {
watermark: WriteWatermark;
}
-const UNSETTLED = ['queued', 'running', 'recovering'];
+const UNSETTLED = ['queued', 'deferred', 'running', 'recovering'];
export async function readWriteApplied(engine: BrainEngine, row: { source_id: string; source_incarnation: string; slug: string; sequence: string | number; state: string }): Promise<WriteApplied> {
const sequence = Number(row.sequence);
@@ -33,7 +33,7 @@ export async function readWriteApplied(engine: BrainEngine, row: { source_id: st
const base = { sequence, watermark, page: null, embedding_hold: null, searchable_yet: false, searchable: false as const };
if (UNSETTLED.includes(row.state)) {
const [ahead] = await engine.executeRaw<{ count: number | string }>(`SELECT count(*) AS count FROM persistence_requests
- WHERE source_id=$1 AND source_incarnation=$2::uuid AND state IN ('queued','running','recovering') AND sequence < $3::bigint`, [row.source_id, row.source_incarnation, sequence]);
+ WHERE source_id=$1 AND source_incarnation=$2::uuid AND state IN ('queued','deferred','running','recovering') AND sequence < $3::bigint`, [row.source_id, row.source_incarnation, sequence]);
return { ...base, state: 'pending_write', gap: { requests_ahead: Number(ahead?.count ?? 0), unembedded_chunks: 0 } };
}
if (row.state !== 'committed') return { ...base, state: 'not_written', gap: { requests_ahead: 0, unembedded_chunks: 0 } };
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 4b42497248..1babdcdee4 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -2218,7 +2218,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LA
RAISE EXCEPTION 'writer_coordinator_required: writer state is unreadable to this database role' USING ERRCODE='42501';
END IF;
IF COALESCE(current_setting('gbrain.writer_quiesced',true),'')<>'true' OR NOT NEW.enabled OR NEW.writer_protocol_floor<>2
- OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_effects WHERE state='running' OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE EXISTS
(SELECT 1 FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 6fb40a172d..cebc29767e 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2977,7 +2977,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LA
RAISE EXCEPTION 'writer_coordinator_required: writer state is unreadable to this database role' USING ERRCODE='42501';
END IF;
IF COALESCE(current_setting('gbrain.writer_quiesced',true),'')<>'true' OR NOT NEW.enabled OR NEW.writer_protocol_floor<>2
- OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_effects WHERE state='running' OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE EXISTS
(SELECT 1 FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
diff --git a/src/core/schema-migrations/v290-refresh-write-barrier.ts b/src/core/schema-migrations/v290-refresh-write-barrier.ts
index 9d8f2c3b05..1aec6470a5 100644
--- a/src/core/schema-migrations/v290-refresh-write-barrier.ts
+++ b/src/core/schema-migrations/v290-refresh-write-barrier.ts
@@ -12,7 +12,7 @@ import type { Migration } from './types.ts';
// reaches completed or aborted, whoever moves it (a mixed-version window
// included); barrier_sequence is diagnostic.
// - gbrain_request_deferred: a deferred row leaves the state only to running (a
-// barrier-aware claim of a released refresh), failed or cancelled.
+// barrier-aware claim of a released refresh), conflict, failed or cancelled.
// - persistence_consumers.capabilities: what a live consumer can drain; admission
// defers only when every live consumer of the owner host can.
// Postgres swaps the state CHECK with ADD ... NOT VALID then VALIDATE (no long
@@ -47,7 +47,7 @@ export const v290: Migration = {
IF OLD.state<>'deferred' THEN RAISE EXCEPTION 'unsupported_mutation_protocol: only admission defers a request' USING ERRCODE='42501'; END IF;
RETURN NEW;
END IF;
- IF NEW.state IN ('failed','cancelled') THEN RETURN NEW; END IF;
+ IF NEW.state IN ('conflict','failed','cancelled') THEN RETURN NEW; END IF;
IF NEW.state='running' AND COALESCE(current_setting('gbrain.refresh_barrier',true),'')='1'
AND EXISTS (SELECT 1 FROM persistence_worktree_refreshes f WHERE f.id=OLD.deferred_refresh_id AND f.released_at IS NOT NULL) THEN
RETURN NEW;
@@ -85,7 +85,7 @@ export const v290: Migration = {
IF OLD.state<>'deferred' THEN RAISE EXCEPTION 'unsupported_mutation_protocol: only admission defers a request' USING ERRCODE='42501'; END IF;
RETURN NEW;
END IF;
- IF NEW.state IN ('failed','cancelled') THEN RETURN NEW; END IF;
+ IF NEW.state IN ('conflict','failed','cancelled') THEN RETURN NEW; END IF;
IF NEW.state='running' AND COALESCE(current_setting('gbrain.refresh_barrier',true),'')='1'
AND EXISTS (SELECT 1 FROM persistence_worktree_refreshes f WHERE f.id=OLD.deferred_refresh_id AND f.released_at IS NOT NULL) THEN
RETURN NEW;
diff --git a/src/core/shared-skills/migration-export.ts b/src/core/shared-skills/migration-export.ts
index 521986a4d5..da3334b047 100644
--- a/src/core/shared-skills/migration-export.ts
+++ b/src/core/shared-skills/migration-export.ts
@@ -185,7 +185,7 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data
if (!options.dryRun && options.confirmQuiesced && ((await ctx.engine.executeRaw(
'SELECT id FROM gbrain_cycle_locks WHERE $1::uuid IS NULL OR acquisition_token IS DISTINCT FROM $1::uuid LIMIT 1',
[options.ownLeaseToken ?? null])).length ||
- (await ctx.engine.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length)) {
+ (await ctx.engine.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length)) {
throw opError('writer_not_quiesced', 'Active maintenance locks or durable writes remain; finish or recover them before exporting.',
`Stop memory and file writers and old skill servers, let queued or recovering writes settle (the command in fix shows them for source ${options.sourceId}), then run the export again with --confirm-quiesced. Nothing was exported.`,
{ fix: readFix(`Shows source ${options.sourceId}'s writer, queued requests and pending recovery.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', options.sourceId, '--json'] }) });
diff --git a/src/core/shared-skills/persistence-schema.ts b/src/core/shared-skills/persistence-schema.ts
index 6512bfd4fe..1b4f7e3ec6 100644
--- a/src/core/shared-skills/persistence-schema.ts
+++ b/src/core/shared-skills/persistence-schema.ts
@@ -67,7 +67,7 @@ export const PROTOCOL_ACTIVATION_GUARD_SQL = `CREATE OR REPLACE FUNCTION gbrain_
RAISE EXCEPTION 'writer_coordinator_required: writer state is unreadable to this database role' USING ERRCODE='42501';
END IF;
IF COALESCE(current_setting('gbrain.writer_quiesced',true),'')<>'true' OR NOT NEW.enabled OR NEW.writer_protocol_floor<>2
- OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_effects WHERE state='running' OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE EXISTS
(SELECT 1 FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
diff --git a/src/schema.sql b/src/schema.sql
index 30f73911ae..abc1ed3311 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2973,7 +2973,7 @@ CREATE OR REPLACE FUNCTION gbrain_guard_protocol_activation() RETURNS trigger LA
RAISE EXCEPTION 'writer_coordinator_required: writer state is unreadable to this database role' USING ERRCODE='42501';
END IF;
IF COALESCE(current_setting('gbrain.writer_quiesced',true),'')<>'true' OR NOT NEW.enabled OR NEW.writer_protocol_floor<>2
- OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','deferred','running','recovering') OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_effects WHERE state='running' OR recovery IS NOT NULL)
OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE EXISTS
(SELECT 1 FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 3fff92528d..790399792b 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -382,13 +382,14 @@
"persistence_local_writers.persistence_local_writers_credential_hash_key": "u UNIQUE (credential_hash)",
"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))",
"persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)",
+ "persistence_requests.persistence_requests_deferred_refresh_id_fkey": "f FOREIGN KEY (deferred_refresh_id) REFERENCES persistence_worktree_refreshes(id)",
"persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",
"persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))",
"persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))",
"persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)",
"persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",
"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)",
- "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
+ "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'deferred'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",
"persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",
"persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)",
@@ -595,9 +596,10 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
- "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=66b6cd26959d68687e6bec2314d10594bd2e20c5013638cad41c2d872a999eda",
+ "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
@@ -608,6 +610,7 @@
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
+ "gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
@@ -1519,6 +1522,7 @@
"persistence_local_writers_pkey": "CREATE UNIQUE INDEX persistence_local_writers_pkey ON public.persistence_local_writers USING btree (id)",
"persistence_requests_compactable": "CREATE INDEX persistence_requests_compactable ON public.persistence_requests USING btree (completed_at) WHERE ((recovery IS NULL) AND (NOT compacted) AND (state = ANY (ARRAY['committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests_database_pending": "CREATE INDEX persistence_requests_database_pending ON public.persistence_requests USING btree (source_incarnation, sequence) WHERE ((worktree_id IS NULL) AND (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text])))",
+ "persistence_requests_deferred": "CREATE INDEX persistence_requests_deferred ON public.persistence_requests USING btree (deferred_refresh_id, sequence) WHERE (state = 'deferred'::text)",
"persistence_requests_foreground_committed": "CREATE INDEX persistence_requests_foreground_committed ON public.persistence_requests USING btree (worktree_id, sequence) WHERE ((state = 'committed'::text) AND (NOT (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text)))",
"persistence_requests_pending": "CREATE INDEX persistence_requests_pending ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text]))",
"persistence_requests_pkey": "CREATE UNIQUE INDEX persistence_requests_pkey ON public.persistence_requests USING btree (id)",
@@ -3536,7 +3540,8 @@
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
"17 process_start text/text NULL",
- "18 segment_reader boolean/bool NULL"
+ "18 segment_reader boolean/bool NULL",
+ "19 capabilities ARRAY/_text NOT NULL DEFAULT '{}'::text[]"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3664,7 +3669,8 @@
"43 admitter_segment_reader boolean/bool NULL",
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
- "46 next_attempt_at timestamp with time zone/timestamptz NULL"
+ "46 next_attempt_at timestamp with time zone/timestamptz NULL",
+ "47 deferred_refresh_id uuid/uuid NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -3715,7 +3721,9 @@
"12 outcome jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb",
"13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"14 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "15 completed_at timestamp with time zone/timestamptz NULL"
+ "15 completed_at timestamp with time zone/timestamptz NULL",
+ "16 barrier_sequence bigint/int8 NULL",
+ "17 released_at timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -4585,7 +4593,9 @@
"pages.trust_tier_stamp": "CREATE TRIGGER trust_tier_stamp BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_trust_tier()",
"persistence_brain.gbrain_protocol_activation": "CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON public.persistence_brain FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation()",
"persistence_effects.gbrain_effect_protocol": "CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_effects FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol()",
+ "persistence_requests.gbrain_request_deferred": "CREATE TRIGGER gbrain_request_deferred BEFORE UPDATE OF state ON public.persistence_requests FOR EACH ROW WHEN (((old.state = 'deferred'::text) OR (new.state = 'deferred'::text))) EXECUTE FUNCTION gbrain_guard_deferred_request()",
"persistence_requests.gbrain_request_protocol": "CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_requests FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol()",
+ "persistence_worktree_refreshes.gbrain_refresh_release": "CREATE TRIGGER gbrain_refresh_release BEFORE UPDATE OF state ON public.persistence_worktree_refreshes FOR EACH ROW WHEN (((new.state = ANY (ARRAY['completed'::text, 'aborted'::text])) AND (old.state <> ALL (ARRAY['completed'::text, 'aborted'::text])))) EXECUTE FUNCTION gbrain_release_refresh_barrier()",
"shared_skill_delivery_batches.shared_skill_delivery_lease": "CREATE TRIGGER shared_skill_delivery_lease AFTER INSERT OR UPDATE OF revisions ON public.shared_skill_delivery_batches FOR EACH ROW EXECUTE FUNCTION gbrain_lease_shared_skill_delivery()",
"shared_skill_heads.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_heads FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 431955bb26..dfbf264c7d 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -386,13 +386,14 @@
"persistence_local_writers.persistence_local_writers_credential_hash_key": "u UNIQUE (credential_hash)",
"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))",
"persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)",
+ "persistence_requests.persistence_requests_deferred_refresh_id_fkey": "f FOREIGN KEY (deferred_refresh_id) REFERENCES persistence_worktree_refreshes(id)",
"persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",
"persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))",
"persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))",
"persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)",
"persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",
"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)",
- "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
+ "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'deferred'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",
"persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",
"persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)",
@@ -598,9 +599,10 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
- "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=66b6cd26959d68687e6bec2314d10594bd2e20c5013638cad41c2d872a999eda",
+ "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
@@ -611,6 +613,7 @@
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
+ "gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
@@ -1523,6 +1526,7 @@
"persistence_local_writers_pkey": "CREATE UNIQUE INDEX persistence_local_writers_pkey ON public.persistence_local_writers USING btree (id)",
"persistence_requests_compactable": "CREATE INDEX persistence_requests_compactable ON public.persistence_requests USING btree (completed_at) WHERE ((recovery IS NULL) AND (NOT compacted) AND (state = ANY (ARRAY['committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests_database_pending": "CREATE INDEX persistence_requests_database_pending ON public.persistence_requests USING btree (source_incarnation, sequence) WHERE ((worktree_id IS NULL) AND (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text])))",
+ "persistence_requests_deferred": "CREATE INDEX persistence_requests_deferred ON public.persistence_requests USING btree (deferred_refresh_id, sequence) WHERE (state = 'deferred'::text)",
"persistence_requests_foreground_committed": "CREATE INDEX persistence_requests_foreground_committed ON public.persistence_requests USING btree (worktree_id, sequence) WHERE ((state = 'committed'::text) AND (NOT (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text)))",
"persistence_requests_pending": "CREATE INDEX persistence_requests_pending ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text]))",
"persistence_requests_pkey": "CREATE UNIQUE INDEX persistence_requests_pkey ON public.persistence_requests USING btree (id)",
@@ -3548,7 +3552,8 @@
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
"17 process_start text/text NULL",
- "18 segment_reader boolean/bool NULL"
+ "18 segment_reader boolean/bool NULL",
+ "19 capabilities ARRAY/_text NOT NULL DEFAULT '{}'::text[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3676,7 +3681,8 @@
"43 admitter_segment_reader boolean/bool NULL",
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
- "46 next_attempt_at timestamp with time zone/timestamptz NULL"
+ "46 next_attempt_at timestamp with time zone/timestamptz NULL",
+ "47 deferred_refresh_id uuid/uuid NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3727,7 +3733,9 @@
"12 outcome jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb",
"13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"14 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "15 completed_at timestamp with time zone/timestamptz NULL"
+ "15 completed_at timestamp with time zone/timestamptz NULL",
+ "16 barrier_sequence bigint/int8 NULL",
+ "17 released_at timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -4569,7 +4577,9 @@
"pages.trust_tier_stamp": "CREATE TRIGGER trust_tier_stamp BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_trust_tier()",
"persistence_brain.gbrain_protocol_activation": "CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON public.persistence_brain FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation()",
"persistence_effects.gbrain_effect_protocol": "CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_effects FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol()",
+ "persistence_requests.gbrain_request_deferred": "CREATE TRIGGER gbrain_request_deferred BEFORE UPDATE OF state ON public.persistence_requests FOR EACH ROW WHEN (((old.state = 'deferred'::text) OR (new.state = 'deferred'::text))) EXECUTE FUNCTION gbrain_guard_deferred_request()",
"persistence_requests.gbrain_request_protocol": "CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_requests FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol()",
+ "persistence_worktree_refreshes.gbrain_refresh_release": "CREATE TRIGGER gbrain_refresh_release BEFORE UPDATE OF state ON public.persistence_worktree_refreshes FOR EACH ROW WHEN (((new.state = ANY (ARRAY['completed'::text, 'aborted'::text])) AND (old.state <> ALL (ARRAY['completed'::text, 'aborted'::text])))) EXECUTE FUNCTION gbrain_release_refresh_barrier()",
"shared_skill_delivery_batches.shared_skill_delivery_lease": "CREATE TRIGGER shared_skill_delivery_lease AFTER INSERT OR UPDATE OF revisions ON public.shared_skill_delivery_batches FOR EACH ROW EXECUTE FUNCTION gbrain_lease_shared_skill_delivery()",
"shared_skill_heads.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_heads FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 70ea09940c..b481c99efc 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -386,13 +386,14 @@
"persistence_local_writers.persistence_local_writers_credential_hash_key": "u UNIQUE (credential_hash)",
"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))",
"persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)",
+ "persistence_requests.persistence_requests_deferred_refresh_id_fkey": "f FOREIGN KEY (deferred_refresh_id) REFERENCES persistence_worktree_refreshes(id)",
"persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",
"persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))",
"persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))",
"persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)",
"persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",
"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)",
- "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
+ "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'deferred'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",
"persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",
"persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)",
@@ -598,9 +599,10 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
- "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=66b6cd26959d68687e6bec2314d10594bd2e20c5013638cad41c2d872a999eda",
+ "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
@@ -611,6 +613,7 @@
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
+ "gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
@@ -1523,6 +1526,7 @@
"persistence_local_writers_pkey": "CREATE UNIQUE INDEX persistence_local_writers_pkey ON public.persistence_local_writers USING btree (id)",
"persistence_requests_compactable": "CREATE INDEX persistence_requests_compactable ON public.persistence_requests USING btree (completed_at) WHERE ((recovery IS NULL) AND (NOT compacted) AND (state = ANY (ARRAY['committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests_database_pending": "CREATE INDEX persistence_requests_database_pending ON public.persistence_requests USING btree (source_incarnation, sequence) WHERE ((worktree_id IS NULL) AND (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text])))",
+ "persistence_requests_deferred": "CREATE INDEX persistence_requests_deferred ON public.persistence_requests USING btree (deferred_refresh_id, sequence) WHERE (state = 'deferred'::text)",
"persistence_requests_foreground_committed": "CREATE INDEX persistence_requests_foreground_committed ON public.persistence_requests USING btree (worktree_id, sequence) WHERE ((state = 'committed'::text) AND (NOT (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text)))",
"persistence_requests_pending": "CREATE INDEX persistence_requests_pending ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text]))",
"persistence_requests_pkey": "CREATE UNIQUE INDEX persistence_requests_pkey ON public.persistence_requests USING btree (id)",
@@ -3548,7 +3552,8 @@
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
"17 process_start text/text NULL",
- "18 segment_reader boolean/bool NULL"
+ "18 segment_reader boolean/bool NULL",
+ "19 capabilities ARRAY/_text NOT NULL DEFAULT '{}'::text[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3676,7 +3681,8 @@
"43 admitter_segment_reader boolean/bool NULL",
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
- "46 next_attempt_at timestamp with time zone/timestamptz NULL"
+ "46 next_attempt_at timestamp with time zone/timestamptz NULL",
+ "47 deferred_refresh_id uuid/uuid NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3727,7 +3733,9 @@
"12 outcome jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb",
"13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"14 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "15 completed_at timestamp with time zone/timestamptz NULL"
+ "15 completed_at timestamp with time zone/timestamptz NULL",
+ "16 barrier_sequence bigint/int8 NULL",
+ "17 released_at timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -4569,7 +4577,9 @@
"pages.trust_tier_stamp": "CREATE TRIGGER trust_tier_stamp BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_trust_tier()",
"persistence_brain.gbrain_protocol_activation": "CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON public.persistence_brain FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation()",
"persistence_effects.gbrain_effect_protocol": "CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_effects FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol()",
+ "persistence_requests.gbrain_request_deferred": "CREATE TRIGGER gbrain_request_deferred BEFORE UPDATE OF state ON public.persistence_requests FOR EACH ROW WHEN (((old.state = 'deferred'::text) OR (new.state = 'deferred'::text))) EXECUTE FUNCTION gbrain_guard_deferred_request()",
"persistence_requests.gbrain_request_protocol": "CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_requests FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol()",
+ "persistence_worktree_refreshes.gbrain_refresh_release": "CREATE TRIGGER gbrain_refresh_release BEFORE UPDATE OF state ON public.persistence_worktree_refreshes FOR EACH ROW WHEN (((new.state = ANY (ARRAY['completed'::text, 'aborted'::text])) AND (old.state <> ALL (ARRAY['completed'::text, 'aborted'::text])))) EXECUTE FUNCTION gbrain_release_refresh_barrier()",
"shared_skill_delivery_batches.shared_skill_delivery_lease": "CREATE TRIGGER shared_skill_delivery_lease AFTER INSERT OR UPDATE OF revisions ON public.shared_skill_delivery_batches FOR EACH ROW EXECUTE FUNCTION gbrain_lease_shared_skill_delivery()",
"shared_skill_heads.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_heads FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index e32d6a2302..2657533ebc 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -386,13 +386,14 @@
"persistence_local_writers.persistence_local_writers_credential_hash_key": "u UNIQUE (credential_hash)",
"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))",
"persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)",
+ "persistence_requests.persistence_requests_deferred_refresh_id_fkey": "f FOREIGN KEY (deferred_refresh_id) REFERENCES persistence_worktree_refreshes(id)",
"persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",
"persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))",
"persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))",
"persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)",
"persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",
"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)",
- "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
+ "persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'deferred'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",
"persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",
"persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)",
@@ -598,9 +599,10 @@
"gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=b35125db2179fb90ea092804d0acd61b60e58434d7fbf937413324b681ab416c",
"gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, pg_temp] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",
"gbrain_graduation_fence()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=cd4642fe8deee2a3c14ef41f53862f0a449b2d8a10e47177bd4f5d2e05ce8803",
+ "gbrain_guard_deferred_request()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d27724f55c14a48ed24a02219e2ad6ce37c8a91cda7ae15982bec9414f1ed528",
"gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=aa01528006dd7029eac6808e0233991524c9de9dc14aaf41f44160d67a747042",
"gbrain_guard_inserted_facts()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=027c16bf0f61101510f54966dfa7d3c5f90112cef52a51861adc36103a0bc02b",
- "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=66b6cd26959d68687e6bec2314d10594bd2e20c5013638cad41c2d872a999eda",
+ "gbrain_guard_protocol_activation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=bb477ec66ecac06e6edba773a94a2834ef4286a0b9e5cfa8b9b8646e003b0b9e",
"gbrain_guard_request_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2709686143e064b577e2b3c8e3e2b1009d52a836a2bc709f5f003a251eb004d2",
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
@@ -611,6 +613,7 @@
"gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e",
"gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",
"gbrain_refuse_purging_derivation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=0d0afb3e61857f1668f2e7996da1c6aaf269aecaa1bf3763ce90df90e2d66fd3",
+ "gbrain_release_refresh_barrier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0474782d352e51a92be5486f0d1eb0245cd6dc70ab6d7320acc685330690db4b",
"gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=15a834d125e04a6508f114e93e2595800bccf0a8ccfe7e2e23323830580c98a1",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=a0aa697992ad1777eaba4a1f4d2325dc4f2a98f3ebf9e81325d1b068406ce1cb",
@@ -1519,6 +1522,7 @@
"persistence_local_writers_pkey": "CREATE UNIQUE INDEX persistence_local_writers_pkey ON public.persistence_local_writers USING btree (id)",
"persistence_requests_compactable": "CREATE INDEX persistence_requests_compactable ON public.persistence_requests USING btree (completed_at) WHERE ((recovery IS NULL) AND (NOT compacted) AND (state = ANY (ARRAY['committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))",
"persistence_requests_database_pending": "CREATE INDEX persistence_requests_database_pending ON public.persistence_requests USING btree (source_incarnation, sequence) WHERE ((worktree_id IS NULL) AND (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text])))",
+ "persistence_requests_deferred": "CREATE INDEX persistence_requests_deferred ON public.persistence_requests USING btree (deferred_refresh_id, sequence) WHERE (state = 'deferred'::text)",
"persistence_requests_foreground_committed": "CREATE INDEX persistence_requests_foreground_committed ON public.persistence_requests USING btree (worktree_id, sequence) WHERE ((state = 'committed'::text) AND (NOT (COALESCE((intent ->> 'kind'::text), ''::text) ~~ 'managed_sync_%'::text)))",
"persistence_requests_pending": "CREATE INDEX persistence_requests_pending ON public.persistence_requests USING btree (worktree_id, sequence) WHERE (state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text]))",
"persistence_requests_pkey": "CREATE UNIQUE INDEX persistence_requests_pkey ON public.persistence_requests USING btree (id)",
@@ -3544,7 +3548,8 @@
"15 version text/text NOT NULL",
"16 boot_id text/text NULL",
"17 process_start text/text NULL",
- "18 segment_reader boolean/bool NULL"
+ "18 segment_reader boolean/bool NULL",
+ "19 capabilities ARRAY/_text NOT NULL DEFAULT '{}'::text[]"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3672,7 +3677,8 @@
"43 admitter_segment_reader boolean/bool NULL",
"44 consumer_segment_reader boolean/bool NULL",
"45 transient_interruptions integer/int4 NOT NULL DEFAULT 0",
- "46 next_attempt_at timestamp with time zone/timestamptz NULL"
+ "46 next_attempt_at timestamp with time zone/timestamptz NULL",
+ "47 deferred_refresh_id uuid/uuid NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -3723,7 +3729,9 @@
"12 outcome jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb",
"13 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"14 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "15 completed_at timestamp with time zone/timestamptz NULL"
+ "15 completed_at timestamp with time zone/timestamptz NULL",
+ "16 barrier_sequence bigint/int8 NULL",
+ "17 released_at timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -4565,7 +4573,9 @@
"pages.trust_tier_stamp": "CREATE TRIGGER trust_tier_stamp BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_trust_tier()",
"persistence_brain.gbrain_protocol_activation": "CREATE TRIGGER gbrain_protocol_activation BEFORE UPDATE ON public.persistence_brain FOR EACH ROW EXECUTE FUNCTION gbrain_guard_protocol_activation()",
"persistence_effects.gbrain_effect_protocol": "CREATE TRIGGER gbrain_effect_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_effects FOR EACH ROW EXECUTE FUNCTION gbrain_guard_effect_protocol()",
+ "persistence_requests.gbrain_request_deferred": "CREATE TRIGGER gbrain_request_deferred BEFORE UPDATE OF state ON public.persistence_requests FOR EACH ROW WHEN (((old.state = 'deferred'::text) OR (new.state = 'deferred'::text))) EXECUTE FUNCTION gbrain_guard_deferred_request()",
"persistence_requests.gbrain_request_protocol": "CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR DELETE OR UPDATE ON public.persistence_requests FOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol()",
+ "persistence_worktree_refreshes.gbrain_refresh_release": "CREATE TRIGGER gbrain_refresh_release BEFORE UPDATE OF state ON public.persistence_worktree_refreshes FOR EACH ROW WHEN (((new.state = ANY (ARRAY['completed'::text, 'aborted'::text])) AND (old.state <> ALL (ARRAY['completed'::text, 'aborted'::text])))) EXECUTE FUNCTION gbrain_release_refresh_barrier()",
"shared_skill_delivery_batches.shared_skill_delivery_lease": "CREATE TRIGGER shared_skill_delivery_lease AFTER INSERT OR UPDATE OF revisions ON public.shared_skill_delivery_batches FOR EACH ROW EXECUTE FUNCTION gbrain_lease_shared_skill_delivery()",
"shared_skill_heads.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_heads FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index ef5fecd23b..5ea23a4799 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -2042,11 +2042,11 @@
},
"upgrade": {
"hasSwitchCase": false,
- "phase": "pre-connect",
+ "phase": "pre-connect-own-engine",
"preConnectRules": [
{
"condition": "command === 'upgrade'",
- "connectsEngine": false,
+ "connectsEngine": true,
"refusesThinClient": false,
"routesThinClient": false,
"terminates": true,
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index e82a42ae81..7d2824a47b 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6832,7 +6832,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/refresh-barrier-state-audit.test.ts b/test/refresh-barrier-state-audit.test.ts
new file mode 100644
index 0000000000..325c507abe
--- /dev/null
+++ b/test/refresh-barrier-state-audit.test.ts
@@ -0,0 +1,72 @@
+/**
+ * PR B refresh write barrier: every SQL or TypeScript test of a write request's open states decides about `deferred`.
+ *
+ * Protects: a write deferred behind a refresh is a durable, non-terminal request. Checks that must not proceed past an
+ * accepted write (activation, deactivation, graduation, topology changes, staging retention, purges, redaction,
+ * watermarks, capacity and diagnostics) list `deferred`; claim and head-of-queue selectors name released deferred rows
+ * through RELEASED_DEFERRED; managed-sync checks deliberately leave deferred rows out, so a refresh's own member syncs are
+ * never held behind writes that wait for that refresh. TypeScript checks read receipts, where a deferred row reads as
+ * `queued`, or rows of producers that never defer.
+ * Regression it catches: a new `('queued','running','recovering')` list added without that decision (for example the
+ * staging sweep, which would expire the body of a waiting write).
+ */
+import { expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+
+const OPEN_WITHOUT_DEFERRED = /'queued', ?'running', ?'recovering'/g;
+
+/** Files whose open-state lists leave `deferred` out on purpose, with how many such lists each holds. */
+const DECIDED: Record<string, { count: number; why: string }> = {
+ 'src/commands/book-mirror.ts': { count: 1, why: 'receipt state (a deferred row reads as queued)' },
+ 'src/core/cycle/synthesize-postprocess.ts': { count: 1, why: 'cycle producer, never deferred' },
+ 'src/core/facts/absorb-log.ts': { count: 1, why: 'facts producer, never deferred' },
+ 'src/core/generations/managed-retire.ts': { count: 1, why: 'maintenance producer, never deferred' },
+ 'src/core/minions/handlers/subagent-oneshot.ts': { count: 1, why: 'receipt state' },
+ 'src/core/minions/tool-write-identity.ts': { count: 1, why: 'receipt state' },
+ 'src/core/persistence/atom-maintenance.ts': { count: 3, why: 'maintenance producer, never deferred' },
+ 'src/core/persistence/atom-retry.ts': { count: 2, why: 'receipt state' },
+ 'src/core/persistence/checkpoint-validation.ts': { count: 2, why: 'managed sync' },
+ 'src/core/persistence/journal.ts': { count: 7, why: 'claim and head selectors use RELEASED_DEFERRED; the rest are sync or recovery rules' },
+ 'src/core/persistence/managed-sync-orphans.ts': { count: 4, why: 'managed sync' },
+ 'src/core/persistence/page-batch.ts': { count: 1, why: 'batches are never deferred' },
+ 'src/core/persistence/schema.ts': { count: 3, why: 'the original state CHECK and partial indexes; deferred rows have their own index' },
+ 'src/core/persistence/sync-admission.ts': { count: 1, why: 'managed sync' },
+ 'src/core/persistence/sync-cursor-key.ts': { count: 2, why: 'managed sync' },
+ 'src/core/persistence/sync-drain.ts': { count: 2, why: 'managed sync' },
+ 'src/core/persistence/sync-dry-run-writer.ts': { count: 1, why: 'managed sync' },
+ 'src/core/persistence/sync-movement.ts': { count: 1, why: 'managed sync' },
+ 'src/core/persistence/sync-pass-batch.ts': { count: 1, why: 'managed sync' },
+ 'src/core/persistence/sync-pass-carried.ts': { count: 2, why: 'managed sync' },
+ 'src/core/persistence/sync-pass-run.ts': { count: 3, why: 'managed sync' },
+ 'src/core/persistence/sync-pass.ts': { count: 3, why: 'managed sync' },
+ 'src/core/persistence/sync-run.ts': { count: 4, why: 'managed sync' },
+ 'src/core/persistence/sync-waivers.ts': { count: 2, why: 'managed sync' },
+ 'src/core/persistence/sync-window.ts': { count: 1, why: 'managed sync' },
+ 'src/core/persistence/terminal-classify.ts': { count: 2, why: 'classifies sync knock-ons' },
+ 'src/core/persistence/terminal-failures.ts': { count: 2, why: 'managed sync' },
+ 'src/core/persistence/types.ts': { count: 1, why: 'the public receipt states, where deferred reads as queued' },
+ 'src/core/persistence/worktree-refresh.ts': { count: 1, why: 'the drain counts released deferred rows through RELEASED_DEFERRED' },
+ 'src/core/shared-skills/retention.ts': { count: 1, why: 'skill bundles are never deferred' },
+};
+
+function walk(dir: string, out: string[] = []): string[] {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) walk(path, out);
+ else if (name.endsWith('.ts') && !name.includes('.generated.')) out.push(path);
+ }
+ return out;
+}
+
+test('every open-state list of write requests either names deferred or is a recorded decision', () => {
+ const found: Record<string, number> = {};
+ for (const file of walk('src')) {
+ const count = readFileSync(file, 'utf8').match(OPEN_WITHOUT_DEFERRED)?.length ?? 0;
+ if (count) found[file] = count;
+ }
+ const undecided = Object.entries(found).filter(([file, count]) => DECIDED[file]?.count !== count)
+ .map(([file, count]) => `${file}: ${count} list(s) without 'deferred' (recorded: ${DECIDED[file]?.count ?? 0})`);
+ const stale = Object.keys(DECIDED).filter(file => !found[file]);
+ expect({ undecided, stale }).toEqual({ undecided: [], stale: [] });
+});