Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): register the #6317 reliability-contract codes with full agent-operator envelopes

garrytan3da36936d213
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index b1a368dfa5..00ceed94cf 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -582,6 +582,16 @@ More: [docs/guides/write-refusals.md#concurrent_write](../../docs/guides/write-r
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### consumers_without_heartbeat
+
+<a id="consumers_without_heartbeat"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Running write claims on this host are stamped by a process that writes no `persistence_consumers` heartbeat row, so its liveness and mode cannot be read. | Every full consumer on this release renews a heartbeat row every 10 s; a claim owner with no row is a gbrain process from before the heartbeat table (an older `serve`, jobs worker or sync CLI), which also never defers to the resident consumer, so the host may run two full consumers until it is upgraded. | Upgrade and restart the process whose pid the check names (its kind and gbrain version come from the claim stamp); until then the host runs its consumer beside the resident one. Run: gbrain sources writer status --json | agent | `gbrain doctor --only consumers_without_heartbeat --json` | 1 | no |
+
+More: [docs/guides/troubleshooting.md#consumers-without-heartbeat](../../docs/guides/troubleshooting.md#consumers-without-heartbeat)
+
### content_rejected
<a id="content_rejected"></a>
@@ -728,6 +738,18 @@ More: [docs/guides/ambient-recall.md#replay-after-a-degraded-wake](../../docs/gu
|---|---|---|---|---|---|---|
| Commit or stash canonical skill edits before optimization. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### drain_stalled
+
+<a id="drain_stalled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A managed sync drain stopped `blocked` because its head write made no progress (no committed receipt and no step advance) for the whole stall window. | A renewed lease is not progress: the detector keys on the head claim's phase and step. With a live owner on this host the drain prints `stalled <N>s on <step>` from the allowance (budget plus 30 s) and keeps going; it stops only when `persistence.preparation_ceiling_ms` passes without the root being released, or when that owner's heartbeat row reads wedged (`cause: owner_wedged_here`, with the owner's kind, pid and nonce and `retry_after_ms` to the ceiling, after which the owner frees the root and the next pass holds the entry). A lapsed claim (`owner_missing`) stops at once unless this host owns the checkout and a live full consumer can reclaim it, which gets one more window. `drain.stall.cause` names which. | Inspect the writer with gbrain sources writer status --source <id> --json (read-only: the owner process, its step and what it waits on, and the next action). Before the ceiling (`next.safe_to_loop` true) rerun next.command after retry_after_ms; past it, or with a wedged owner, restart the named owner process on the brain host and rerun the same sync. Run: gbrain sources writer status --source '{source_id}' --json | host_admin | `gbrain doctor --only managed_sync_not_moving --json` | 1 | no |
+
+Reasons: `owner_wedged_here`, `owner_missing`, `preparation_overdue`, `publication_overdue`, `no_progress`.
+
+More: [docs/guides/write-refusals.md#drain-stalled](../../docs/guides/write-refusals.md#drain-stalled)
+
### dream_breaker_tripped
<a id="dream_breaker_tripped"></a>
@@ -1292,6 +1314,16 @@ More: [docs/guides/bootstrap.md#harness_hook_unowned](../../docs/guides/bootstra
|---|---|---|---|---|---|---|
| Held out required for bundled. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### host_identity_mismatch
+
+<a id="host_identity_mismatch"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| This process's `host.json` identity differs from the identity that owns the binding although both resolve on this machine, so writes that need the owner read it as another host. | Host identity is a file under the persistence home: a job worker or container launched with a different `HOME` or `GBRAIN_HOME` mints a new `host.json` and sees the binding as another host's (`owner_unavailable`, `host_mismatch`), so its maintenance writes never reach the owner. The check names both files and the environment each was minted under (`minted_under`, `unknown` for a file minted before it was recorded); re-deriving the identity would re-own every existing binding, so the fix is the environment, never the file. | Set GBRAIN_HOME on the supervisor of the process to the owner's home (the value the check prints; config appends .gbrain itself) and restart it; never edit or delete a host.json. Run: gbrain doctor --only host_identity_mismatch --json | host_admin | `gbrain doctor --only host_identity_mismatch --json` | 1 | no |
+
+More: [docs/guides/troubleshooting.md#host-identity-mismatch](../../docs/guides/troubleshooting.md#host-identity-mismatch)
+
### idempotency_conflict
<a id="idempotency_conflict"></a>
@@ -1582,6 +1614,18 @@ More: [docs/guides/cron-schedule.md#dream-beside-autopilot](../../docs/guides/cr
More: [docs/guides/write-refusals.md#managed_pull_skipped](../../docs/guides/write-refusals.md#managed_pull_skipped)
+### managed_sync_not_moving
+
+<a id="managed_sync_not_moving"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A managed source has unfinished sync work and a live consumer on its owner host, but no committed `managed_sync_*` receipt and no head step advance for longer than `persistence.preparation_ceiling_ms`. | Process liveness is not data movement: `/health` ok, a live pid and `sync_running: true` all held while one deployment moved nothing for weeks. `sources status --json` carries `data_moving`, `not_moving_since` and `movement_state` per source (`parked` when no drain or full consumer is live, informational), doctor warns with this code and counts it against the score, `serve` prints one notice when a source flips, and `gbrain sources writer movement` judges a window after a restart and exits 1 with this code (`reason: movement_check`) when pending work does not move. | Run gbrain sources writer status --source <id> --json (read-only): its next_action names the owner process, the step it is parked on and whether to wait or restart it. After the fix, gbrain sources writer movement proves the data moves again. Run: gbrain sources writer status --source '{source_id}' --json | host_admin | `gbrain doctor --only managed_sync_not_moving --json` | 1 | no |
+
+Reasons: `movement_check`.
+
+More: [docs/guides/troubleshooting.md#managed-sync-not-moving](../../docs/guides/troubleshooting.md#managed-sync-not-moving)
+
### manual_only_skipped
<a id="manual_only_skipped"></a>
@@ -2554,6 +2598,16 @@ More: [docs/guides/data-ingestion.md#credential-redaction](../../docs/guides/dat
|---|---|---|---|---|---|---|
| The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it. | Only the operator of the brain host can change what blocks this. | Ask the user to run the named gbrain command on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+### two_consumers_on_host
+
+<a id="two_consumers_on_host"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Two resident gbrain processes on this host (`serve`, `sync`, `jobs`, `autopilot` or `mcp`) have each run a full persistence consumer for longer than 30 s, so both claim writes on the same roots. | One full consumer per host is a preference, not a fenced role: a `serve` always starts full, every other resident kind defers to the first live full consumer it finds in `persistence_consumers`, and two processes that start within one renewal of each other, or a CLI that took its consumer before the `serve` started, both stay full until one exits. Every observed `preparing` wedge had two consumers alive on the host. Short-lived commands (`put`, `import`, `dream`, `cli`) and rows younger than 30 s are listed, never warned. | Let the shorter-lived of the two finish (a sync CLI run ends on its own) or restart it so it defers; with persistence.single_consumer off, this is the configured behavior. Run: gbrain sources writer status --json | agent | `gbrain doctor --only two_consumers_on_host --json` | 1 | no |
+
+More: [docs/guides/troubleshooting.md#two-consumers-on-host](../../docs/guides/troubleshooting.md#two-consumers-on-host)
+
### unavailable
<a id="unavailable"></a>
diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.ts
index 98ef392fd0..ce427d4a25 100644
--- a/scripts/check-agent-contract.ts
+++ b/scripts/check-agent-contract.ts
@@ -263,7 +263,9 @@ const READ_ONLY_SUBCOMMANDS = new Set(['config get', 'sources list', 'sources st
// Engine graduation: --status and --plan are zero-mutation (pre-connect; no schema migration, no target DDL).
'migrate --status', 'migrate --plan',
// Reads the pack resolution only; never connects without a configured brain (#6090).
- 'schema active']);
+ 'schema active',
+ // #6317: trusted-local writer administration reads (owners, running claims, consumers, movement); `sources writer claim|transfer|deactivate` stay mutating.
+ 'sources writer status', 'sources writer movement']);
function tsFiles(dir: string): string[] {
if (!existsSync(dir)) return [];
@@ -419,7 +421,7 @@ export function scan(root: string = ROOT): Hit[] {
if (!ts.isPropertyAssignment(p) || propName(p) !== 'argv' || !ts.isArrayLiteralExpression(p.initializer)) continue;
const words = p.initializer.elements.map(e => stringText(e));
if (words[0] !== 'gbrain' || words[1] === undefined) continue;
- if (!readOnly.has(words[1]!) && !READ_ONLY_SUBCOMMANDS.has(`${words[1]} ${words[2]}`)) add('verify-not-read-only', p);
+ if (!readOnly.has(words[1]!) && !READ_ONLY_SUBCOMMANDS.has(`${words[1]} ${words[2]}`) && !READ_ONLY_SUBCOMMANDS.has(`${words[1]} ${words[2]} ${words[3]}`)) add('verify-not-read-only', p);
}
}
}
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 596fa9458e..35e9969f15 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -141,6 +141,9 @@ test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistenc
test/embedding-dim-check-facts.test.ts postgres-engine fact insert cast (T6, codex #20) 1 source-surface-helper
test/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSync
test/error-catalogue.test.ts error code registry (agent contract v1) 5 readFileSync
+test/error-registry-6317-contract.test.ts #6317 codes are registered with a full envelope 3 readFileSync
+test/error-registry-6317-contract.test.ts drain_stalled: the same-host stop has a cause vocabulary and a filled writer-status fix 3 readFileSync
+test/error-registry-6317-contract.test.ts the doctor codes each have a troubleshooting symptom row that names who acts, consent and a verify step 1 readFileSync
test/eval-brainbench-e2e.slow.test.ts --llm availability gate 1 exec-scan
test/eval-brainbench-e2e.slow.test.ts privacy guard violation branches (negative path) 1 exec-scan
test/eval-brainbench-e2e.slow.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 11f5189066..046bb94f60 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -110,6 +110,7 @@ export const CODES = {
connector_holds_exhausted: { class: 'caller', summary: "The source holds the maximum number of failed items; its cursor did not advance." },
connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },
consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ consumers_without_heartbeat: { class: 'host_only', summary: "Running write claims on this host are stamped by a process that writes no `persistence_consumers` heartbeat row, so its liveness and mode cannot be read.", why: "Every full consumer on this release renews a heartbeat row every 10 s; a claim owner with no row is a gbrain process from before the heartbeat table (an older `serve`, jobs worker or sync CLI), which also never defers to the resident consumer, so the host may run two full consumers until it is upgraded.", docs: 'docs/guides/troubleshooting.md#consumers-without-heartbeat', suggestion: 'Upgrade and restart the process whose pid the check names (its kind and gbrain version come from the claim stamp); until then the host runs its consumer beside the resident one.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with their heartbeat rows beside the running claims and the owner each claim stamps.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'consumers_without_heartbeat', '--json'] } } },
content_rejected: { class: 'caller', summary: "The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`.", why: "A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry.", suggestion: 'Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again.' },
core_budget_exceeded: { class: 'caller', summary: "The write would push always-loaded core memory over its brain-wide character budget or page limit.", why: "Core pages enter every session's prompt in every harness, so their total size is capped on the write path.", docs: 'docs/guides/core-memory.md#budget', fix: { argv: ['gbrain', 'core', 'status', '--json'], consent: [], actor: 'agent', why: "Shows core usage against the budget and the largest core pages, read-only.", requires_exclusive: false } },
core_delete_owner_only: { class: 'consent', summary: "A remote caller tried to delete an always-loaded core page; only the owner can remove pages from core.", docs: 'docs/guides/core-memory.md#owner-only', actor: 'user' },
@@ -132,6 +133,14 @@ export const CODES = {
demo_verification_failed: { class: 'server', summary: "Expected ownership or decision provenance is missing." },
derived_cap_exhausted: { class: 'server', summary: "Paid work stopped at the cost cap derived from its estimate; the run is resumable." },
destination_not_ready: { class: 'host_only', summary: "The destination brain is not initialized for this operation." },
+ drain_stalled: { class: 'server', retryable: false, actor: 'host_admin',
+ summary: "A managed sync drain stopped `blocked` because its head write made no progress (no committed receipt and no step advance) for the whole stall window.",
+ why: "A renewed lease is not progress: the detector keys on the head claim's phase and step. With a live owner on this host the drain prints `stalled <N>s on <step>` from the allowance (budget plus 30 s) and keeps going; it stops only when `persistence.preparation_ceiling_ms` passes without the root being released, or when that owner's heartbeat row reads wedged (`cause: owner_wedged_here`, with the owner's kind, pid and nonce and `retry_after_ms` to the ceiling, after which the owner frees the root and the next pass holds the entry). A lapsed claim (`owner_missing`) stops at once unless this host owns the checkout and a live full consumer can reclaim it, which gets one more window. `drain.stall.cause` names which.",
+ reasons: ['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress'],
+ docs: 'docs/guides/write-refusals.md#drain-stalled',
+ suggestion: 'Inspect the writer with gbrain sources writer status --source <id> --json (read-only: the owner process, its step and what it waits on, and the next action). Before the ceiling (`next.safe_to_loop` true) rerun next.command after retry_after_ms; past it, or with a wedged owner, restart the named owner process on the brain host and rerun the same sync.',
+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: names the owner process holding the head write (kind, pid), its step and wait cause, and ends in a next_action.", requires_exclusive: false,
+ verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },
dream_breaker_tripped: { class: 'unavailable', summary: "A dream synthesize or patterns submission died (or, for patterns, was cancelled at its timeout after paid work) the breaker limit of times within 24 hours, so it was not submitted again.", why: "A run that keeps dying keeps paying; the breaker stops resubmitting until the cause is fixed and the key is reset. Patterns count per source (`dream:patterns:source:<id>`) whatever reflections each run read, and a completed run resets that count.", docs: 'docs/operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions', fix: { argv: ['gbrain', 'doctor', '--only', 'dream_paid_loop', '--json'], consent: [], actor: 'agent', why: 'Shows the tripped dream keys with their counts and reset commands, read-only.', requires_exclusive: false } },
dirty_tree: { class: 'caller', summary: "Commit or stash canonical skill edits before optimization." },
effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },
@@ -190,6 +199,7 @@ export const CODES = {
graduation_unsupported_platform: { class: 'host_only', summary: "Moving a brain with write history to Postgres is not available on this platform yet.", docs: 'docs/guides/move-to-postgres.md#platforms' },
graduation_verify_failed: { class: 'server', summary: "The moved copy did not verify against the source; the target stays fenced and the source stays authoritative.", docs: 'docs/guides/move-to-postgres.md#verify', reasons: ['count', 'digest', 'sequence', 'fk', 'trigger', 'relation_set', 'replay', 'doctor'] },
graph_incomplete: { class: 'server', summary: "Source relationship reconciliation is incomplete." },
+ host_identity_mismatch: { class: 'host_only', summary: "This process's `host.json` identity differs from the identity that owns the binding although both resolve on this machine, so writes that need the owner read it as another host.", why: "Host identity is a file under the persistence home: a job worker or container launched with a different `HOME` or `GBRAIN_HOME` mints a new `host.json` and sees the binding as another host's (`owner_unavailable`, `host_mismatch`), so its maintenance writes never reach the owner. The check names both files and the environment each was minted under (`minted_under`, `unknown` for a file minted before it was recorded); re-deriving the identity would re-own every existing binding, so the fix is the environment, never the file.", docs: 'docs/guides/troubleshooting.md#host-identity-mismatch', suggestion: 'Set GBRAIN_HOME on the supervisor of the process to the owner\'s home (the value the check prints; config appends .gbrain itself) and restart it; never edit or delete a host.json.', fix: { argv: ['gbrain', 'doctor', '--only', 'host_identity_mismatch', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: names both host.json paths, the HOME and GBRAIN_HOME each was minted under and the GBRAIN_HOME value to set.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'host_identity_mismatch', '--json'] } } },
harness_hook_duplicates: { class: 'caller', summary: "A harness hook carrier wires one Claude Code event more than once with this install's own entries (marked or not), so the hook fires twice per event.", why: "Claude Code can drop the `_gbrain` marker when it rewrites settings.json; installs before wave 11 then appended a second set on every re-run.", docs: 'docs/guides/bootstrap.md#harness_hook_duplicates', fix: { argv: ['gbrain', 'doctor', '--only', 'bootstrap_harness_health', '--json'], consent: [], actor: 'agent', why: "Names the carrier, the duplicated events and the re-run (with the install's own flags) that converges them, read-only.", requires_exclusive: false } },
harness_hook_unowned: { class: 'caller', summary: "A hook entry looks like gbrain's harness hook but is not this install's exact command, so gbrain left it in place.", why: "An unmarked entry is deleted only when its command is exactly what this install (or its receipt) wrote; an edited command or another install's launcher is never removed, and removal is not reported complete while it remains.", docs: 'docs/guides/bootstrap.md#harness_hook_unowned', fix: { argv: ['gbrain', 'bootstrap', 'harness', '--status'], consent: [], actor: 'agent', why: 'Shows each hook carrier with the events holding entries that are not this install\'s, read-only.', requires_exclusive: false } },
held_out_overlaps_benchmark: { class: 'caller', summary: "Held out overlaps benchmark." },
@@ -224,6 +234,13 @@ export const CODES = {
lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },
maintenance_backpressure: { class: 'retryable', summary: "Managed maintenance stopped admitting requests because this writer's outstanding requests, reserved receipt bytes or permanent request ids would pass 80% of their limit; nothing more was submitted.", why: "Each page of a maintenance run publishes as its own request under the local CLI writer the user's own CLI writes share. Stopping at 80% leaves room for those writes: reserved receipt bytes free only when receipts compact, request ids never.", docs: 'docs/guides/write-refusals.md#maintenance_backpressure', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the pending requests holding this writer's capacity, read-only.", requires_exclusive: false }, exit: 12 },
maintenance_lock_busy: { class: 'retryable', summary: "A source-scoped dream cycle skipped its brain-wide phases because another cycle (usually autopilot maintenance) holds the shared gbrain-cycle lease; its source phases still ran.", why: 'Brain-wide phases (synthesize, patterns, embed, purge and the other mixed or global phases) must not run twice at once, so a cycle that cannot take gbrain-cycle runs only the phases its own source lease covers.', docs: 'docs/guides/cron-schedule.md#dream-beside-autopilot', suggestion: 'Nothing is lost: the holder runs those phases itself. To run one now, wait until the lease is released, then re-run `gbrain dream --phase <phase>` (LLM-backed phases spend; ask the user first).', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows who holds gbrain-cycle and when its lease expires, read-only.', requires_exclusive: false } },
+ managed_sync_not_moving: { class: 'server', retryable: false, actor: 'host_admin',
+ summary: "A managed source has unfinished sync work and a live consumer on its owner host, but no committed `managed_sync_*` receipt and no head step advance for longer than `persistence.preparation_ceiling_ms`.",
+ why: "Process liveness is not data movement: `/health` ok, a live pid and `sync_running: true` all held while one deployment moved nothing for weeks. `sources status --json` carries `data_moving`, `not_moving_since` and `movement_state` per source (`parked` when no drain or full consumer is live, informational), doctor warns with this code and counts it against the score, `serve` prints one notice when a source flips, and `gbrain sources writer movement` judges a window after a restart and exits 1 with this code (`reason: movement_check`) when pending work does not move.",
+ reasons: ['movement_check'],
+ docs: 'docs/guides/troubleshooting.md#managed-sync-not-moving',
+ suggestion: 'Run gbrain sources writer status --source <id> --json (read-only): its next_action names the owner process, the step it is parked on and whether to wait or restart it. After the fix, gbrain sources writer movement proves the data moves again.',
+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the owner process, the head write\'s step and wait cause, and a next_action (wait with retry_after_ms, or restart the named pid).', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },
managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },
manual_only_skipped: { class: 'consent', summary: "An automatic remediation run (`gbrain onboard --auto`, `doctor --remediate`, MCP `run_onboard`, autopilot) did not submit a manual-only step: the schema-pack upgrade (`unify-types`) or the paid takes bootstrap (`extract-takes-from-pages`).", why: "A pack upgrade retypes pages and switches the brain's schema pack, and the takes bootstrap pays a model per page; both are the user's one-time decision, so only the user submits them. A job of that kind an earlier run already queued is listed in `queued_jobs` and still runs unless cancelled.", actor: 'user', suggestion: 'Show the user the step and its `fix.command` (`gbrain jobs submit <job> --follow`, with `--params` when the step has them); the user runs it after reviewing `gbrain onboard --check`. Cancel a listed queued job with `gbrain jobs cancel <id>` if the user does not want it.', fix: { argv: ['gbrain', 'jobs', 'list', '--status', 'waiting'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists queued jobs, including any manual-only job an earlier run queued.' } },
membership_inactive: { class: 'caller', summary: "The shared-skills enrollment epoch was left or superseded.", docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' },
@@ -346,6 +363,7 @@ export const CODES = {
topology_change_required: { class: 'host_only', summary: "Adding this source would replace or overlap another owner root." },
transcript_secret_exposure: { class: 'unavailable', summary: "Imported conversation pages may still carry a typed credential from before the labeled-credential detector, or the last audit found some; pages are never rewritten automatically.", why: 'Re-ingest skips unchanged sessions, so pages imported before the detector keep any password typed in prose until someone reviews them.', docs: 'docs/guides/data-ingestion.md#credential-redaction', suggestion: 'Run the read-only audit to list affected slugs (never values), then review, edit or (after asking the user) remove each page, and ask the user to rotate any real credential.', fix: { argv: ['gbrain', 'transcripts', 'audit-secrets', '--json'], consent: [], actor: 'agent', why: 'Lists conversation pages that still carry a credential with hit counts per pattern; changes no page.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'transcript_secret_exposure', '--json'] } } },
triage_unreliable_backoff: { class: 'retryable', summary: "Dream triage did not re-judge a transcript because its last judge verdict was truncated, refused or unparseable and its backoff has not ended.", why: 'An unreliable verdict is never cached, so without a backoff the same input was paid for every cycle; it waits 24h, doubling per repeat up to 7 days, and a content or triage-model change re-judges at once.', docs: 'docs/guides/error-codes.md#triage_unreliable_backoff', suggestion: 'Leave it (it is retried after the backoff), or ask the user before `gbrain dream retriage --force`, which re-judges every transcript now and pays per file.', fix: { argv: ['gbrain', 'dream', 'retriage', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the transcripts that still need a verdict without any judge call, read-only.', requires_exclusive: false } },
+ two_consumers_on_host: { class: 'host_only', summary: "Two resident gbrain processes on this host (`serve`, `sync`, `jobs`, `autopilot` or `mcp`) have each run a full persistence consumer for longer than 30 s, so both claim writes on the same roots.", why: "One full consumer per host is a preference, not a fenced role: a `serve` always starts full, every other resident kind defers to the first live full consumer it finds in `persistence_consumers`, and two processes that start within one renewal of each other, or a CLI that took its consumer before the `serve` started, both stay full until one exits. Every observed `preparing` wedge had two consumers alive on the host. Short-lived commands (`put`, `import`, `dream`, `cli`) and rows younger than 30 s are listed, never warned.", docs: 'docs/guides/troubleshooting.md#two-consumers-on-host', suggestion: 'Let the shorter-lived of the two finish (a sync CLI run ends on its own) or restart it so it defers; with persistence.single_consumer off, this is the configured behavior.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every consumer alive on this host (pid, kind, mode, started_at, pool) so you can see which one to let finish.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'two_consumers_on_host', '--json'] } } },
trusted_local_only: { class: 'host_only', summary: 'The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it.', legacy_error: 'permission_denied', suggestion: 'Ask the user to run the named gbrain command on the brain host.' },
unavailable: { class: 'unavailable', summary: "A required dependency or capability cannot serve this request." },
unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },
diff --git a/test/error-registry-6317-contract.test.ts b/test/error-registry-6317-contract.test.ts
new file mode 100644
index 0000000000..312ff4142f
--- /dev/null
+++ b/test/error-registry-6317-contract.test.ts
@@ -0,0 +1,179 @@
+/**
+ * #6317 (T-06): the managed sync reliability contract's codes carry the full
+ * agent-operator envelope. One contract case per code (`drain_stalled` with
+ * its new `owner_wedged_here` cause, `two_consumers_on_host`,
+ * `consumers_without_heartbeat`, `host_identity_mismatch`,
+ * `managed_sync_not_moving`): registered with class, exit code and
+ * `retryable`; `why` and a `fix` whose `next` derives per the v1 decision
+ * table and whose `verify` is read-only; a docs anchor that resolves; and the
+ * rendered CLI envelope an agent reads (`fix.argv` filled from the receipt's
+ * `source_id`). The scanner case proves `sources writer status|movement` are
+ * legal `fix.verify` commands while `sources writer claim` is not.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { CODES, codeEntry, codeRetryable, exitCodeForCode, type CodeEntry } from '../src/core/error-catalogue.ts';
+import { errorCodeRow } from '../src/core/error-docs.ts';
+import { cliRenderContext, deriveNext, renderAction, type RenderContext } from '../src/core/agent-output.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { envelopeFor } from './helpers/agent-envelope.ts';
+import { scan } from '../scripts/check-agent-contract.ts';
+
+const ROOT = join(import.meta.dir, '..');
+const CONTRACT_CODES: string[] = ['drain_stalled', 'two_consumers_on_host', 'consumers_without_heartbeat', 'host_identity_mismatch', 'managed_sync_not_moving'];
+const DOCTOR_CODES: string[] = ['two_consumers_on_host', 'consumers_without_heartbeat', 'host_identity_mismatch', 'managed_sync_not_moving'];
+
+function headingAnchor(heading: string): string {
+ return heading.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
+}
+function anchorsOf(path: string): Set<string> {
+ const text = readFileSync(join(ROOT, path), 'utf8').replace(/^```[\s\S]*?^```/gm, '');
+ const anchors = new Set<string>();
+ for (const [, heading] of text.matchAll(/^#{1,6}\s+(.+)$/gm)) anchors.add(headingAnchor(heading!));
+ for (const [, id] of text.matchAll(/<a id="([^"]+)"><\/a>/g)) anchors.add(id!);
+ return anchors;
+}
+const stdio: RenderContext = { transport: 'stdio', isCallable: () => false, preapproved: () => false };
+
+describe('#6317 codes are registered with a full envelope', () => {
+ test.each(CONTRACT_CODES)('%s: class, exit 1, not retryable, why, actor, fix with read-only verify, resolving docs anchor', (code: string) => {
+ const entry = codeEntry(code);
+ expect(entry, `${code} is not in src/core/error-registry.ts`).toBeDefined();
+ expect(['server', 'host_only']).toContain(entry!.class);
+ expect(exitCodeForCode(code)).toBe(1);
+ expect(codeRetryable(code)).toBe(false);
+ expect(entry!.why?.length ?? 0).toBeGreaterThan(80);
+ expect(entry!.summary.endsWith('.')).toBe(true);
+ expect(entry!.fix).toBeDefined();
+ expect(entry!.fix!.argv?.[0]).toBe('gbrain');
+ expect(entry!.fix!.consent).toEqual([]);
+ expect(entry!.fix!.verify?.argv?.[0]).toBe('gbrain');
+ expect(entry!.fix!.why.length).toBeGreaterThan(20);
+ const [path, anchor] = entry!.docs.split('#');
+ expect(path).toMatch(/^docs\/guides\/(write-refusals|troubleshooting)\.md$/);
+ expect(anchorsOf(path!).has(anchor!), `${code}: ${entry!.docs} does not resolve`).toBe(true);
+ const row = errorCodeRow(code)!;
+ expect(['agent', 'host_admin']).toContain(row.actor);
+ expect(row.verify).toStartWith('gbrain ');
+ expect(row.effects).toEqual([]);
+ });
+
+ test('the generated catalogue (docs/guides/error-codes.md) has a section per code', () => {
+ const doc = readFileSync(join(ROOT, 'docs/guides/error-codes.md'), 'utf8');
+ for (const code of CONTRACT_CODES) expect(doc).toContain(`<a id="${code}"></a>`);
+ });
+
+ test('every doctor-check code points its fix.verify at its own doctor check, so an agent closes the loop with one read', () => {
+ for (const code of DOCTOR_CODES) {
+ const entry = (CODES as Record<string, CodeEntry>)[code]!;
+ expect(entry.fix!.verify!.argv).toEqual(['gbrain', 'doctor', '--only', code, '--json']);
+ const rendered = renderAction(entry.fix!, cliRenderContext());
+ expect(rendered.verify?.argv).toEqual(['gbrain', 'doctor', '--only', code, '--json']);
+ expect(rendered.command).toStartWith('gbrain ');
+ }
+ });
+
+ test('fix.next follows the v1 decision table: agent fixes run on the CLI and relay over stdio; the host_admin fix relays everywhere', () => {
+ const agentCodes = CONTRACT_CODES.filter(code => (CODES as Record<string, CodeEntry>)[code]!.fix!.actor === 'agent');
+ expect(agentCodes.length).toBeGreaterThanOrEqual(4);
+ for (const code of agentCodes) {
+ const fix = (CODES as Record<string, CodeEntry>)[code]!.fix!;
+ expect(deriveNext(fix, cliRenderContext())).toBe('run');
+ expect(deriveNext(fix, stdio)).toBe('tell_user_to_run');
+ }
+ const host = (CODES.host_identity_mismatch as CodeEntry).fix!;
+ expect(host.actor).toBe('host_admin');
+ expect(deriveNext(host, cliRenderContext())).toBe('tell_user_to_run');
+ // `wait` is reachable only through actor `provider` (agent-output.ts deriveNext row 2): a wedged owner on this host is not a
+ // provider, so a registry default can never say `wait`; the drain's own stop envelope carries `retry_after_ms` instead.
+ expect(deriveNext({ ...host, actor: 'provider' }, cliRenderContext())).toBe('wait');
+ });
+});
+
+describe('drain_stalled: the same-host stop has a cause vocabulary and a filled writer-status fix', () => {
+ test('owner_wedged_here is a registered reason beside the earlier causes, and the row says what changed', () => {
+ const entry = CODES.drain_stalled as CodeEntry;
+ expect(entry.reasons).toEqual(['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress']);
+ expect(entry.why).toContain('owner_wedged_here');
+ expect(entry.why).toContain('retry_after_ms');
+ expect(entry.why).not.toContain('nothing here can claim it');
+ expect(entry.docs).toBe('docs/guides/write-refusals.md#drain-stalled');
+ });
+
+ test('the rendered CLI envelope fills --source from the receipt and names the owner in why', () => {
+ const error = new OperationError('drain_stalled', 'Managed sync of source default stopped: the head write is held by gbrain serve (pid 4121) past the preparation ceiling.');
+ error.reason = 'owner_wedged_here';
+ error.why = 'gbrain serve (pid 4121, nonce 7f3a) on this host has held request 01J9 at step import_screen for 660 s; the ceiling has passed, so only a restart of that process frees the root.';
+ error.receiptFields = { operation: 'managed_sync_import', source_id: 'default', slug: null, principal_kind: 'cli', principal_id: 'local_cli' };
+ const env = envelopeFor(error, 'cli');
+ expect(env).toMatchObject({ code: 'drain_stalled', reason: 'owner_wedged_here', class: 'server', retryable: false, contract_version: 1 });
+ expect(env.why).toContain('pid 4121');
+ expect(env.fix?.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json']);
+ expect(env.fix?.next).toBe('run');
+ expect(env.fix?.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json']);
+ expect(env.docs).toContain('docs/guides/write-refusals.md#drain-stalled');
+ expect(env.docs_cmd).toEqual(['gbrain', 'errors', 'drain_stalled']);
+ expect(env.suggestion).toContain('gbrain sources writer status --source default --json');
+ });
+
+ test('the write-refusals row and the live-sync outcome table carry the new meaning, not the old one', () => {
+ const refusals = readFileSync(join(ROOT, 'docs/guides/write-refusals.md'), 'utf8');
+ const row = refusals.split('\n').find(line => line.includes('<a id="drain-stalled"></a>'))!;
+ expect(row).toContain('owner_wedged_here');
+ expect(row).toContain('retry_after_ms');
+ expect(row).toContain('safe_to_loop: true');
+ expect(row).not.toContain('nothing on this host can claim it');
+ const liveSync = readFileSync(join(ROOT, 'docs/guides/live-sync.md'), 'utf8');
+ expect(liveSync).toContain('| `blocked` / `drain_stalled` | 1 |');
+ expect(liveSync).toContain('### One consumer per host');
+ expect(liveSync).toContain('persistence.single_consumer');
+ expect(liveSync).toContain('--no-delegate');
+ });
+});
+
+describe('the doctor codes each have a troubleshooting symptom row that names who acts, consent and a verify step', () => {
+ const doc = readFileSync(join(ROOT, 'docs/guides/troubleshooting.md'), 'utf8');
+ const rows = doc.split('\n').filter(line => line.startsWith('| [') || line.startsWith('| `') || line.startsWith('| A ') || line.startsWith('| The '));
+ test.each([...DOCTOR_CODES, 'owner_wedged_here'])('%s', (code: string) => {
+ const row = rows.find(line => line.includes(code) && line.split(' | ').length >= 5);
+ expect(row, `no symptom row names ${code}`).toBeDefined();
+ const cells = row!.split(' | ');
+ expect(cells[2]!.length).toBeGreaterThan(10);
+ expect(cells[3]!.length).toBeGreaterThan(3);
+ expect(cells[4]!).toContain('gbrain ');
+ });
+
+ test('the parked-catch-up section is a two-call journey and the transcript names each step', () => {
+ expect(doc).toContain('<a id="managed-sync-not-moving"></a>');
+ expect(doc).toContain('<a id="managed-sync-wedge-transcript"></a>');
+ for (const step of ['gbrain sources status default --json', 'gbrain doctor --only managed_sync_not_moving --json', 'gbrain sources writer status --source default --json', 'gbrain sources retry-held default', 'gbrain sources writer movement default']) {
+ expect(doc, `transcript lacks ${step}`).toContain(step);
+ }
+ expect(doc).toContain('"next_action"');
+ expect(doc).toContain('cause=owner_wedged_here');
+ expect(doc).not.toContain('budget times its attempts');
+ });
+});
+
+describe('the contract scanner accepts writer status and movement as read-only verify steps', () => {
+ test('sources writer status|movement pass; sources writer claim is still flagged', () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-6317-scanner-'));
+ try {
+ mkdirSync(join(root, 'src'), { recursive: true });
+ mkdirSync(join(root, 'baselines'), { recursive: true });
+ writeFileSync(join(root, 'src', 'fixes.ts'), [
+ "export const ok1 = { fix: { argv: ['gbrain', 'doctor'], consent: [], actor: 'agent', why: 'w', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json'] } } };",
+ "export const ok2 = { fix: { argv: ['gbrain', 'doctor'], consent: [], actor: 'agent', why: 'w', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'writer', 'movement', 'default'] } } };",
+ "export const ok3 = { fix: { argv: ['gbrain', 'doctor'], consent: [], actor: 'agent', why: 'w', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'status', 'default', '--json'] } } };",
+ "export const bad = { fix: { argv: ['gbrain', 'doctor'], consent: [], actor: 'agent', why: 'w', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'writer', 'claim', 'default'] } } };",
+ '',
+ ].join('\n'));
+ const hits = scan(root).filter(h => h.rule === 'verify-not-read-only');
+ expect(hits.map(h => h.line)).toEqual([4]);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});