Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
404 KB
Raw Blame
/**
 * The error code registry (agent operator contract v1, A2). Every literal
 * code thrown in `src/` has one entry here: its class (which derives the CLI
 * exit code and `retryable`), a one-sentence meaning, and optionally a
 * default suggestion, a default fix (diagnostic reads only), reasons, a docs
 * anchor and the frozen legacy wire value. `docs/guides/error-codes.md` is
 * generated from this table (`bun run build:error-codes`), and
 * `test/error-catalogue.test.ts` walks the source AST so an unregistered code
 * fails CI.
 *
 * Adding a code: add one entry (snake_case, no transport prefix), then run
 * `bun run build:error-codes`. Entries default their docs to
 * `docs/guides/error-codes.md#<code>`.
 */
import type { Action, Actor, Effect, ErrorClass } from './agent-output.ts';
import { FENCE_REASON_CODES } from './fence-repair/reasons.ts';
import { ENGINE_CAPABILITIES } from './engine-capabilities.ts';

export interface CodeEntry {
  class: ErrorClass;
  /** What happened, one sentence. */
  summary: string;
  /** Why it happens / what it protects. */
  why?: string;
  /** Closed vocabulary for `reason` when one code covers several causes. */
  reasons?: readonly string[];
  /**
   * Tombstones of reasons nothing emits any more (reason → the release that retired it); a receipt an older build wrote may
   * still carry one, so it stays explained here, and it never returns to `reasons`.
   */
  retired_reasons?: Readonly<Record<string, string>>;
  /**
   * A reason whose next step differs in kind from the code's (a lock that waiting never frees needs the user, not a retry):
   * its class and exit replace the code's on the envelope and the CLI exit. Every key is also in `reasons`.
   */
  reason_overrides?: Readonly<Record<string, { class: ErrorClass; exit?: number }>>;
  /** Repo-relative anchor; default `docs/guides/error-codes.md#<code>`. */
  docs?: string;
  /** Default prose suggestion when a site supplies none. */
  suggestion?: string;
  /**
   * Default fix template: read-only diagnostics only (scanner-checked).
   * `{slug}`, `{source_id}`, `{request_id}`, `{operation}` placeholders are
   * filled from envelope/receipt fields at render time; an unfillable
   * template is dropped, never rendered with a placeholder.
   */
  fix?: Action;
  effects?: readonly Effect[];
  actor?: Actor;
  /** The code this one replaced (documented in error-codes.md "Legacy `error` values"). */
  renamed_from?: string;
  /** Frozen v1 `error` wire value some sites keep for this canonical code. */
  legacy_error?: string;
  /** CLI exit code; default derives from class (1). */
  exit?: number;
  retryable?: boolean;
  /**
   * The release that retired this code: nothing emits it any more, but receipts and ledger rows an older build wrote still
   * carry it, so the entry stays and `gbrain errors <code>` still answers. Its fix names the current path, never a retired
   * key or flag (`test/error-registry-retired.test.ts`).
   */
  retired_in?: string;
}

export const CODES = {
  absent_from_worktree: { class: 'caller', retryable: false, reasons: ['skip_worktree', 'deleted_locally'], summary: "Sync held one file that is committed at HEAD but missing from the working tree (a sparse checkout or a skip-worktree bit, or a local deletion that is not committed); the rest of the source synced.", why: "Sync imports from the working tree, so it cannot import a file that is not on disk, and treating it as deleted would drop a committed file silently. Whether the file comes back or its deletion is committed is the user's choice; classic sync re-screens the hold on every run.", docs: 'docs/guides/write-refusals.md#absent_from_worktree', suggestion: 'Restore the file (git restore -- <path>, or widen the sparse checkout) and the next sync imports it; or commit the deletion with gbrain git commit-push -m <msg> -- <path> and the next sync clears the hold.' },
  apple_full_disk_access_pending: { class: 'caller', actor: 'user', summary: "GBrain Helper is running but cannot read Messages because Full Disk Access is off for it, so nothing was imported.",
    why: 'macOS lets an app read the Messages database only after the user switches it on in System Settings; only the user can do that, and a grant can be turned off again later.',
    docs: 'docs/guides/apple-setup.md#apple_full_disk_access_pending',
    suggestion: 'Ask the user to open System Settings > Privacy & Security > Full Disk Access and switch on GBrain Helper, then run gbrain sync --source <id>.' },
  apple_helper_not_running: { class: 'caller', actor: 'user', summary: "Nothing answered on the GBrain Helper's loopback port (the helper is stopped, the Mac is asleep, or apple.helper.port is not set), so nothing was imported.",
    why: 'An imessage source reads only from the helper on the same Mac over 127.0.0.1; it never opens the Messages database itself.',
    docs: 'docs/guides/apple-setup.md#apple_helper_not_running',
    suggestion: 'Start GBrain Helper on this Mac and check gbrain config get apple.helper.port names its port, then run gbrain sync --source <id>.' },
  apple_helper_unauthorized: { class: 'caller', actor: 'user', summary: "GBrain Helper refused the token gbrain sent, or gbrain has no helper token, so nothing was imported.",
    why: 'The helper answers only a request that carries one of its own tokens with the read:imessage scope; the token is read from the source\'s --token-env variable when it names one, else GBRAIN_CONNECTOR_IMESSAGE_TOKEN, else the 0600 file ~/.gbrain/connectors/imessage.json.',
    docs: 'docs/guides/apple-setup.md#apple_helper_unauthorized',
    suggestion: "Save the helper's current token where GBrain reads it, then run gbrain sync --source <id>." },
  apple_schema_mismatch: { class: 'caller', summary: "GBrain Helper does not recognise the layout of the Messages database (macOS may have changed it), so nothing was imported.",
    why: 'The helper reads only the tables and columns it knows; it refuses a changed database rather than guess at it.',
    docs: 'docs/guides/apple-setup.md#apple_schema_mismatch',
    suggestion: 'Update GBrain and the GBrain Helper to their newest versions, then run gbrain sync --source <id>.' },
  access_command_failed: { class: 'caller', summary: "Google connect credential error: access command failed.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  access_identity_unavailable: { class: 'retryable', actor: 'provider', summary: "The member a credential (access token, OAuth client or stdio binding) is bound to could not be looked up, so the request was refused and nothing was read or written.", why: "Reading the binding failed with a database error, or with a lock or statement timeout or a dropped connection while the request was submitted. Reading the credential as unbound instead would open every unlabelled page to a labelled-only member, so the request stops, and the same request succeeds once the database answers.", docs: 'docs/guides/write-refusals.md#access_identity_unavailable', suggestion: 'Retry the same request in a few seconds (a write with the same request_id); if it keeps failing, ask the brain operator to run gbrain doctor --json on the brain host.', fix: { argv: ['gbrain', 'whoami', '--json'], consent: [], actor: 'provider', requires_exclusive: false, why: 'Read-only: after a few seconds whoami reads the binding again and shows the member this connection reads as; then repeat the original request.', verify: { argv: ['gbrain', 'whoami', '--json'] } } },
  access_member_disabled: { class: 'host_only', actor: 'user', reasons: ['disabled', 'removed', 'missing', 'malformed'], summary: "The credential (access token, OAuth client or stdio binding) is bound to a member who is disabled, removed or missing, so it was refused at verification and nothing was read.", why: 'A credential bound to a member reads as that member. While the member cannot read, the credential is refused rather than silently treated as unbound.', docs: 'docs/guides/write-refusals.md#access_member_disabled', suggestion: 'Ask the brain operator to enable the member (gbrain access member enable <id>) or rebind the credential (gbrain auth rescope --token <name>|--client <id> --member <id>|none).' },
  archive_audience_unproven: { class: 'retryable', retryable: true, summary: "The conversation archive could not check whether the brain is shared (its client-usage read failed), so it wrote nothing this run.", why: 'A brain with no audience declared counts as shared when several clients use it; without that read a page written as personal could be open to other members, so the run publishes nothing.', docs: 'docs/guides/conversation-archive.md#privacy', suggestion: 'Rerun gbrain transcripts archive run; if it repeats, declare the audience with gbrain config set brain.audience personal|shared.' },
  archive_gateway_unreachable: { class: 'retryable', retryable: true, summary: "The conversation archive could not reach the OpenClaw Gateway, so no OpenClaw conversation was read this run; the archive ledger is unchanged, so the next run retries safely.", why: "Current OpenClaw keeps live sessions in SQLite owned by its Gateway, and gbrain reads them only through the Gateway's documented RPCs (openclaw gateway call), never the file.", docs: 'docs/guides/conversation-archive.md#openclaw', suggestion: 'Start the Gateway (openclaw gateway) or point gbrain at it with GBRAIN_OPENCLAW_GATEWAY_URL, then rerun gbrain transcripts archive run.', fix: { argv: ['gbrain', 'transcripts', 'archive', 'status', '--json'], consent: [], actor: 'agent', why: 'Shows each harness the archive reads, the last error per reader and the held days, read-only.', requires_exclusive: false } },
  archive_gateway_auth: { class: 'host_only', actor: 'user', summary: "The OpenClaw Gateway refused the credential the conversation archive used, so no OpenClaw conversation was read this run; the archive ledger is unchanged.", why: 'The Gateway token or device pairing belongs to the user; gbrain never mints or edits one.', docs: 'docs/guides/conversation-archive.md#openclaw', suggestion: 'Ask the user to give gbrain the Gateway token (GBRAIN_OPENCLAW_GATEWAY_TOKEN, or gateway.auth in the OpenClaw config on this machine), then rerun gbrain transcripts archive run.', fix: { argv: ['gbrain', 'transcripts', 'archive', 'status', '--json'], consent: [], actor: 'agent', why: 'Shows the reader error and the held days, read-only.', requires_exclusive: false } },
  archive_gateway_failed: { class: 'retryable', retryable: true, summary: "The OpenClaw Gateway answered the conversation archive with an error, so no OpenClaw conversation was read this run; the archive ledger is unchanged.", docs: 'docs/guides/conversation-archive.md#openclaw', suggestion: 'Rerun gbrain transcripts archive run; if it repeats, report the redacted message from gbrain transcripts archive status --json.', fix: { argv: ['gbrain', 'transcripts', 'archive', 'status', '--json'], consent: [], actor: 'agent', why: 'Shows the reader error, read-only.', requires_exclusive: false } },
  archive_owner_unset: { class: 'host_only', actor: 'user', summary: "On a shared brain the conversation archive held every day and wrote nothing, because no owner member is named and an archive page without readable_by would be open to the whole source.", docs: 'docs/guides/conversation-archive.md#privacy', suggestion: 'Ask the user which enabled member owns the brain, run gbrain access owner set <member>, then rerun the archive; held days are written then.', fix: { argv: ['gbrain', 'access', 'owner'], consent: [], actor: 'agent', why: 'Shows whether an owner member is named, read-only.', requires_exclusive: false } },
  archive_redaction_failed: { class: 'retryable', retryable: true, summary: "Redaction failed for a conversation, so the conversation archive held its days instead of writing them; the next run retries them.", why: 'Archive pages are written only after redaction succeeded over the whole session; a day is never written unredacted and never dropped.', docs: 'docs/guides/conversation-archive.md#privacy', suggestion: 'Rerun gbrain transcripts archive run; if the day stays held, check the user redaction pattern file named in the held message.', fix: { argv: ['gbrain', 'transcripts', 'archive', 'status', '--json'], consent: [], actor: 'agent', why: 'Lists held days with their codes, read-only.', requires_exclusive: false } },
  archive_run_busy: { class: 'retryable', retryable: true, summary: "Another conversation archive run holds this source, so this run read and wrote nothing.", why: 'A run decides each day from the archive ledger it read when it started, so two runs at once could publish older history over newer; runs on one source take turns on a database lease.', docs: 'docs/guides/conversation-archive.md#openclaw', suggestion: 'Wait for the other run to finish, then rerun gbrain transcripts archive run.', fix: { argv: ['gbrain', 'status', '--section', 'locks', '--json'], consent: [], actor: 'agent', why: 'Shows which process holds the archive lease and when it expires, read-only.', requires_exclusive: false } },
  autopilot_no_repo: { class: 'caller', summary: "gbrain autopilot --install found no absolute repo directory (sync.repo_path and the default source's local_path are unset or relative), so it installed nothing.", why: 'The autopilot daemon syncs a git checkout. A repo-less brain needs no daemon: free upkeep (gbrain maintain --unattended) keeps it maintained.', suggestion: 'Pass --repo <absolute-directory> for a brain kept in git, or check free upkeep with gbrain maintain --status.' },
  autopilot_pglite_daemon: { class: 'caller', summary: 'gbrain autopilot --install refused on a PGLite brain: a daemon would hold the single-writer lock all day and block every other gbrain process.', why: 'PGLite has one writer. gbrain serve owns the lock and runs the resident sweep; free upkeep runs through gbrain maintain --unattended.', suggestion: 'Run gbrain serve. Check upkeep with gbrain maintain --status. For a dedicated-brain daemon, re-run gbrain autopilot --install --force.' },
  cycle_already_running: { class: 'retryable', summary: 'Another maintenance cycle holds the brain cycle lock, so this run skipped instead of waiting.', why: 'Cycles serialize on the gbrain-cycle lease; the holder releases it when it finishes (or its TTL lapses after a crash).', suggestion: 'Wait for the other cycle; unattended upkeep retries on its next turn (gbrain maintain --status shows the last skip).' },
  engine_degraded: { class: 'unavailable', summary: 'The brain database was unreachable (the engine is in degraded mode), so background work such as unattended upkeep skipped this run.', why: 'A degraded engine answers from its last state and reconnects on its own; writing maintenance results then would be lost or refused.', suggestion: 'Run gbrain doctor --json and report the connection problem it names.' },
  rust_engine_addon_missing: { class: 'unavailable', actor: 'user', retryable: true, reasons: ['unsupported_target', 'not_installed', 'override_not_found'], summary: 'The Rust engine is selected (engine: rust), but no addon for this gbrain release is installed on this machine, or no addon is published for this platform, so gbrain opened nothing and wrote nothing.', why: 'The Rust engine ships as a separate addon file kept in the gbrain home, checked against the checksum in this release\'s manifest before it loads. Without a checked addon the engine cannot open, and gbrain refuses before touching the brain.', suggestion: 'Point GBRAIN_RUST_ENGINE_ADDON at an addon you built with bun run rust:build, or switch engine in the gbrain config back to pglite or postgres.' },
  rust_engine_addon_mismatch: { class: 'unavailable', actor: 'user', retryable: false, reasons: ['digest', 'engine_abi', 'engine_build', 'target', 'load_failed'], summary: 'The Rust engine addon on this machine does not match what this gbrain release expects (checksum, engine_abi, engine_build or target), so it was not used and gbrain wrote nothing.', why: 'A different addon build could read or write the brain with a different on-disk format, so only the addon the running release names, with the checksum in its manifest, is loaded. A file that fails the check is left as it was.', suggestion: 'Rebuild the addon with bun run rust:build and point GBRAIN_RUST_ENGINE_ADDON at the path it prints, or install the gbrain release that matches the addon, or switch engine in the gbrain config back to pglite or postgres.' },
  maintenance_disabled: { class: 'caller', exit: 0, summary: 'Free unattended upkeep is off on this brain (maintenance.auto is false), so nothing ran.', why: 'The person turned upkeep off; doctor reads it as off, not stale.', suggestion: 'Turn it back on with gbrain config set maintenance.auto true.' },
  maintenance_owned_by_serve: { class: 'caller', exit: 0, summary: 'A live gbrain serve owns this brain and runs free upkeep while idle, so the scheduled upkeep run did nothing (serve owns upkeep).', why: 'One runner at a time: the serve holds the brain (the PGLite lock, or the warm CLI socket on Postgres) and runs the same free upkeep on its idle tick.', suggestion: 'Nothing to do; gbrain maintain --status shows the last run and its runner.' },
  schedule_unsupported: { class: 'caller', reasons: ['windows', 'container', 'mount'], summary: 'gbrain maintain --schedule installed nothing: on Windows and in containers it has no installer, and it schedules the host brain only.', why: 'Windows gets the schtasks line to add by hand (minimal Windows support). In a container an operating-system schedule does not survive a redeploy, so the resident gbrain serve is the upkeep runner there. The scheduled job runs without --brain, so a mounted brain gets no schedule.', suggestion: 'On Windows, add the printed schtasks line yourself. In a container, keep gbrain serve running; it runs free upkeep while idle. For a mounted brain, schedule gbrain --brain <id> maintain --unattended yourself.' },
  schedule_install_failed: { class: 'host_only', retryable: false, actor: 'user', summary: 'gbrain maintain --schedule wrote its files, but the operating-system scheduler (launchctl, systemctl --user or crontab) refused the job.', why: 'The scheduler belongs to the host: a missing user session bus, a locked crontab or a launchd error stops the job from loading.', suggestion: 'Read the scheduler error in the message, fix it on the host, then run gbrain maintain --schedule --yes again (gbrain maintain --unschedule removes the files).' },
  maintenance_owned_by_autopilot: { class: 'caller', exit: 0, summary: 'An autopilot keeps this brain maintained (its brain-wide pass stamped autopilot.last_global_at within 48 hours), so free upkeep did nothing.', why: 'One owner per brain: the autopilot already runs the free phases and more, on any host sharing the database.', suggestion: 'Nothing to do; gbrain autopilot --status shows the daemon.' },
  on_behalf_of_invalid_audience: { class: 'caller', summary: "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', suggestion: 'Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.' },
  on_behalf_of_unknown_member: { class: 'caller', summary: "A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read.", why: 'An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads.', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member', suggestion: 'Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest.' },
  on_behalf_of_not_permitted: { class: 'host_only', actor: 'user', summary: "A shared agent asserted an audience its credential's may_act_for does not list (for a stdio server, config mcp.stdio_may_act_for), so nothing was read.", why: 'A shared agent acts only for the people the brain operator approved for its credential; widening that list is the operator\'s decision, never the agent\'s.', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted', suggestion: 'The brain operator decides whether to approve the audience: gbrain auth rescope --token <name>|--client <id> --may-act-for <list> on the brain host. Until then, call without the audience.' },
  actor_not_attested: { class: 'host_only', actor: 'user', reasons: ['no_attest_right', 'op_not_attested', 'argument_mismatch', 'argument_without_attestation', 'invalid_actor_id', 'actor_required', 'audience_not_supported'], summary: "A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header, names anyone but a member-bound credential's own member, or comes without an attested header from a credential bound to no member, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none; or the request carries x-qm-audience, a channel audience gbrain does not serve yet. Nothing was read or written.", why: 'Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it.', docs: 'docs/guides/write-refusals.md#actor_not_attested', suggestion: 'Read reason: no_attest_right and op_not_attested are the brain operator\'s call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id, actor_required and audience_not_supported are fixed in the calling harness.' },
  actor_unlinked: { class: 'host_only', actor: 'user', summary: 'An attested call named a person whose canonical id is not linked to an enabled member of this brain (never linked, unlinked, or the member is disabled or removed), so nothing was read or written.', why: 'An attested call reads and writes as exactly one member; an unknown person is refused rather than read as a guest, and unlinking or disabling takes effect on the next call.', docs: 'docs/guides/write-refusals.md#actor_unlinked', suggestion: 'The brain operator links the id to its member: gbrain access member link <member> --qm <id> (or enables the member).' },
  on_behalf_of_in_arguments: { class: 'caller', summary: 'A tool call carried on_behalf_of inside its arguments, where conversation text could set it, so it was refused and nothing was read.', why: 'Only harness code may name whose notes a shared agent reads: the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of, never tool arguments.', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments', suggestion: 'Remove on_behalf_of from the tool arguments. Harness code sends it as the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of; other stdio clients use a credential bound to one member or config mcp.stdio_member.' },
  access_policy_invalid: { class: 'host_only', actor: 'user', docs: 'docs/guides/write-refusals.md#access_policy_invalid', summary: "A source's folder-rule policy (the committed .gbrain/access.yml, or a file given to gbrain access rule import) does not validate, so it was not applied: the last applied rules stay in force and every prefix the bad file names reads as nobody (the whole source when its prefixes cannot be read).", why: 'A typo in an access file must never open a folder: an unreadable revision keeps the previous rules and hides what it touches until it is fixed.', suggestion: 'Show each problem with its line (gbrain access rule list --source <id>). Fix the file, commit it with gbrain git commit-push and sync the source (gbrain sync --source <id> --no-pull).', fix: { argv: ['gbrain', 'access', 'rule', 'list', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the applied rules and each problem in the policy file with its line; changes nothing.' } },
  access_policy_pending: { class: 'retryable', docs: 'docs/guides/write-refusals.md#access_policy_pending', summary: "A narrowing change to a source's folder rules is still being applied to its pages, so the prefixes it touches read as nobody until it finishes; pages under other prefixes keep the last applied rules.", why: 'Pages under a newly restricted folder are restamped in batches; until the last batch and its re-check pass land, they read as nobody instead of under the old rules.', suggestion: 'Retry shortly. If it stays pending, the apply was interrupted: the brain host finishes it with gbrain access resume --source <id> (database store); a git store finishes with gbrain sync --source <id> --no-pull.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the pending prefixes and the revision being applied; changes nothing.' } },
  access_policy_widening_held: { class: 'consent', actor: 'user', summary: "A change to a source's folder rules widens who may read (a rule removed, readers added, the old folder of a moved prefix), so it is recorded but held: the previous rules stay in force until an operator previews it with gbrain access apply --source <id> and approves the printed plan with --yes --expect <plan_hash> on the brain host.", why: 'Write access to the policy (a git commit or a rule edit) must not be enough to open a folder; widening needs a host-side preview and an explicit approval.', suggestion: 'Ask the user whether to approve the widening; the brain host previews it with gbrain access apply --source <id>.', fix: { argv: ['gbrain', 'access', 'apply', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the held widening (pages and members gaining access) and prints the plan hash an approval binds; changes nothing.' } },
  access_policy_history_unreadable: { class: 'host_only', actor: 'user', summary: "A folder-rule edit on a git-backed source with no folder-rule revision yet was refused before anything was written: the first sync after it rebuilds the rules from the committed history of .gbrain/access.yml, and this checkout cannot give that history (a shallow clone, or a partial clone that lacks its Git objects), so that sync would read the whole source as nobody.", why: 'A rebuild replays every committed version of the policy file so a narrowing removed by a plain commit stays applied; without the full history it can only fail closed, so the edit refuses up front and the source keeps its current reads.', suggestion: 'In the checkout, fetch the full history (git fetch --unshallow) or the missing objects of a partial clone, then run the same gbrain access rule command again.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the store and the applied rules of the source; changes nothing.' } },
  access_policy_store_mismatch: { class: 'host_only', actor: 'user', summary: "A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own.", why: 'Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens.', suggestion: 'On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the persisted store and the applied rules; changes nothing.' } },
  access_rule_invalid: { class: 'caller', docs: 'docs/guides/write-refusals.md#access_rule_invalid', summary: 'A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written.', why: 'Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none.', suggestion: 'Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>.' },
  requester_scope_required: { class: 'host_only', actor: 'user', reasons: ['grace_ended', 'created_after', 'since_unknown'], docs: 'docs/guides/write-refusals.md#requester_scope_required', summary: 'A remote read came from a connection bound to no member (an access token, an OAuth client or a local stdio server) on a brain that serves several people (two or more enabled members, or config access.serves = several), so it was refused before any work and nothing was read.', why: 'On a brain that serves several people a connection bound to nobody reads every page no rule restricts, for whoever is asking; gbrain refuses rather than guess whose notes a read is for. A connection that existed when the brain started serving several people gets 14 days of in-band notices first (reason grace_ended); one created after that is refused at once (created_after).', suggestion: 'On the brain host, bind the connection to the person it serves: gbrain auth rescope --token <name>|--client <id> --member <id> (preview with gbrain access check --token <name>); for a stdio server, when only one person uses that harness, gbrain setup claude-code --stdio-member <id> (gbrain setup codex --stdio-member <id> on Codex), which binds that one harness entry on that machine (refused where OpenClaw or Hermes is installed); for a harness several people talk to, give each person a key over HTTP instead (gbrain serve --http with gbrain auth create <name> --member <id> keys). A shared agent lists whom it may act for (--may-act-for) and names the person on each call. Last resort: --reads-unscoped --yes lets that one credential read every page no rule restricts for any asker.' },
  requester_scope_unknown: { class: 'retryable', retryable: true, actor: 'provider', docs: 'docs/guides/write-refusals.md#requester_scope_unknown', summary: 'A remote read came from a connection bound to no member, and the brain\'s settings (whether it serves one person or several) could not be read: the config read failed, and so did one re-read. The call was not answered and nothing was read; this is not an access decision, and the same call can succeed once the database answers.', why: 'A statement timeout, a lock wait or a dropped pooled connection can fail one config read while the next read succeeds. Reading that as a one-person brain would let a connection bound to nobody read every page no rule restricts on a brain that may serve several people, so gbrain refuses until it can tell.', suggestion: 'Retry the same call in a few seconds. If it keeps failing, the brain host\'s operator checks the database with gbrain doctor --json. A connection bound to a member is never refused this way.' },
  credential_scope_required: { class: 'caller', docs: 'docs/guides/write-refusals.md#credential_scope_required', summary: 'gbrain auth create or gbrain auth register-client was asked for a credential bound to no member on a brain that serves several people, so nothing was created.', why: 'A credential bound to nobody on such a brain is refused on every read (requester_scope_required); creating one would hand out a key that cannot work, or one that reads everyone\'s unmarked notes.', suggestion: 'Bind it to the person it serves: gbrain auth create <name> --member <id> (gbrain access member list names the members). A shared agent passes --may-act-for <members> instead; --reads-unscoped --yes creates one that reads every page no rule restricts for any asker, on purpose.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the members a credential can be bound to.' } },
  access_serves_roster_empty: { class: 'caller', summary: 'gbrain setup --serves several or gbrain access serves several was given no people (no --members, an empty --members-file), so nothing was written.', why: 'Each person gets a member, a folder only they read and a key bound to them; the installer never guesses who they are.', suggestion: 'Name every person: --members alice-example,bob-example, or --members-file <file> with one id per line.' },
  access_serves_key_dir_in_git: { class: 'caller', summary: 'The directory the per-member keys would be written to is inside a git work tree, so no key, member or rule was written.', why: 'Key files hold live credentials; a file inside a checkout can be committed and pushed.', suggestion: 'Point GBRAIN_HOME at a directory outside any git checkout (the default is your home directory) and run the command again.' },
  repair_propose_dir_in_git: { class: 'caller', docs: 'docs/guides/repair.md#propose-readers', summary: 'gbrain repair visibility --propose was pointed at a directory inside a git work tree for its slugs files, so nothing was written.', why: 'The slugs files list page slugs and who would read them; a file inside a checkout can be committed and pushed.', suggestion: 'Pass --out <dir> outside any git checkout, or leave --out off to use the gbrain config directory (with GBRAIN_HOME outside any checkout).' },
  access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },
  access_labelled_only_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A labelled-only grant was asked for on the brain owner (gbrain access member labelled-only <owner> on), or a labelled-only member was named the owner (gbrain access owner set), so nothing was changed.", why: "The owner reads the whole brain. A labelled-only grant hides every page that does not name its member, so on the owner it would silently hide the owner's own brain from every credential bound to it.", suggestion: 'Ask the user which member the group or audience credential should read as; give it its own member and mark that one labelled-only, or clear the grant before naming the owner.' },
  access_labelled_only_unnamed: { class: 'caller', summary: "A credential whose member is labelled-only tried to create a page that would not name it: the page has no readable_by holding the member or one of its groups, and no folder or page rule over its slug lists them, so nothing was written.", why: 'A labelled-only member reads only pages labelled for it, so a page it creates must name it; otherwise it would write a page it could never read back, readable by every other caller its source admits.', suggestion: 'Add readable_by naming the member or one of its groups to the frontmatter (readable_by: [alice-example, group:team-a]), or ask the brain operator to add a folder rule over the path that lists it, then submit again with a new request_id.' },
  access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group', 'invalid_external_id', 'link_exists', 'unknown_link', 'invalid_email', 'email_taken', 'email_ambiguous'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, or a declared member email is invalid, taken or ambiguous, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },
  access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },
  admin_policy_enforced: { class: 'host_only', summary: "Google connect credential error: admin policy enforced.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  admission_paused: { class: 'host_only', summary: "`sync.admission` is not `normal`, so a managed sync's destructive write (a delete or a keep_db DB-wins reconcile) was not admitted, or was cancelled before it published; nothing was written.", why: "`sync.admission` (`imports_only` or `classify_only`) is the brain-wide switch that pauses what managed sync writes. It is read when the pass pins, inside every admission transaction and again when a destructive write publishes, so a change takes effect at the next group and no destructive write lands after it.", suggestion: 'Restore admission with `gbrain config set sync.admission normal` when the pause is no longer wanted; the next plain sync admits the paused paths again.', fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Shows the admission switch and what the newest pass paused, read-only.', requires_exclusive: false } },
  ambient_capture_off: { class: 'caller', summary: "memory.auto_writeback no longer allows this ambient capture lane, so facts extracted from captured session text were dropped before admission.", why: "An explicit off (or an incoherent setting) applies to every capture-lane fact request admitted after the change, including one whose provider call was already in flight; requests admitted earlier still publish.", docs: 'docs/guides/ambient-writeback.md#capture-lanes-and-the-off-switch' },
  ambiguous_id: { class: 'caller', summary: "The legacy id matches multiple readable pages." },
  ambiguous_ref: { class: 'caller', summary: "A page reference in a rating matches pages in more than one source of that answer.", docs: 'docs/guides/retrieval-feedback.md#ambiguous_ref' },
  ambiguous_skill: { class: 'caller', summary: "This name belongs to multiple authorized sources." },
  answer_not_yours: { class: 'caller', summary: "The rated answer was returned to a different client.", docs: 'docs/guides/retrieval-feedback.md#answer_not_yours' },
  answer_pending: { class: 'retryable', summary: "The rated answer is still being recorded; retry in a few seconds.", docs: 'docs/guides/retrieval-feedback.md#answer_pending' },
  answer_unavailable: { class: 'caller', summary: "The rated answer is not recorded: unknown, dropped, or older than the retention window.", docs: 'docs/guides/retrieval-feedback.md#answer_unavailable' },
  api_not_enabled: { class: 'host_only', summary: "Google connect credential error: api not enabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  append_links_fence: { class: 'caller', summary: "append_page text held a links fence marker, so nothing was appended.", why: "A page has one links section, and the rows it lists are the page's authored links: an appended links table would replace that section and delete every link it does not list.", suggestion: 'Write each link with add_link (from, to, link_type); it adds the row to the page\'s links section and keeps the rows already there.' },
  approval_required: { class: 'consent', summary: "The change needs the owner's explicit approval before it can proceed." },
  atom_drain_incomplete: { class: 'retryable', exit: 11, summary: "An atom drain (`gbrain dream --drain`) stopped with atoms still to extract, or with its backlog count unknown; the batches it finished stay committed and running it again continues.", why: "The drain is bounded by its window, batch cap, per-run budget, job deadline and the cycle lock, and a backlog count that fails is never read as drained; each of these stops can clear on the next run.", reasons: ['window', 'deadline', 'lock_lost', 'aborted', 'max_batches', 'budget', 'count_unavailable'], suggestion: 'Run the printed resume_command again (a budget stop also names the cap it hit).', fix: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the pages still waiting for atom extraction.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'] } } },
  atom_drain_no_progress: { class: 'host_only', retryable: false, summary: "An atom drain batch extracted nothing and the backlog count did not fall, so the drain stopped instead of spending in a loop; batches it finished earlier stay committed.", why: "What is left is failing, skipped or ineligible, so running the drain unchanged repeats the same empty batch.", suggestion: 'Do not rerun this drain unchanged. Run gbrain doctor --json on the brain host and ask the operator to resolve the reported extraction blocker; earlier successful batches remain committed.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: names the extraction blocker (provider, eligibility or backlog) the drain could not get past.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'] } } },
  atom_drain_provider_failure: { class: 'host_only', retryable: false, summary: "Every item an atom drain batch attempted failed at the model provider, so the drain stopped; batches it finished earlier stay committed. An item whose atom write did not commit never reached the provider and is not counted here (#7514): its record names the request id and refusal code, and it is held after 3 such failures (held_failed).", why: "An auth, billing, unknown-model or content-block failure repeats on every retry until someone changes the key, plan, model or content, so it is not retryable. A rate limit or a transient failure (5xx, timeout, network, or a cause the provider did not name) can clear by itself, so those reasons stay retryable on exit 11.", reasons: ['auth', 'billing', 'model_not_found', 'content_block', 'rate_limit', 'transient'], reason_overrides: { rate_limit: { class: 'retryable', exit: 11 }, transient: { class: 'retryable', exit: 11 } }, suggestion: 'For auth, billing or model_not_found, ask the operator to fix the provider key, plan or model named in last_error, then run the drain again; content_block items are skipped once they fail repeatedly. For rate_limit or transient, run the drain again later.', fix: { argv: ['gbrain', 'models', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows the extraction model and whether its provider is configured.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_backlog', '--json'] } } },
  autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },
  body_staging_expired: { class: 'retryable', summary: "The staged body of a large-page write expired before it was published, so nothing was published.", why: "A segmented write stages its segments first and publishes them in one flip; a staging idle past its deadline is collected by maintenance, and publishing without its segments would leave the page missing text.", suggestion: 'Send the same write again; it stages a fresh copy.' },
  budget_below_recent_runtime: { class: 'unavailable', summary: "The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend.", why: 'An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed.', docs: 'docs/guides/dream-patterns.md#budget-sizing', suggestion: 'Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`.' },
  backup_dump_failed: { class: 'host_only', summary: "`gbrain backup create` could not dump the PGLite data dir: an entry PGLite cannot read (a socket, FIFO or symlink that is not a dead gbrain socket) is still inside it.", why: "The backup removes only gbrain's own IPC sockets, and only when nothing listens on them; a live gbrain socket, a foreign socket or FIFO, or a symlink is left in place and named in the message, because the database lock proves no other PGLite owner, not who owns an arbitrary endpoint.", docs: 'docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database', suggestion: 'Stop the process that uses each named entry (or move the entry out of the data dir), then rerun the same `gbrain backup create` command. Do not delete an entry something is still listening on.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only: reports the brain's lock holders and storage state so the user can see what still runs against the data dir.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },
  backup_too_large: { class: 'host_only', summary: "`gbrain backup create` refused before writing anything: the PGLite brain's estimated archive size is over the 8 GiB backup-archive cap.", why: 'The archive format holds at most 8 GiB of payload and the dump is materialized in memory; refusing up front avoids a long dump that cannot be published.', docs: 'docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy', suggestion: 'Take a quiesced physical copy of the data directory instead (stop writers, copy, open the copy in an isolated GBRAIN_HOME, verify with gbrain doctor --json).', fix: { ask_user: true, argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only, after the user agrees to the physical copy: doctor opens the brain only when no other gbrain process holds it, so a clean run shows the writers are stopped.", user_message: "This brain is outside what `gbrain backup create` can archive. Stop every gbrain writer on it (gbrain serve, jobs, autopilot, agent sessions), copy the whole data directory and config.json into a new isolated GBRAIN_HOME, point the copy's database_path at the copied data directory, then run gbrain doctor --json with GBRAIN_HOME set to the copy before relying on it.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },
  belief_coverage_required: { class: 'caller', summary: "The belief ledger is not enabled on this source, so it has no coverage start to work from.", why: "The history backfill seeds events before the source's coverage start; with no coverage there is no cut to backfill before.", docs: 'docs/designs/BELIEF_LEDGER.md#72-the-marked-history-backfill', suggestion: 'Ask the user, then run `gbrain beliefs enable --source <id>` first.' },
  belief_stale_preparation: { class: 'retryable', summary: "A purge ran in the source after a belief ledger payload was prepared, so the append was refused.", why: "A payload prepared outside its appending transaction records the source's purge epoch; appending it after a purge could write the purged text back into history.", docs: 'docs/designs/BELIEF_LEDGER.md#65-purge-removal-from-active-memory-never-a-physical-erasure-promise', suggestion: 'Run the same command again; it prepares the payload from the current, redacted state.' },
  benchmark_duplicate_task_id: { class: 'caller', summary: "Benchmark duplicate task id." },
  benchmark_empty: { class: 'caller', summary: "The benchmark file has no tasks." },
  benchmark_exists: { class: 'caller', summary: "A benchmark already exists at the target path." },
  benchmark_judge_llm_no_rubric: { class: 'caller', summary: "Benchmark judge llm no rubric." },
  benchmark_judge_qrels_no_expected: { class: 'caller', summary: "Benchmark judge qrels no expected." },
  benchmark_judge_rule_no_checks: { class: 'caller', summary: "Benchmark judge rule no checks." },
  benchmark_judge_unknown_kind: { class: 'caller', summary: "Benchmark judge unknown kind." },
  benchmark_malformed: { class: 'caller', summary: "A benchmark row is not valid JSON." },
  benchmark_missing_judge: { class: 'caller', summary: "Benchmark missing judge." },
  benchmark_missing_task: { class: 'caller', summary: "Benchmark missing task." },
  benchmark_missing_task_id: { class: 'caller', summary: "Benchmark missing task id." },
  benchmark_not_found: { class: 'caller', summary: "The benchmark file cannot be read." },
  benchmark_rule_check_bad_arg: { class: 'caller', summary: "Benchmark rule check bad arg." },
  benchmark_rule_check_malformed: { class: 'caller', summary: "Benchmark rule check malformed." },
  benchmark_rule_check_unknown_op: { class: 'caller', summary: "Benchmark rule check unknown op." },
  bootstrap_cleanup_pending: { class: 'host_only', retryable: false, exit: 14, summary: "`gbrain bootstrap harness` wired and verified the harness, but cleanup of earlier shared-skills enrollments or carried previous token ids is still pending.", why: "A rotation leaves each old enrollment with that enrollment's own credential and then revokes the credential (leave_brain is principal-owned, so a revoked token can never leave). Each carried id is revoked and cleared on its own; an enrollment whose credential is already revoked is inert and finishes locally as credential_revoked. Until every id is cleared the run must not read as success, so --json lists each id's token state and cleanup state.", reasons: ['revoke_pending', 'leave_pending', 'enrollment_retained', 'credential_unreadable'], docs: 'docs/guides/bootstrap.md#cleanup-pending', suggestion: 'Follow the fix in the --json result: when every id can converge it re-runs the same bootstrap command; otherwise relay its user_message (restore the cleanup credential or revoke that token by id, or make the current enrollment ready), then re-run. Never revoke a token whose enrollment has not left unless its cleanup credential is lost.' },
  bootstrap_empty: { class: 'caller', summary: "The benchmark bootstrap produced no tasks." },
  bootstrap_pending_review: { class: 'caller', summary: "The bootstrapped benchmark awaits human review." },
  bridge_ownership_conflict: { class: 'caller', summary: "The private local CLI registration is invalid." },
  valid_time_undeclared: { class: 'caller', retryable: false, summary: 'An `as_of` read found no version of the page that declares a readable `valid_from`, so no edition can be placed on the date.', why: 'Valid time comes only from the `valid_from` / `valid_until` frontmatter the page carries; gbrain never infers when text took effect. Only the user knows the date, so the fix asks them before a templated edit_page records it.', docs: 'docs/guides/page-history.md#valid_time_undeclared', suggestion: 'Ask the user when the text took effect and record it as a quoted valid_from (the fix carries the edit). For what the brain had recorded at a time, read with known_as_of instead.' },
  bucket_not_found: { class: 'unavailable', summary: "The configured storage bucket does not exist." },
  budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },
  coverage_from: { class: 'caller', summary: "The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark.", why: "Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty. A best-effort backfill from retained versions carries source times only, so it never answers a recorded-time read.", reasons: ['not_recorded', 'backfill_only', 'backfill_incomplete'], docs: 'docs/guides/repair.md#coverage-from', suggestion: 'Ask about a time at or after the time the message names; `gbrain beliefs status --source <id>` lists the coverage intervals.' },
  coverage_gap: { class: 'caller', summary: "The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore.", why: 'Nothing proves what happened to the page inside the gap, so the read refuses instead of answering from either side.', reasons: ['not_covered', 'restore'], docs: 'docs/guides/repair.md#coverage-gap', suggestion: 'Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps.' },
  clock_mismatch: { class: 'caller', summary: 'A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date (`date_for_instant`); get_page `as_of` (valid time) needs a calendar date, not an instant (`instant_for_date`).', why: 'Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, and an instant is not an edition date, so each is refused instead of guessed.', reasons: ['date_for_instant', 'instant_for_date'], docs: 'docs/guides/repair.md#clock-mismatch', suggestion: 'Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date.' },
  extract_write_lost: { class: 'retryable', summary: "A link or timeline write lost during extraction (after the engine's own retries) left its pages unstamped, so they stay due; pages whose writes landed were stamped.", why: "Stamping links_extracted_at for a page whose rows were dropped would hide the loss from every later extraction; leaving it due lets extract --stale, or the cycle's stale drain, write it again.", suggestion: 'Run the retry command the message names (gbrain extract --stale with the source id); it re-extracts only the pages still due.', fix: { argv: ['gbrain', 'doctor', '--only', 'links_extraction_lag', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the pages still waiting for link extraction.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'links_extraction_lag', '--json'] } } },
  item_failures_systemic: { class: 'server', summary: "Most items of one per-item loop failed (or many failed with one code, or none succeeded), so the failure is systemic and no item was held; the unit stopped instead of skipping every item.",
    why: 'A per-item loop holds a bad item and continues (GBRA-130), but a run where most items fail points at a shared cause, and holding every item would hide it.',
    suggestion: 'Fix the shared cause the first failures name, then rerun the same command; run gbrain doctor --json if the cause is unclear.',
    fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Reports brain health and names failing checks; changes nothing.' } },
  known_as_of_unproven: { class: 'caller', summary: 'A change to the page was recorded before the requested instant but was not yet proven committed at it, so the page at that instant cannot be stated.', why: "A write's recorded time is a lower bound on when it became visible; until its commit mark (or a later write to the same page) proves it committed by the instant, the page then may or may not have included it.", docs: 'docs/guides/repair.md#known-as-of-unproven', suggestion: 'Ask about an instant before the write was recorded, or after it was observed committed (the message names both).' },
  cache_quota_exceeded: { class: 'caller', summary: "Retained shared-skill revisions reached this installation's local cache quota.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
  calendar_unreadable: { class: 'caller', summary: "A Google source's configured calendar returned HTTP 403 or 404 to its account, so its sync imports no events.", why: "Without the typed result an unreadable calendar looks exactly like an empty one. The calendar sweep records it in the source's connector state (the run is not failed); `gbrain doctor` (google_calendar_readable) reads it with no network call and `gbrain google status` probes it live.", docs: 'docs/guides/google-connect.md#unreadable-calendar', suggestion: 'List the calendars the account can read with `gbrain google calendars --account <email>`, then point the source at one with `gbrain sources set-calendar <source> <calendar-id>` and run `gbrain sync --source <source>`.', fix: { argv: ['gbrain', 'google', 'calendars', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the calendar ids the connected account can read.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'google_calendar_readable', '--json'] } } },
  cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },
  capacity_paused: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'],
    summary: "A managed sync passed its capacity preflight, then a cumulative write cap (or the background pause line) refused its next admission, so the drain stopped resumable with its cursor and accepted writes intact; nothing failed.",
    why: "Another writer used the capacity the preflight counted on. Request ids never free, so only the brain host's reversible config raise resumes an ids pause; receipt bytes also free as receipts compact.",
    docs: 'docs/guides/write-refusals.md#drain-capacity-paused',
    suggestion: 'Run the gbrain config set the drain report names on the brain host (gbrain doctor --only persistence_capacity --json prints it), then rerun the same gbrain sync; it resumes at the stored cursor.' },
  catalog_capacity_exceeded: { class: 'caller', summary: "The shared-skills catalog visible to this connection exceeds the delivery limits.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
  catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },
  host_upgrade_required: { class: 'host_only', retryable: false, exit: 16, summary: "The brain host is older than this client and did not answer the question asked: a get_page reply to an `as_of` read came back without `valid_time.as_of`, so it is the current page, not the edition in force on that date. Nothing historical was printed.", why: 'An older host ignores a read parameter it does not know and answers the plain read. Printing that answer as the edition in force on a date would quote the wrong text, so the client fails closed. The error carries the client version, the host version when known, and the minimum host version.', docs: 'docs/guides/page-history.md#host_upgrade_required', suggestion: 'Upgrade gbrain on the brain host (`gbrain upgrade`), or ask its operator to; then run the same read again.' },
  change_reason_rejected: { class: 'caller', summary: "The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret.", why: 'A reason is kept in page history and, on a page that reaches Git, in the commit message, which a push makes permanent; it is checked before the write is journaled so no copy of a refused reason is stored anywhere.', reasons: ['reason_too_long', 'reason_contains_secret'], legacy_error: 'invalid_params', docs: 'docs/guides/page-history.md#reasons', suggestion: 'Shorten the reason, or remove the secret from it, and send the write again.' },
  changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },
  chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'page_body_segmented', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'judge_input_unchanged', 'judge_input_failed', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'campaign_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },
  checkout_not_a_source: { class: 'caller', actor: 'user', summary: "gbrain git commit-push resolved a checkout from the working directory that is not one of this brain's source checkouts on this host (for example a wrapper that changed into another repository), so nothing was staged.", why: 'Committing there would write into an unrelated repository, or fail later with a confusing path refusal.', docs: 'docs/guides/shared-checkout-git.md#checkout_not_a_source' },
  checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },
  checkpoint_validation_timeout: { class: 'retryable', summary: "Validating the managed-sync checkpoint timed out." },
  claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  class_apply_busy: { class: 'retryable', summary: "Another apply of the same whole-class file-drift manifest is running, so this run wrote nothing.", why: "One whole-class apply per manifest at a time keeps its progress record and request ids consistent; a second apply would race the first over the same pages.", docs: 'docs/guides/repair.md#whole-class', suggestion: 'Wait for the running apply to finish. If it was stopped, rerun the same apply command once its lock expires (the message names when); it resumes at the next window and applies no page twice.' },
  class_capacity_exceeded: { class: 'caller', retryable: false, actor: 'user', summary: "A whole-class file-drift preview found that the reconcile backups its apply would retain exceed the brain's recovery-bytes limit, so nothing was written.", why: "Every page the apply replaces keeps a private reconcile backup, and those backups are bounded by persistence.limits.brain_recovery_bytes; an apply that ran out of room would stop partway through the class.", docs: 'docs/guides/repair.md#whole-class', suggestion: 'Show the user the bytes needed and the limit the message names. Raising persistence.limits.brain_recovery_bytes is their call; otherwise settle a smaller class with --only / --skip.', fix: { argv: ['gbrain', 'config', 'get', 'persistence.limits.brain_recovery_bytes'], consent: [], actor: 'agent', why: 'Read-only: shows the recovery-bytes limit in effect.', requires_exclusive: false } },
  class_manifest_stale: { class: 'caller', retryable: false, summary: "The whole-class file-drift manifest no longer matches the hash passed with --expect or the pins its preview saved, so nothing was written.", why: "The apply replaces exactly the pages the user approved; a manifest that was edited, partly written, removed, or previewed for another selection is not that approval.", docs: 'docs/guides/repair.md#whole-class', suggestion: 'Run the fresh preview the message prints, show the user its card, and apply its new hash after they agree.' },
  client_behind: { class: 'host_only', retryable: false, actor: 'host_admin', summary: "Schema setup (initSchema, which gbrain init, init --migrate-only and upgrade run, and apply-migrations before its orchestrators) refused because the brain's schema version is newer than this gbrain binary's newest migration; nothing in its schema ran and nothing changed.", why: "initSchema replays the binary's whole schema, CREATE OR REPLACE FUNCTION included, before it runs migrations. An older binary sharing the database with a newer one (another host, a lagging cron running apply-migrations or upgrade) used to reinstall its own superseded function bodies, the writer-fence guards among them, over the newer ones and then apply nothing (#7776). Reads do not run schema setup and keep working on the older binary; doctor schema_function_bodies names bodies an older replay already reverted.", suggestion: 'Upgrade gbrain on this host (gbrain upgrade) to the release that migrated the database or newer, then rerun the command.', fix: { argv: ['gbrain', 'doctor', '--only', 'schema_version', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the brain's schema version beside this binary's newest migration.", requires_exclusive: false } },
  client_json_unreadable: { class: 'caller', summary: "Google connect credential error: client json unreadable.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  client_json_wrong_type: { class: 'caller', summary: "Google connect credential error: client json wrong type.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  client_not_found: { class: 'caller', summary: "No OAuth client with this id is registered on this brain, so nothing was read or changed.", why: 'A client id is matched exactly; a revoked, deleted or mistyped id has no grant to read or edit.', suggestion: 'List the clients with `gbrain auth clients --json` and retry with an existing client id. Do not register a replacement client or rotate credentials for a lookup miss.', fix: { argv: ['gbrain', 'auth', 'clients', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the OAuth clients registered on this brain.', verify: { argv: ['gbrain', 'auth', 'clients', '--json'] } } },
  client_shape_invalid: { class: 'caller', summary: "Google connect credential error: client shape invalid.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  code_callees_requires_symbol: { class: 'caller', summary: "code-callees requires a symbol name." },
  code_callers_requires_symbol: { class: 'caller', summary: "code-callers requires a symbol name." },
  code_def_requires_symbol: { class: 'caller', summary: "code-def requires a symbol name." },
  code_refs_requires_symbol: { class: 'caller', summary: "code-refs requires a symbol name." },
  code_reused: { class: 'caller', summary: "Google connect credential error: code reused.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  colon_slug_windows_write_through: { class: 'caller', summary: "A colon slug cannot be written through on Windows." },
  command_failed: { class: 'server', summary: "The command failed before it wrote its JSON result." },
  commit_lock_busy: { class: 'retryable', summary: "Another writer held the checkout's commit lock for the whole wait, so nothing was committed.", docs: 'docs/guides/shared-checkout-git.md#outcomes' },
  commit_base_moved: { class: 'caller', summary: "A file named with --base changed at HEAD since the writer read it, so nothing was staged or committed.", why: "--base <path>=<blob> binds a commit to the bytes the writer read; another writer committed that file since, and committing now would overwrite its change.", docs: 'docs/guides/shared-checkout-git.md#base-check', suggestion: 'Read the file at HEAD again, redo the change on it, and rerun with the new --base the message names.' },
  commit_paths_unmerged: { class: 'caller', actor: 'user', summary: "The commit was refused before staging: a named file still has unresolved merge conflicts in the index, so committing it would publish its conflict markers.", why: "Git keeps the two sides of a conflicted file (after a merge, rebase or stash pop that stopped on a conflict) as unmerged index entries until someone resolves it; staging it would record the file with its markers as resolved.", docs: 'docs/guides/shared-checkout-git.md#outcomes', suggestion: 'Resolve each file with the user (edit out the markers and keep the changes from both sides that belong in the file, since one side may be a write gbrain made), mark it resolved with git add -- <file>, then rerun the commit.' },
  commit_paths_invalid: { class: 'caller', summary: "The commit was refused before staging: no paths, a path outside the checkout, the whole checkout, or a path git would not stage.", docs: 'docs/guides/shared-checkout-git.md#outcomes' },
  commit_paths_skipped: { class: 'caller', reasons: ['assume_unchanged', 'skip_worktree', 'not_staged'], summary: "gbrain git commit-push (or the brain's committed commit-push helper) committed the other named paths but git left the listed ones out: a modified file flagged assume-unchanged or skip-worktree, or a file inside a nested Git repository.", why: 'git add stages nothing for those and still exits 0 (or, for a named skip-worktree file, refuses every path), so reporting success would leave the write uncommitted with nothing in any log.', docs: 'docs/guides/shared-checkout-git.md#outcomes', suggestion: 'Read each skipped path and its reason in the message. Clear an assume-unchanged or skip-worktree flag after the user agrees, one flag per call (git update-index --no-assume-unchanged -- <path>, git update-index --no-skip-worktree -- <path>), or move a file out of a nested repository, then rerun the same commit-push.' },
  commit_prestaged_paths: { class: 'consent', summary: "The commit was refused before staging: files another writer had already staged sit under a named directory, and committing them would publish that writer's work.", docs: 'docs/guides/shared-checkout-git.md#outcomes', actor: 'user' },
  commit_outside_source_root: { class: 'consent', summary: "The commit or publish was refused: it changes files outside the brain's configured source root (git config gbrain.sourceRoot), often a commit made without gbrain git commit-push.", docs: 'docs/guides/shared-checkout-git.md#source-roots', actor: 'user' },
  concurrent_write: { class: 'caller', summary: "A managed sync import raced a database-only write to the same page, so the file is held and the page keeps the database version; neither was overwritten.", why: "The page's live revision was written by a committed non-sync request after the import was frozen, so the Git file and the database genuinely diverge; choosing either silently would lose the other.", docs: 'docs/guides/write-refusals.md#concurrent_write', suggestion: 'Preview the reconciliation with gbrain sources reconcile <source> <slug> --preview, resolve it with the user, then run gbrain sources retry-held <source> and gbrain sync --source <source> --no-pull.' },
  config_error: { class: 'caller', summary: "A required configuration value or directory is missing or invalid." },
  confirmation_required: { class: 'consent', summary: "The command needs the user's authorization before it runs; nothing was changed.", exit: 3 },
  conflicting_source_scope: { class: 'caller', summary: "--source and --all-sources were both given." },
  connection_inherited_read_only: { class: 'host_only', retryable: false, actor: 'host_admin',
    summary: "The database refused a write as read-only (SQLSTATE 25006): the server connection defaults to read-only transactions, so nothing was written.",
    why: "default_transaction_read_only is on for that server connection: session state another client set on a connection a transaction-mode pooler shares, a role or database default, or a read-only server. gbrain opens its transactions READ WRITE and runs a refused autocommit statement once more inside one, so a session default alone no longer stops it; a read-only server (a hot standby) still refuses.",
    docs: 'docs/guides/write-refusals.md#connection_inherited_read_only',
    suggestion: "Ask the database operator to reset the pooler's server connections (PgBouncer: RECONNECT, or server_reset_query = DISCARD ALL with server_reset_query_always = 1), find the client that issues session-level SET through the pooler (read-only audits belong in BEGIN READ ONLY ... COMMIT), and check ALTER ROLE / ALTER DATABASE ... SET default_transaction_read_only; then retry.",
    fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: reports the database connection and what is blocked on it.', requires_exclusive: false } },
  connection_lost: { class: 'retryable', retryable: true, actor: 'agent',
    summary: "The managed sync drain lost its database connection three times in a row without committing a page in between, so it stopped where the cursor stands; nothing is recorded against the source.",
    why: "A pooler drop (ECONNABORTED, ECONNRESET, ETIMEDOUT, EPIPE) is a transport fault, not a page fault: the drain reconnects and retries at 5, 15 and 45 seconds, and the frozen manifest and cursor stay as they are. Three consecutive drops with no progress mean the database is unreachable from here for now.",
    docs: 'docs/guides/write-refusals.md#drain-connection-lost',
    suggestion: 'Check the database URL and pooler (gbrain doctor --json), then rerun the same gbrain sync; it resumes at the stored cursor without re-freezing the manifest.' },
  connector_account_changed: { class: 'caller', summary: "The connector credential resolves to a different account than the source is pinned to.",
    why: 'A connector source is pinned to the account it first synced, so a swapped credential can never import another account\'s mail, calendar or repositories into it. The refused run records the mismatch, and autopilot skips the source (unavailable-path) instead of retrying it every interval (#6803).',
    docs: 'docs/guides/write-refusals.md#connector-account-changed',
    suggestion: 'Restore the credential for the pinned account and run gbrain sync --source <id> (it clears the skip once the account check passes), or add a new source for the new account and archive this one with gbrain sources archive <id>. gbrain doctor --only connector_account_mismatch lists every affected source.',
    fix: { argv: ['gbrain', 'doctor', '--only', 'connector_account_mismatch', '--json'], consent: [], actor: 'agent', why: 'Lists the connector sources autopilot skips for an account mismatch; changes nothing.', requires_exclusive: false } },
  connector_access_denied: { class: 'caller', summary: "The connector key works but may not read what the source asks for; nothing more was imported.",
    docs: 'docs/guides/meeting-and-slack-sources.md#connector_access_denied',
    suggestion: 'Save a key whose account can read it (gbrain connectors auth <provider> --token -), then gbrain sync --source <id>.' },
  connector_auth_required: { class: 'caller', summary: "The connector source has no working API key; nothing was imported.",
    why: 'The key is read from the source\'s --token-env variable when it names one, else GBRAIN_CONNECTOR_<PROVIDER>_TOKEN, else the 0600 credential file. None held a key the provider accepted.',
    docs: 'docs/guides/meeting-and-slack-sources.md#connector_auth_required',
    suggestion: 'Ask the user for the provider API key and save it on stdin: gbrain connectors auth <provider> --token -; then gbrain sync --source <id>.' },
  connector_binding_missing: { class: 'caller', summary: "A connector source records to Git, but its Git checkout is not available; the item was held, not written database-only.",
    why: 'A source whose record mode is git commits each item to its checkout before the database row, so git stays the parent. When the checkout is missing the item waits in the holds and is retried on the next sync; it is never written to the database alone, and the record mode is never re-inferred.',
    docs: 'docs/guides/meeting-and-slack-sources.md#connector_binding_missing',
    suggestion: 'Restore the source checkout (gbrain sources status <id>), then gbrain sources retry-held <id>.' },
  connector_fence_below_timeline: { class: 'caller', summary: "A stored page carries a fence the connector render cannot preserve." },
  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." },
  connector_item_too_large: { class: 'caller', summary: "A connector item renders larger than the page size limit; it was held, not truncated.",
    docs: 'docs/guides/meeting-and-slack-sources.md#connector_item_too_large' },
  connector_response_too_large: { class: 'caller', summary: "A connector API response exceeded the client's size limit and was not read.",
    docs: 'docs/guides/meeting-and-slack-sources.md#connector_response_too_large' },
  connector_shape_drift: { class: 'caller', summary: "A connector API response is missing a field it must carry; the item was held, never published partially.",
    docs: 'docs/guides/meeting-and-slack-sources.md#connector_shape_drift' },
  chunkless_pages_healable: { class: 'consent', summary: "Live pages have body text but no chunk rows, so search cannot read their body.", why: 'A page written without the chunking step (an enrichment stub, an interrupted write) has nothing for search to match; `gbrain embed --stale` chunks it first, which makes paid embedding calls.', docs: 'docs/guides/troubleshooting.md#embedding-state', suggestion: 'List them with `gbrain pages unsearchable --state chunkless_healable --json`, then run `gbrain embed --stale --catch-up --yes` once embedding spend is approved.', fix: { argv: ['gbrain', 'pages', 'unsearchable', '--state', 'chunkless_healable', '--json'], consent: [], actor: 'agent', why: 'Lists the chunkless pages and each one\'s fix; changes nothing.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'] } } },
  consent_required: { class: 'consent', summary: "A paid step is waiting for the user's opt-in, so it was skipped and nothing was spent.", why: "A dream-cycle phase that a database-config schema pack newly declares (extract_atoms, synthesize_concepts) did not run before this release; resolving the pack correctly must not start paid model calls on its own (#6393).", suggestion: 'Ask the user; with their agreement run gbrain config set cycle.<phase>.enabled true (the phase skip names the exact command).', fix: { argv: ['gbrain', 'schema', 'active', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows which pack is active and the tier it comes from.', requires_exclusive: false } },
  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_repair_needs_human: { class: 'caller', retryable: false, actor: 'user',
    summary: "The content-repair model could not decide whether a held file and the page its frontmatter `slug:` names are the same page, so nothing was written and a person decides which keeps the slug.",
    why: "A `frontmatter_slug_conflict` hold that the deterministic rules cannot clear (the named page exists and shares a type or a title word with the file) goes to the judgment model; `needs_human` is its answer when the shown frontmatter, headings, opening lines and cross-mentions do not decide identity. Removing the `slug:` line on a guess would mint a second page for the same thing, and merging on a guess would fold two different things together, so gbrain records the verdict on the hold as codes and slugs, retries nothing until the file changes, and the rest of the source keeps syncing.",
    docs: 'docs/guides/write-refusals.md#content_repair_needs_human',
    suggestion: 'Show the user the paragraph gbrain sources status <id> --json renders for the hold (the path and the two slugs). If the two differ, remove the slug: line of the file; if they are one page, merge the unique sections into the page that keeps the slug and delete the other file; then commit and run gbrain sync --source <id> --no-pull.',
    fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,
      why: 'Read-only: lists the held file with the two slugs and the rendered paragraph; the user decides which page keeps the slug before anything is edited.',
      verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
  content_filter_owned: { class: 'caller', summary: "A synced file is stored in Git through a filter (git-crypt or another clean/smudge driver), so managed sync holds that file alone.", why: "A filter's committed bytes (git-crypt ciphertext, for one) are not the file's text, and gbrain does not run a repository's filter programs during sync, so the file cannot be imported as it stands. The rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#content_filter_owned', suggestion: 'Leave the file out with sync.exclude, or commit it without the filter so Git stores its text, then sync again.' },
  content_null_bytes: { class: 'caller', summary: "A synced Markdown file holds NUL bytes (U+0000), so managed sync holds that file alone.", why: "Page text is stored as UTF-8 without NUL bytes, so the file cannot be imported as it stands; NUL bytes usually mean a UTF-16 save (a Windows \"Unicode\" file), a binary file named .md or a crash-padded file. The rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#content_null_bytes', suggestion: 'Save a UTF-16 file as UTF-8, remove the NUL bytes, or remove a binary file (or leave it out with sync.exclude), then commit and sync again.' },
  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.' },
  continuation_unproven: { class: 'retryable', summary: "Claude Code continued an answer past its output cap and gbrain could not prove the full text, so the claude-cli call returned no text and no tool calls and finished as length.", why: "Print mode reports only the text after an automatic continuation; parsing or dispatching that tail as a complete answer would act on a fragment. The caller retries or escalates as for any capped answer; the gateway does not resend it to a fallback model.", reasons: ['events_missing', 'no_assistant_events', 'segments_unmatched'], docs: 'docs/ai-providers/claude-cli.md#claude-cli-troubleshooting', fix: { argv: ['gbrain', 'config', 'set', '<KEY>', '<TOKENS>'], inputs: [{ name: 'KEY', how: "The output cap the failing caller's truncation warning names (for example dream.propose_takes.max_tokens, facts.extraction_max_tokens or models.synopsis_max_tokens)." }, { name: 'TOKENS', how: 'A larger whole number of output tokens; ask the user, since a larger cap can cost more per call.' }], consent: [], actor: 'agent', ask_user: true, why: 'A cap the whole answer fits under ends the call before Claude Code continues it, so the full text arrives in one response.', requires_exclusive: false } },
  corpus_chat_unavailable: { class: 'unavailable', summary: "The sweep's corpus pass stopped because the extraction model is not servable in this process; the captured session files stay pending (no `.ingested` sidecar), so nothing was lost.",
    why: "No servable model is a state of the extracting process, not of the transcript. Before #6786 it was recorded as a finished file with zero facts, and retention later deleted the text.",
    suggestion: 'Configure the extraction model (gbrain models shows it) or run the sweep from a process that has its key; the next sweep extracts the pending files.',
    fix: { argv: ['gbrain', 'models', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows the facts extraction model and whether its provider is configured.' } },
  corpus_window_backoff: { class: 'retryable', summary: "A corpus window failed after its model call and waits out its retry delay (the next sweep, then 10, 20 and 40 minutes) before the sweep pays for it again.",
    why: 'Without a delay a write that fails after extraction (#6785) was paid for again on every drain.',
    fix: { argv: ['gbrain', 'sweep', '--retry-failed', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the failing files, their attempt counts and the last error code.' } },
  corpus_window_dead_lettered: { class: 'consent', summary: "A corpus window failed after its model call on every allowed attempt, so the sweep stopped paying for it; its file stays pending until an operator retries it.",
    why: 'A window that can never commit was re-extracted forever before #6785. The count is per window and source incarnation; tail growth and changing error codes do not reset it, and one extraction-config change (model, provider, key presence) retries it once.',
    suggestion: 'Fix the cause the last code names (for writer_coordinator_required: gbrain sources writer status <source>), then ask the user before gbrain sweep --retry-failed --apply: the retry pays for the extraction again.',
    fix: { argv: ['gbrain', 'sweep', '--retry-failed', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the stopped files, their attempt counts and the last error code.' } },
  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' },
  // #6712 PR 4a: the read-only convergence shadow could not read the level (`convergence.code` on an unavailable receipt).
  convergence_read_failed: { class: 'server', actor: 'agent', summary: "The read-only convergence shadow (`gbrain sync --dry-run --json`'s `convergence`, `sync status --detail`, doctor `managed_sync_convergence`) could not read the source's level, so it reports `status: unavailable` instead of counts.",
    why: 'The shadow only predicts what the level-triggered pass would do; the dry run, status and doctor results around it are unaffected and nothing was written.',
    docs: 'docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes',
    suggestion: "Read the receipt's message, then rerun the read-only status; report it with gbrain doctor --json if it repeats.",
    fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--detail', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-reads the convergence shadow; writes nothing.' } },
  core_mark_owner_only: { class: 'consent', summary: "A remote caller tried to change always_load or core_priority; only the owner designates core pages.", docs: 'docs/guides/core-memory.md#owner-only', actor: 'user' },
  core_remote_edit_refused: { class: 'consent', summary: "Remote edits to always-loaded core pages are refused by memory.core.remote_edit.", docs: 'docs/guides/core-memory.md#remote-edits', actor: 'user' },
  cost_cap_exceeded: { class: 'server', summary: "The run reached its cost cap before finishing." },
  cost_preview_requires_yes: { class: 'consent', summary: "Cost preview requires yes." },
  // wave 16 (GBRA-79) #6518: `gbrain sync status` names a cursor no current sync can select.
  cursor_incarnation_retired: { class: 'caller', summary: "An unfinished managed sync cursor of this source was recorded under a source incarnation the source no longer has (it was re-pointed at a new checkout, or removed and added again), so no current sync selects or resumes it.",
    why: "The cursor key digests the incarnation; every incarnation-joined reader drops the old rows while the local ledger mirror and the source-id-only cursor read still showed them. Retiring the bookkeeping says nothing about whether the current source's files are imported.",
    docs: 'docs/guides/repair.md#managed-sync-orphans',
    suggestion: 'Preview gbrain repair managed-sync-orphans --source <id> and apply it with the hash it prints; then gbrain sync status --source <id> --json shows the current cursor, if any.',
    fix: { argv: ['gbrain', 'repair', 'managed-sync-orphans', '--source', '{source_id}'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the retired bookkeeping and prints the apply command; writes nothing.' } },
  cycle_failed: { class: 'server', summary: "The maintenance (dream) cycle failed, or a phase threw and was contained so later phases could run." },
  d_sel_too_small: { class: 'caller', summary: "The selection split has too few tasks for meaningful validation." },
  database_error: { class: 'server', summary: "The brain database could not be reached or refused the operation." },
  delta_cursor_upgrade_required: {
    class: 'caller',
    summary: "A since/since_slug delta call reached more undelivered facts at one timestamp than that cursor can page; repeat the call with the opaque cursor.",
    why: "The legacy cursor is a single timestamp, so facts that share one can only be paged by fact id, which next_cursor.cursor carries. Nothing was skipped and no cursor moved.",
    suggestion: "Repeat the delta call with the cursor from fix (next_cursor.cursor) instead of since/since_slug, and keep passing next_cursor.cursor afterwards.",
    docs: 'docs/guides/ambient-recall.md#replay-after-a-degraded-wake',
  },
  deleted_page_chunks_overdue: { class: 'consent', summary: "Chunks of pages soft-deleted longer than the purge window (72h), which the purge would remove, are still stored.", why: 'Search never reads them; the purge lifecycle (`gbrain pages purge-deleted`, the autopilot purge phase) hard-deletes such pages and their chunks. Pages its holds keep (a derived retirement inside generations.restore_days, a restorable atom, an open rename-identity pair, a parked derived-page origin, an archived source) are not counted. The purge is brain-wide and irreversible, so it needs the user.', docs: 'docs/guides/troubleshooting.md#embedding-state', suggestion: 'Preview with `gbrain pages purge-deleted --dry-run --json`, then run `gbrain pages purge-deleted --yes` once the user agrees.', fix: { argv: ['gbrain', 'pages', 'purge-deleted', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the soft-deleted pages the purge would remove; changes nothing.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'] } } },
  demo_graph_failed: { class: 'server', summary: "The fictional graph did not verify." },
  downgrade_blocked_deferred_writes: { class: 'consent', actor: 'host_admin', exit: 3, summary: "Writes deferred behind a worktree refresh are still waiting, and an older gbrain cannot drain them.", why: "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. A released write publishes only when a gbrain process runs the write consumer on the worktree's owner host; polling its receipt does not publish it.", docs: 'docs/guides/write-refusals.md#deferred-writes', suggestion: 'Turn the barrier off (gbrain config set persistence.refresh_barrier false); wait until gbrain upgrade --check-downgrade exits 0, then downgrade.' },
  demo_import_failed: { class: 'server', summary: "The fictional page did not import successfully." },
  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." },
  // GBRA-133 PR 3a: the commit notifier's failure code for a source whose drain-lease holder commits nothing.
  drain_holder_stalled: { class: 'retryable', actor: 'agent', summary: "The commit notifier did not wait on a source's drain lease because the process holding it has made no commit or cursor save for 5 minutes; it counts as a failed attempt.",
    why: "Waiting on a holder that commits nothing kept the source due forever with nothing reported. Counting it as a failed attempt runs the notifier's retry tiers (5 s, 15 s, 1 min, 5 min), so the source reaches notifier_stalled with the sync-now fix in sync status and doctor; a foreground sync follows the holder and takes the source over when its lease lapses.",
    docs: 'docs/guides/on-commit-sync.md#notifier-stalled',
    suggestion: 'Read gbrain sync status --source <id> --json (the notifier block and drain_holder name the holder), stop that process if it is wedged, then run gbrain sync --source <id> --no-pull.' },
  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', 'owner_restart_required'],
    // #6712 PR 2: a pass that admits nothing with no unfinished request stops `no_progress`; an older build wrote `no_admission` for it.
    retired_reasons: { no_admission: '0.60.266.0' },
    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." },
  doctor_alert_act: { class: 'host_only', retryable: false, exit: 17, summary: "`gbrain doctor --alert` found a page-class check that needs someone now (database unreachable, writes failing or stalled, migrations pending or wedged, more than one build running, sync or maintenance stalled, corrupt rows, a public schema exposed, or a tripped paid-loop breaker).", why: "Only page-class checks page; skill, advisory and coaching checks never do, so health_score warnings alone exit 0. Each item in --json alert.items keeps that check's own fix, consent, actor and verify.", docs: 'docs/guides/troubleshooting.md#doctor-alert-act', suggestion: 'Read alert.items in the --json document and follow each fix.next; page the operator for items whose fix needs them.', fix: { argv: ['gbrain', 'doctor', '--alert', '--json'], consent: [], actor: 'agent', why: 'Read-only: the alert verdict with each item and its fix.', requires_exclusive: false } },
  doctor_alert_unknown: { class: 'retryable', exit: 18, reasons: ['budget', 'bound', 'errored', 'last_known', 'not_run'], summary: "`gbrain doctor --alert` found nothing to act on, but at least one page-class check did not run fresh in this run, so the brain's health is unknown, not clear.", why: "A check that timed out, errored, was reported from its last known result or was skipped by the tier proves nothing; reading it as healthy would hide an outage. alert.consecutive_unknown counts the alert runs in a row that ended unknown, and agent crons page on the second.", docs: 'docs/guides/troubleshooting.md#doctor-alert-unknown', suggestion: 'Run each alert.unknown item fix (it measures that check alone); if a check keeps running out of time, raise --budget-ms or run gbrain doctor --alert --tier standard --json.', fix: { argv: ['gbrain', 'doctor', '--alert', '--budget-ms', '0', '--json'], consent: [], actor: 'agent', why: 'Read-only: the alert verdict with no overall budget, so every page-class check can finish.', requires_exclusive: false } },
  doctor_tier_unavailable: { class: 'host_only', actor: 'host_admin', summary: "The remote serve cannot answer this doctor tier or check for this client, so the thin client ran nothing.", why: "A serve older than the doctor ops tier does not advertise run_doctor's tier and only parameters or get_brain_health, and a token without admin scope cannot call run_doctor; the thin client never falls back to the full report.", docs: 'docs/guides/troubleshooting.md#doctor-ops-tier', fix: { argv: ['gbrain', 'doctor', '--tier', 'ops', '--json'], consent: [], actor: 'host_admin', why: 'The ops report, run on the brain host (or after upgrading and restarting its serve).', requires_exclusive: false } },
  effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },
  embed_backfill_stalled: { class: 'unavailable', actor: 'agent',
    summary: "A source's automatic embed-backfill failed the same way several times with nothing embedded, so automatic backfill for it backs off and then stops.",
    why: 'The only remaining work sits on pages whose text projection cannot be rebuilt (a rebuild_failed projection, or an image page: gbrain projections drain seals the importer-attested ones, the rest need their importer). Each identical run spent a worker slot and dead-lettered; after three, automatic submission stops until the blocked pages or the stale chunks change, or a run embeds something (#6803). Explicit gbrain embed --stale and gbrain jobs submit embed-backfill are not gated.',
    docs: 'docs/guides/repair.md#embed-backfill-stalled',
    suggestion: 'Run gbrain doctor --only embed_backfill_stalled to see the blocked pages, preview the repair with gbrain projections drain --dry-run, then run gbrain projections drain; it names each page that still fails and its next step, and gbrain doctor --only text_projection_readiness --json counts the image pages by class.',
    fix: { argv: ['gbrain', 'doctor', '--only', 'embed_backfill_stalled', '--json'], consent: [], actor: 'agent', why: 'Names the blocked pages and the preview-first repair; changes nothing.', requires_exclusive: false } },
  embedding_auth_failed: { class: 'unavailable', summary: "The embedding provider rejected the credentials." },
  embedding_budget_below_worst_case: { class: 'unavailable', summary: "The embedding migration cap is below its worst-case cost; nothing was changed." },
  embedding_configuration: { class: 'host_only', summary: "The brain's embedding configuration is invalid." },
  embedding_disabled: { class: 'unavailable', summary: "Embeddings are disabled on this brain." },
  embedding_failed: { class: 'server', summary: "Computing embeddings for the content failed." },
  embedding_identity_unqualified: { class: 'consent', summary: "The brain's embedding_model config row names a model with no provider prefix, so managed fact extraction cannot verify its embedding identity.", why: 'Rows from older installs stored the bare model name. The managed facts resolver reads only the DB row and `config set` refuses to change it, so the supported rewrite is `gbrain migrate embeddings --to <provider:model>`, which re-embeds active facts (paid).', docs: 'docs/guides/troubleshooting.md#embedding-identity-unqualified', suggestion: 'Preview the rewrite with `gbrain migrate embeddings --to <provider:model> --dry-run`, show the user its cost, and apply it only with their paid authorization.', fix: { argv: ['gbrain', 'doctor', '--only', 'embedding_identity_unqualified', '--json'], consent: [], actor: 'agent', why: 'Names the stored row, the configured model and the exact preview command, read-only.', requires_exclusive: false } },
  embedding_model_mismatch: { class: 'unavailable', summary: "The configured provider does not match the active embedding column." },
  embedding_plane_split: { class: 'unavailable', summary: "Embedding plane split." },
  embedding_state_unknown: { class: 'unavailable', summary: "The ops tier could not count embedding state: the active embedding column has no covering partial index, and the ops tier never scans.", why: 'Without an index on `WHERE <active column> IS NULL`, counting vector-less chunks means a full table scan, which the bounded ops tier refuses.', docs: 'docs/guides/troubleshooting.md#embedding-state', suggestion: 'Run the standard tier (`gbrain doctor --only embedding_state --json`) for exact counts.', fix: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'], consent: [], actor: 'agent', why: 'The standard tier counts every embedding state exactly; it reads and changes nothing.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'embedding_state', '--json'] } } },
  embedding_storage_unavailable: { class: 'retryable', summary: "Embedding policy or claim storage is temporarily unavailable." },
  embedding_unavailable: { class: 'unavailable', summary: "The provider returned an incomplete embedding batch." },
  embedding_unconfigured: { class: 'host_only', summary: "The selected brain has no verifiable text embedding model and dimensions." },
  embedding_width_mismatch: { class: 'caller', summary: "The embedding model cannot produce the width of the brain's vector column; nothing was changed." },
  embedded_core_required: { class: 'caller', summary: "openEngine (gbrain/engine-open) was called without embedded_core: true, so no engine was opened.", why: 'Opening an engine from settings alone is an experimental embedding surface that is off by default; a host opts in explicitly so no existing caller changes behavior.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass embedded_core: true in the settings; the CLI, gbrain serve and mounts open brains through their own connect path and need nothing.' },
  enforced_member_refused: { class: 'consent', exit: 3, actor: 'user', reasons: ['command_not_allowed', 'member_not_usable', 'target_not_readable', 'label_change', 'thin_client', 'as_flag', 'arguments_not_allowed', 'remember_needs_entity', 'writes_off'], summary: "The CLI runs under GBRAIN_ENFORCED_MEMBER and refused the command before it read or changed anything: the command or its arguments are not on the enforced member allow-list, the variable names no usable member, a target page or source is outside what the member reads, the write would change an access or privacy label, or the brain turned member writes off (access.enforced_member_writes).", why: 'A launcher pins GBRAIN_ENFORCED_MEMBER so a shared agent turn acts as one member: reads show only what that member reads, writes never touch a page it cannot read or change a label, and anything not classified is refused rather than run as the trusted owner. Stderr starts with gbrain: refused under GBRAIN_ENFORCED_MEMBER=<member>: <command> [GBRAIN_ENFORCED_REFUSED].', docs: 'docs/guides/enforced-member.md#refused', suggestion: 'Do not retry here; nothing was changed. Ask the brain owner to run the command in a direct session, one without GBRAIN_ENFORCED_MEMBER.' },
  engine_embedding_mismatch: { class: 'host_only', actor: 'user', summary: "An engine opened from settings names an embedding model or width that differs from the one its database already records, so initSchema changed nothing.", why: 'The vector column has one width and the brain one embedding model; seeding another over it would make every stored and future embedding unreadable. Changing it is an explicit re-embed the user decides on.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Pass the database's recorded model and width in settings.embedding, or read the recorded identity with gbrain migrate embeddings --status on the brain host and preview a migration from there.", fix: { argv: ['gbrain', 'migrate', 'embeddings', '--status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: "Read-only: reports the brain's recorded embedding model and width and what a migration would change." } },
  embedded_engine_required: { class: 'caller', summary: "An operation that serves an embedding host (file_register, file_verify) was called on an engine the CLI or a server opened, so it did nothing.", why: 'These operations trust a host that stores bytes itself; a brain opened the usual way stores files through file_upload, so the operations stay off there and its behavior is unchanged.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Call it on an engine opened from settings with settings.storage; a brain the CLI or a server opens stores files only through file_upload (gbrain files upload).' },
  engine_closed: { class: 'caller', summary: 'An engine opened from settings was disconnected, which closes it for good, so connect() and reconnect() refuse and nothing was reopened.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Call openEngine again with the settings to open a new engine.' },
  engine_host_missing: { class: 'caller', summary: "An engine opened from settings has no host identity, so nothing that needs one ran and no host.json was created.", why: 'An embedded engine publishes and claims work under the host id its host gave at open; minting a host.json under the home directory instead would tie its writes to whatever process happens to share that directory.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass host: { id: <uuid> } to openEngine; keep the same id for the same host across restarts.' },
  engine_scope_missing: { class: 'caller', summary: "An engine opened from settings made an AI call (embed, chat, expansion or rerank) through a provider its settings.ai does not name, or after it was disconnected, so nothing was sent.", why: "An embedded engine's AI calls reach only the providers and keys its host passed as values. Falling back to a process.env key, ~/.gbrain/config.json or the process-wide gateway would spend another brain's key and send this brain's text where its host never pointed it.", docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass the provider in settings.ai.providers (apiKey, and baseUrl when it is not the default) to openEngine, or point settings.ai.models (or settings.embedding) at a provider the engine has.' },
  engine_scope_required: { class: 'caller', summary: "An AI call (embed, chat, expansion or rerank) ran outside any engine scope while this process holds engines opened from settings, so nothing was sent.", why: "With no scope the call's brain is unknown. Using the process gateway, a process.env key or ~/.gbrain/config.json would spend a key no brain's host gave and could send one brain's text where its host never pointed it, so the call refuses whatever process gateway the host configured.", docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Run the call inside withEngineScope(engine, fn) for the engine it belongs to, or withLocalScope(fn) for a call that belongs to the process gateway (both exported from gbrain/engine-open).' },
  engine_settings_invalid: { class: 'caller', summary: "A setting passed to openEngine is missing or malformed (engine kind, database url or path, pool size, host or writer id, writer credential or lane, embedding identity), so nothing was opened or registered.", docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Correct the setting the message names and call again.' },
  engine_capability_missing: { class: 'caller', retryable: false, reasons: ENGINE_CAPABILITIES, summary: "The brain's engine does not implement the capability this call needs (reason names it), so the call was refused before any work and nothing was written.", why: 'The Rust engine preview grows one capability at a time. A call that needs a capability it does not report is refused up front instead of running part of the way; detail names the member, the capability and whether anything was written (written=nothing unless the outcome is partial or unknown).', docs: 'docs/ENGINES.md#the-rust-engine-shell', suggestion: 'Run the call on a pglite or postgres brain, or wait for a gbrain release whose Rust engine reports the capability.' },
  engine_graduated: { class: 'caller', summary: "A client opened a PGLite brain that moved to Postgres; its old path holds a tombstone.", docs: 'docs/guides/move-to-postgres.md#graduated-datastore' },
  // wave 18b (GBRA-106) #4772: onboarding coverage checks read entity types from the active pack(s).
  entity_types_unavailable: { class: 'unavailable', summary: "A schema pack in scope did not load, so the entity page types are unknown; onboarding's entity_link_coverage and timeline_coverage warn instead of grading the old hardcoded type list.",
    why: "Entity types come from the active pack per source (the get_health predicate). Grading a fixed person/company list would count the wrong population on a pack with its own entity types, so the checks name the sources whose pack failed.",
    suggestion: 'Run gbrain schema active --json (add --source <id> for a named source) to see which pack is active and why it did not load; fix or reinstall the pack, then gbrain onboard --json.' },
  eval_suite_unwired: { class: 'caller', summary: "`gbrain eval run-all` was asked for a suite it does not run in-process (longmemeval or replay); nothing ran.", why: "run-all runs only wired suites (brainbench). Recording a skipped run and exiting 0 would read as a completed sweep with no numbers behind it.", suggestion: 'Run each requested suite with its own command (`gbrain eval longmemeval <dataset.jsonl> --mode <mode> --record`, `gbrain eval replay --mode <mode>`), once per mode, or drop it from --suites.' },
  explicit_tasks_conflict: { class: 'caller', summary: "SkillOpt was given explicit task lists and a benchmark file; it takes one or the other." },
  export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },
  extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "The drain retries a failed managed atom batch on its own up to 3 times per content (then holds it, code held_failed); this code reports a failed explicit retry, or a failure the drain cannot attribute to a checkpoint, so the same input is not paid for again without approval." },
  extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },
  fact_withdrawn: { class: 'caller', summary: "`remember`, or an owner `gbrain trust release` that writes a held fact into its entity page's `## Facts` table (a managed brain), refused a claim that was explicitly forgotten for this subject (wire `invalid_params`, message prefix `fact_withdrawn:`); nothing was saved, and a refused release leaves the fact held.", why: "A forgotten claim stays withdrawn: remembering the same normalized text does not restore it, and a claim forgotten without an entity is withdrawn for every entity. The additive `withdrawn` object (`at`, `subject`: an entity slug or `all_entities`, `visibility`) says when and how widely the exact claim was forgotten; it covers that exact claim only, and its absence carries no meaning.", legacy_error: 'invalid_params', suggestion: 'Do not retry the same text. Tell the user the claim was forgotten (withdrawn.at, withdrawn.subject); if it is still true, remember it in new words. To link a fact saved without an entity, remember it with entity and replaces set to its fact id instead of forgetting it. For a refused release, do not retry it: drop the hold (gbrain trust drop h<id>) unless the user wants the claim back in new words.' },
  fact_rows_collide: { class: 'caller', summary: "Carrying a page's identity across a rename would drop facts: a fence row of the old page has a different claim in the new file, or the new file does not hold it.", why: "gbrain repair rename-identity merges the two pages' facts only where both say the same thing at the same fence row; anything else would lose one side, so nothing is written.", suggestion: 'Give each old claim its own row in the new file\'s facts fence (or keep the same claim at its row), commit and sync, then preview again; or keep the old page with gbrain restore, or release the hold with --close.', docs: 'docs/guides/repair.md#rename-identity' },
  fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write.", why: "For `forget_fact` the withdrawal is still recorded first (the ledger row and the struck page row), so a later import cannot bring the fact back; any other write changed nothing.", suggestion: 'Do not retry with the same fact id. List the active facts (recall) to find the current one.' },
  fence_row_changed: { class: 'caller', reasons: ['row_missing', 'struck', 'empty', 'visibility', 'text', 'held_row_edited'], summary: "A fact was not indexed from the facts fence row its request names because that row no longer reads back as the fact (removed, struck, emptied, another visibility or other text), or, for an owner release of a held row, because its context or source was edited after the hold (`held_row_edited`, named in the message); nothing was written, and a refused release leaves the fact held.", why: "A facts row derives from its fence row, which Git holds. Indexing a fact at a row that now says something else would make the database disagree with the file, so the write stops and the file stays as it is. For `held_row_edited` the row still reads back, but the owner approved the older context or source, so indexing it would publish content the owner did not review.", suggestion: 'Read the page (gbrain get <slug>) to see the row as it stands; if the fact is still wanted, remember it again, which writes it as a new row. For a refused gbrain trust release, do not remember it and do not release the same hold again (it refuses the same way): drop it (gbrain trust drop h<id>). If the edit was itself held, gbrain trust review lists it separately.' },
  fence_unrenderable: { class: 'server', summary: "A legacy fact row was not adopted into its page's facts fence because the fence codec reads the rendered row back as something other than the stored fact.", why: "The fence trims a claim, folds CRLF to LF, reads `~~x~~` as a struck row and `<br>` as a line break; a claim the codec would change by more than whitespace cannot be written into the fence without changing what it says, so the row stays a legacy row (active and searchable, nothing is lost) and is counted by doctor fence_integrity as unrenderable_legacy_facts. The same code names a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input.", docs: 'docs/guides/write-refusals.md#fence_unrenderable', suggestion: 'Nothing to fix in the page: the rows stay active and searchable. Report the page slug and the reason class with the gbrain version; do not forget or expire a row to clear this count.', fix: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], consent: [], actor: 'agent', why: 'Lists the pages whose legacy fact rows cannot be adopted into their fence and why (by fact id and reason class, never the claim text), read-only.', requires_exclusive: false } },
  fact_not_found: { class: 'caller', summary: "Fact not found." },
  facts_absorb_write_refused: { class: 'caller', summary: "Facts absorb refused the write." },
  facts_backstop_skipped: { class: 'unavailable', summary: "A page write queued no automatic fact extraction; the receipt's `facts_backstop.skipped` reason says why (a `kind:<type>` reason names a page type that is not extracted).", reasons: ['opted_out', 'quarantined', 'body_unchanged', 'extraction_disabled', 'dream_generated', 'subagent_namespace', 'too_short', 'no_parsed_page', 'slug_bound_client', 'operation_bound_client', 'not_imported', 'conversation_pipeline', 'backstop_error'], docs: 'docs/guides/concurrent-writes.md#facts-backstop', suggestion: 'Nothing failed. `opted_out` means the page frontmatter sets `facts_backstop: false`; remove that line and save the page to extract it.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Shows the page frontmatter that decided the skip.', requires_exclusive: false } },
  facts_drain_deferred: { class: 'unavailable', summary: "The automatic facts drain left queued facts-absorb jobs waiting; `reason` says why and `fix`, when present, is the next step. Nothing is dropped: the jobs run on a later drain.", reasons: ['no_key', 'extraction_unavailable', 'budget_exhausted', 'daily_budget_exhausted', 'job_over_budget', 'no_pricing', 'provider_halted', 'drain_error'], docs: 'docs/guides/facts-drain.md#deferrals', suggestion: 'Read doctor `facts_drain`: its message names the cause and its fix the next step (raising a spend cap is paid; ask the user first).', fix: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'], consent: [], actor: 'agent', why: 'Shows the drain status, the backlog and the last error with its fix.', requires_exclusive: false } },
  facts_drain_job_failed: { class: 'server', summary: "A facts-absorb job failed inside the automatic facts drain; it retries with backoff until its attempts run out.", docs: 'docs/guides/facts-drain.md#deferrals', suggestion: 'Read doctor `facts_drain`: its message names the cause and its fix the next step (raising a spend cap is paid; ask the user first).', fix: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'], consent: [], actor: 'agent', why: 'Shows the drain status, the backlog and the last error with its fix.', requires_exclusive: false } },
  facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },
  feedback_disabled: { class: 'host_only', summary: "Retrieval feedback is off (or not learning) on this brain, so ratings are not recorded.", docs: 'docs/guides/retrieval-feedback.md#feedback_disabled' },
  feedback_not_authorized: { class: 'host_only', summary: "This caller may not change the brain's shared ranking for that source.", docs: 'docs/guides/retrieval-feedback.md#feedback_not_authorized' },
  fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },
  file_database_drift: { class: 'caller', summary: "A page's checkout file and its database copy differ, so the writer left both as they are instead of replacing one with the other; the item is held and the rest of the batch continues.", why: "Replacing the file with the database copy (or the database copy with the file) would destroy an edit only the replaced copy holds: a hand edit sync has not imported, an unindexed file at the page's path, or a database edit the file never received (#6982). The file is replaceable only when it equals the live page or one of its recent page_versions rows.", docs: 'docs/guides/write-refusals.md#file_database_drift', suggestion: 'If the file holds the newer edit, run gbrain sync --source <source> to import it; if the database copy is newer, re-save the page with write-through on; when both changed, ask the user which version to keep before retrying.' },
  fix_not_writable: { class: 'host_only', summary: "A gbrain lint fix was not applied because the file refused the write (EACCES, EPERM or EROFS); the file was left unchanged.", why: "Lint repairs files in place, and this file's permissions or a read-only mount stopped the write; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#fix-not-writable', suggestion: "Make the file writable by the user running gbrain, or pass its directory or file name to gbrain lint --exclude, then lint again." },
  file_drift: { class: 'caller', summary: "A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version.", why: "Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database.", docs: 'docs/guides/write-refusals.md#file_drift', suggestion: 'Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file); the preview writes nothing and names any file edit or deletion sync never imported that the database copy would overwrite. Decide with the user: the apply needs their consent (run it without --yes to get the consent message, exit 3, and add --yes only after they agree). The next gbrain sync --source <source> --no-pull re-screens the hold.' },
  file_drift_mixed_selection: { class: 'caller', summary: "gbrain repair file-drift --held selected held pages of more than one Decision (side, or deleted state), so nothing was previewed: one --prefer must not resolve differently shaped drift in bulk.", why: "Each side and deleted state is its own Decision with its own meaning of --prefer file and --prefer database; resolving them together would apply one choice to questions the user answered differently, or not at all.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Preview one Decision at a time with the narrower commands the message names (--held --side <side>, plus --state <state> for --side deleted), or narrow with --only / --skip.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },
  file_drift_state_required: { class: 'caller', summary: "gbrain repair file-drift --held for deleted-side drift needs --state (tombstone_edited, purged_differs or file_gone); nothing was previewed.", why: "In each deleted state --prefer file and --prefer database do opposite things (tombstone_edited: restore and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the file; file_gone: soft-delete the page, or recreate the file), so the state is always named explicitly.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Rerun the preview with --side deleted --state <state>, choosing the state gbrain sources status <source> --json lists for the held files.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },
  file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },
  file_unreadable: { class: 'caller', retryable: false, reasons: ['symlink_in_repo', 'symlink_outside_root', 'symlink_dangling', 'symlink_loop', 'permission_denied', 'not_regular_file'], summary: "Sync held one file because it is not a readable regular file inside the source root (a symlink, a non-regular file or a permission error); the rest of the source synced.", why: "Sync reads only regular files inside the source root and never follows a symlink, which can point anywhere on the host. The file waits in the hold store instead of failing the run, so it never blocks the source, and classic sync re-screens it on every run.", docs: 'docs/guides/write-refusals.md#file_unreadable', suggestion: 'Replace the symlink with the regular file (or delete it), make the file readable to the account that runs gbrain, or leave it out with sync.exclude; the next gbrain sync --source <source> --no-pull re-screens it.' },
  file_wins_rewrite: { class: 'caller', retryable: false, actor: 'user', summary: "gbrain repair file-drift --prefer file refused a page because keeping its file would need a full re-render of the file, not only appended protected parts; nothing was written.", why: "File wins keeps the canonical file's bytes and adds only what reconcile's protections keep from the database: protected frontmatter keys the file lacks and database-only timeline rows, appended. A result that also changes a value, a tag, the title or the body would re-render the whole file (keys reordered, lists re-emitted, rules and headings rewritten), which is not the file winning.", docs: 'docs/guides/write-refusals.md#file_wins_rewrite', suggestion: 'Show the user the page\'s exceptions in the preview. Commit the database-only differences into the file through the door (`gbrain git commit-push`) and preview again, or preview `--prefer database` if the database copy should win.' },
  file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },
  follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
  foreign_table: { class: 'host_only', actor: 'user', retryable: false, summary: "A table gbrain owns by name (an OAuth table) already exists in the brain's schema without a column gbrain always gives it, or with a type gbrain never gives it, so schema setup stopped before the schema replay or any migration changed anything; the message names the table, the column, the type found and the type gbrain needs.", why: "gbrain creates its tables with CREATE TABLE IF NOT EXISTS, so without this check it adopted a same-named table another application created in the shared database, added its own columns to it and failed partway through an upgrade on the first statement that compared the wrong type (#9190). The table holds that application's data, so gbrain never moves, renames or drops it.", docs: 'docs/guides/troubleshooting.md#foreign-table', suggestion: 'Ask the user: give gbrain its own database, or move the other table to a schema of its own (ALTER TABLE <table> SET SCHEMA <other_schema> takes its indexes and constraints along) and point that application there; then run gbrain apply-migrations --force-schema --yes.' },
  forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A caller asked to forget a fact (remote forget) or remove a take (takes_remove) more trusted than its own writes, so nothing was removed and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact or take needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
  reserved_frontmatter_key: { class: 'caller', summary: 'A remote page write tried to add or change a frontmatter key only a trusted derived writer sets (`retired_by`, `retired_at`, `retired_generation`); nothing was written.', why: 'Those keys mark a page a derived writer retired, which the purge holds for 30 days and the repairs treat as machine-owned. A remote caller that could set them could make a page look machine-retired. Carrying the stored value unchanged, or dropping the key, is allowed.', suggestion: 'Remove the key from the frontmatter (or keep the stored value) and write the page again.' },
  generation_fenced: { class: 'retryable', exit: 11, reasons: ['stale_generation', 'pin_moved'], summary: 'A derived result was not published because the live generation or its input changed after the producer read them; nothing was written.', why: 'The generation primitive (GBRA-161) publishes a result only against the generation and input pin it was computed from. A concurrent run that published first (stale_generation), or an input edited since the read (pin_moved), would otherwise let an older result replace a newer one.', docs: 'docs/architecture/generations.md#publishing', suggestion: 'Run the producer again; it reads the current generation and input and recomputes.' },
  generation_held: { class: 'caller', reasons: ['shrunk', 'oversize', 'valve', 'no_proof', 'fence_absent', 'attempts_exhausted', 'segmented_unsupported', 'tie'], summary: 'A derived result was recorded as held instead of published, so nothing it would have retired was retired.', why: 'A model-produced result at or below the input-relative shrink floor (shrunk), one over generations.max_items (oversize), one over the run window retirement budget (valve), an empty result without a proof the input is really empty (no_proof, fence_absent), repeated failed attempts on one input (attempts_exhausted) a segmented page the ledger cannot keep a copy of (segmented_unsupported) or a ranked result whose cut is ambiguous (tie) would retire live items on evidence the primitive does not accept (GBRA-161 D4/D5).', docs: 'docs/guides/repair.md#generations', suggestion: 'Preview the held set with gbrain repair generations --kind <kind> --mode release-held --held --since <restore_days>d. shrunk, valve and attempts_exhausted publish once with --apply --expect <hash> --yes after the user agrees; oversize needs gbrain config set generations.max_items first; no_proof, fence_absent, segmented_unsupported and tie clear only when the input or the producer result changes.', fix: { argv: ['gbrain', 'doctor', '--only', 'generation_held', '--json'], consent: [], actor: 'agent', why: 'Lists the held generations by kind and reason with their preview commands, read-only.', requires_exclusive: false } },
  generation_live_conflict: { class: 'retryable', exit: 11, summary: 'A derived generation was not activated because one of its items was not live at the content the publication wrote; nothing was committed.', why: 'Activation rechecks every item of the new generation under the key lock; an item another writer changed or deleted in between would make the ledger record a set that is not what the pages say.', docs: 'docs/architecture/generations.md#publishing', suggestion: 'Run the producer again; it reads the items as they are now.' },
  frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },
  full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
  gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
  ghost_mass_delete_refused: { class: 'consent', summary: "gbrain repair ghost-pages refused to soft-delete more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to ghost pages: that many missing canonical files almost always means the checkout is the wrong path, unmounted or half-cloned, not that the files were deleted.", docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Check the source checkout on its owner host first. If removing these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host, to check the checkout before anything is removed.", requires_exclusive: false } },
  notifier_stalled: { class: 'retryable', actor: 'agent', summary: "The commit notifier kept a source due through every retry tier (5 s, 15 s, 1 min, 5 min) without the sync making progress; it keeps retrying every 5 minutes.", why: "A commit-triggered sync failed or was refused the same way on every attempt, so the commit is still not searchable; the notifier block in gbrain sync status names the last error and the trace file with every attempt.", docs: 'docs/guides/on-commit-sync.md#notifier-stalled', suggestion: 'Run gbrain sync --source <id> --no-pull in the foreground to see the error, fix its cause, then read gbrain sync status --source <id> --json (the notifier block) to confirm the source is current.' },
  moved_pages_mass_fold_refused: { class: 'consent', summary: "gbrain repair moved-pages refused to fold moved pages amounting to more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to moved pages (GST-2584): that many moved pages at once almost always means a re-import under other paths or the wrong checkout, not a backlog.", docs: 'docs/guides/repair.md#moved-pages', suggestion: 'Check the source and its checkout first. If folding these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.' },
  origin_twin_mass_merge_refused: { class: 'consent', summary: "gbrain repair origin-twins refused to merge duplicate-origin twins amounting to more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to origin twins (#6948): that many twins at once almost always means a re-import under other slugs or the wrong checkout, not a backlog.", docs: 'docs/guides/repair.md#origin-twins', suggestion: 'Check the source and its checkout first. If merging these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.' },
  ghost_storage_unknown: { class: 'unavailable', summary: "Ghost pages of a source cannot be classified because its canonical checkout cannot be read reliably; nothing was listed or changed.", why: "A page is never reported or removed as a ghost while its file may only be unreadable: a missing or non-directory root (storage_unavailable), or a stat error, an invalid gbrain.yml or an inconclusive page check (ambiguous_storage), fails closed.", reasons: ['storage_unavailable', 'ambiguous_storage'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair ghost-pages --source <id> again.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host.", requires_exclusive: false } },
  git_branch_unborn: { class: 'host_only', summary: "The canonical checkout's branch has no commit yet, so Git durability has nothing to build on.", why: "A Git effect commits on top of HEAD and pushes the branch; on an unborn branch (a fresh `init --git` root) there is no HEAD to commit on and no ref to push, so enabling durability would park every effect. The database is unaffected.", suggestion: 'Make the first commit on the branch on the brain host (git add -A && git commit -m "Initial brain"), then rerun gbrain sources writer git-durability <source> --enable.' },
  // wave 18b (GBRA-106) #5182: activation warns per source whose Git effects it would leave skipped.
  git_durability_not_enabled: { class: 'host_only', summary: "A filesystem source's owner will not commit or push its page writes (Git durability is off, or not recorded and no harden post-commit hook is installed), so its Git effects complete as skipped; writer activate still proceeds and lists it under warnings.",
    why: "Activation applies the effect runner's own policy: the binding's recorded setting decides, and only when nothing is recorded does the legacy hook decide (a failed probe counts as not durable). sources harden is refused once the brain is managed, so the recorded setting is the way to turn durability on.",
    docs: 'docs/guides/concurrent-writes.md#git-durability-at-activation',
    suggestion: 'Preview gbrain sources writer git-durability <source> --enable --dry-run on the owner host, then apply it with --admin-intent writer_git_durability; enabling re-queues the Git effects that were skipped while it was off.' },
  git_checkout_required: { class: 'host_only', summary: "The canonical root is not inside a Git checkout, so its Git effects have nothing to commit to.", suggestion: 'Initialize the root as a Git repository with a first commit and a remote on the brain host, then rerun; a database-only source needs no Git durability.' },
  git_worktree_link_broken: { class: 'host_only', summary: "The directory is a linked Git worktree whose link to its repository is broken (the repository's entry was pruned, or the checkout moved), so it cannot be claimed as a canonical worktree; nothing was claimed.", why: 'A linked worktree reaches its commits through a .git file naming an entry in the repository, and the repository names the worktree back. With either link broken, Git commands in the directory fail or the next git worktree prune deletes the entry, so a door commit would go nowhere.', suggestion: 'From the repository, run git worktree repair on the worktree when both still exist, or add the worktree again with git worktree add, then rerun the claim.' },
  hosted_repo_refused: { class: 'caller', reasons: ['source_bound', 'source_has_pages', 'source_has_path', 'source_archived', 'dir_not_empty'], summary: "gbrain sources host-repo starts a hosted repository only for an empty, unbound source and an absent or empty directory; nothing was created.", why: 'The verb makes a new bare repository the source of truth for the source. Existing pages or an existing directory would need converting into it, which is a separate step, so it refuses instead of guessing.', docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#remote-and-hosted-writes', suggestion: 'Pick a new source ID and an empty directory, or keep this source as it is.' },
  git_detached_head: { class: 'host_only', summary: "The canonical checkout is on a detached HEAD, so a push would target the wrong ref.", suggestion: 'Check out the branch the remote should track (git switch <branch>) on the brain host, then rerun.' },
  git_index_conflict: { class: 'caller', actor: 'user', summary: "A strict (canonical: git) write found a staged change of its path that is not committed, so it committed nothing and left the index as it was.", why: "The door commits a path only while the checkout's index entry for it equals HEAD's. Committing over a staged change would overwrite it in the index or publish it under a gbrain commit, so the person who staged it decides first.", suggestion: 'Commit the staged change, or unstage it (git restore --staged -- <path> keeps the file on disk), then retry the write with a new request_id. git diff --cached --name-only -- <path> prints nothing once it is resolved.' },
  git_index_locked: { class: 'retryable', summary: "Another Git process holds the canonical checkout index lock." },
  git_index_stale: { class: 'caller', summary: "Git index stale." },
  git_target_pending: { class: 'retryable', summary: "Git still lists a removed canonical file in the index; the removal was not committed yet." },
  git_operation_in_progress: { class: 'caller', summary: "A rebase, merge, cherry-pick or revert is in progress in the checkout, so gbrain will not commit or move it.", docs: 'docs/guides/shared-checkout-git.md#stuck-rebase' },
  git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },
  git_target_changed: { class: 'caller', actor: 'user', summary: "A strict (canonical: git) write's file changed on disk while it was being committed, so nothing was committed and the write was not published.", why: "The door commits exactly the bytes the write published, and checks the file's hash against them before and after Git stores it. An edit landing in between would otherwise be committed while the database records other content; recovery leaves the changed file as it is.", suggestion: "When the file holds neither the write's bytes nor the version before it, the write is held in recovery (blocked reason unexpected_file_bytes) and the source's later writes wait behind it; when it holds the version before the write, nothing is held and the write failed; when it holds the write's own bytes again by the time recovery runs, recovery restores the version before the write and the write failed, with nothing held. After a failure, read the page before resubmitting it with a new request_id. To resolve a held write, preview with gbrain repair stuck-recovery --source <id> --json, ask the user which version to keep, then run gbrain repair stuck-recovery --source <id> --keep disk|prior --apply --expect <preview_hash> --yes (disk keeps the edit).", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held request, its source and its blocked reason.', requires_exclusive: false } },
  git_target_ignored: { class: 'caller', summary: "A .gitignore rule excludes the canonical file, so its Git effect cannot commit it; the effect parks at once.", suggestion: 'Remove or narrow the rule and commit that change, then run gbrain sources writer retry-effects <source> --parked-code git_target_ignored; or keep the file out of Git and leave the effect parked.' },
  git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },
  git_command_stopped: { class: 'retryable', summary: "A git command was stopped before it finished (its time limit, an output limit, a signal from outside gbrain, or git crashing on a signal such as SIGSEGV), so gbrain did not use its partial output.", why: "The child ended without exiting on its own (unless it crashed, git itself works), and a cut-off listing read as the answer would stage, restore or report the wrong files.", reasons: ['timeout', 'output_limit', 'signal'], docs: 'docs/guides/shared-checkout-git.md#outcomes', suggestion: 'Rerun the same command once. For a signal, check the machine first (the out-of-memory killer or a supervisor), or for a crash run git fsck on the checkout; if it stops again, tell the user which command and checkout.' },
  git_unavailable: { class: 'retryable', summary: "A git command did not complete." },
  git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone; a partial clone that lacks a tree of the synced commit stops the run.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'In a partial clone (git clone --filter), which sync never fetches from, fetch the blob with git cat-file -p <blob> in the checkout or check the file out, or, when the run stopped on a missing tree, run the git ls-tree -r -d <commit> it names; otherwise run git fsck in the checkout to see what is missing and restore it with git fetch (a shallow clone) or from a backup. Then sync again; every sync re-tests the hold.' },
  git_conversion_blocked: { class: 'consent', actor: 'user', summary: "Converting a source to git-canonical would discard database content or cannot place it, so the apply wrote nothing.", reasons: ['both_moved', 'held_drift_both', 'held_drift_unknown_differs', 'deleted_in_git', 'uncommitted_edit', 'ignored_target', 'unparseable', 'unsafe_path', 'segmented_page', 'export_mismatch', 'git_overwrites_database', 'ignore_status_unknown', 'no_record_both_moved', 'no_record_no_evidence'], why: "gbrain sources canonical --to git applies only when every database row will be in Git or in a declared database-only class afterwards. The preview counts what would be lost or cannot be placed by category (detail lists them): both_moved and held_drift_both, a page Git and the database both changed; no_record_both_moved and no_record_no_evidence, a page with no import record whose content history shows both sides moved, or shows nothing, until the owner's --decisions file decides it; deleted_in_git, a page Git deleted that the database edited since; uncommitted_edit, a working-tree edit the adoption would overwrite; ignored_target, a page whose file Git ignores without a declared class; unparseable and unsafe_path, a committed file or path sync cannot read; segmented_page, a segmented page conversion does not adopt yet; export_mismatch, a page whose export does not read back equal; git_overwrites_database, a page version a strict pass would replace that nothing accepted; ignore_status_unknown, a target whose ignore status Git cannot read (beyond a symlink, outside the checkout, a timed-out check). There is no override.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Relay the categories and their paths (the --dry-run preview lists them) and ask the user how each should be resolved; preview again afterwards.' },
  git_conversion_delta: { class: 'consent', actor: 'user', summary: "An approved conversion found pages that changed since the approval, or decisions it did not approve, so only the unchanged pages were applied and the source stays mixed.", why: "gbrain sources canonical --to git --apply --approved applies only the pages whose slug, revision, committed blob, evidence and action are the ones the owner approved. A page that changed since, a new page, a database edit the plan would now discard, and any decision the approval did not hold stay unapplied and are listed (delta) with counts; nothing outside the approved set is applied without a new decision.", docs: 'docs/guides/git-canonical.md#approval-across-time', suggestion: 'Relay the delta list and its counts to the owner; once they decide, preview again with --approval-out and apply the new approval.' },
  conversion_file_in_source_root: { class: 'caller', summary: "A conversion review list, decisions file or approval was refused because its path is inside a source's checkout.", why: "Those files name pages and paths. Written or read only outside every registered source root and the Git working tree holding it (mode 0600), they can never be synced, imported or committed.", docs: 'docs/guides/git-canonical.md#review-list-and-decisions', suggestion: 'Pass a path outside every source checkout, e.g. under ~/.gbrain.' },
  git_conversion_incomplete: { class: 'retryable', summary: "A git-canonical conversion stopped because its strict pass did not finish, finished with work left after the flag was set, or found the flag removed (a --to mixed apply) while it ran.", why: "The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after, then up to three closing strict passes while only door commits a live writer landed meanwhile are left (Git ahead of the database). A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash.' },
  git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet, or a fact for a page-less entity under an exact page rule, which no holding page can carry (create the page with put_page, then remember again).", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },
  git_private_commit_refused: { class: 'caller', summary: "A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged.", reasons: ['private', 'alias_private', 'lineage_private'], why: "Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes.", docs: 'docs/guides/write-refusals.md#git_private_commit_refused', suggestion: 'The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id.' },
  git_protocol_required: { class: 'host_only', summary: "A write reached a git-canonical source from a process that does not declare the git-canonical protocol (an older gbrain, or gbrain.write_sources set by hand); nothing was written.", docs: 'docs/guides/write-refusals.md#git_protocol_required', suggestion: 'Upgrade or stop the gbrain process that wrote it (gbrain upgrade on its host), then retry with a new request_id.' },
  git_lfs_not_enabled: { class: 'caller', summary: "A git-canonical write falls under a Git LFS rule, but storage.git_lfs is off or the checkout does not configure the LFS filter; nothing was written.", reasons: ['opt_in_off', 'checkout_unconfigured'], why: "The door commits a file before its database row. A path .gitattributes routes through Git LFS commits as an LFS pointer only when the checkout configures the LFS filter (git lfs install --local) and the operator opted in; otherwise the raw bytes would be committed.", docs: 'docs/guides/write-refusals.md#git_lfs_not_enabled', suggestion: 'Ask the user: configure git-lfs in the checkout and run gbrain config set storage.git_lfs true, or narrow the .gitattributes rule; then submit again with a new request_id.' },
  gitlink_not_followed: { class: 'caller', summary: "A classic sync range added a gitlink (a submodule or an embedded repository); sync does not follow it, so the linked repository's files are not indexed.", why: "A gitlink records another repository's commit, not files, and that repository may be absent or uninitialized. The rest of the source syncs; the notice (`gitlinks_not_followed` in the result and one stderr line) comes once, in the run that passes the gitlink.", docs: 'docs/guides/write-refusals.md#gitlink_not_followed', suggestion: 'Nothing is blocked. To index the linked repository, check it out and add the checkout as its own source (gbrain sources add <name> --path <checkout>).' },
  graduation_drain_timeout: { class: 'retryable', summary: "Queued or running writes did not drain within --drain-timeout; the move stopped before copying and the source is unchanged.", docs: 'docs/guides/move-to-postgres.md#drain', reasons: ['progressing', 'blocked'], exit: 11 },
  graduation_embedding_dimension_mismatch: { class: 'caller', summary: "An existing, non-empty target database has a different embedding column layout than the brain being moved.", docs: 'docs/guides/move-to-postgres.md#embeddings' },
  graduation_foreign_host_binding: { class: 'host_only', summary: "A source's worktree is owned by another host, so this host cannot move it to Postgres.", docs: 'docs/guides/move-to-postgres.md#hosts' },
  graduation_in_progress: { class: 'retryable', summary: "Another process is moving this brain to Postgres; neither engine may be opened until it finishes.", docs: 'docs/guides/move-to-postgres.md#in-progress', exit: 75 },
  graduation_interrupted: { class: 'unavailable', summary: "An engine graduation stopped before it finished and no process owns it.", docs: 'docs/guides/move-to-postgres.md#resume' },
  graduation_rollback_writes_lost: { class: 'consent', summary: "Rolling back to PGLite would drop changes made on Postgres since the move.", docs: 'docs/guides/move-to-postgres.md#rollback', reasons: ['user_data', 'security_changes'] },
  graduation_source_writer_held: { class: 'host_only', summary: "A live serve or daemon holds the PGLite brain and did not hand it over to the move.", docs: 'docs/ENGINES.md#graduation-writer-held' },
  graduation_split_brain: { class: 'unavailable', summary: "A different brain appeared at the graduated brain's old path; the target is withheld from authority until the user decides.", docs: 'docs/guides/move-to-postgres.md#split-brain' },
  graduation_target_auth_failed: { class: 'caller', summary: "The target database rejected the credentials recorded for this move.", docs: 'docs/guides/move-to-postgres.md#credentials' },
  graduation_target_ddl_unreachable: { class: 'unavailable', summary: "The target's direct (schema) connection is unreachable or names a different database than its main URL.", docs: 'docs/guides/move-to-postgres.md#ddl-connection' },
  graduation_target_not_empty: { class: 'caller', summary: "The target database already holds data that is not this move's.", docs: 'docs/guides/move-to-postgres.md#target-not-empty' },
  graduation_target_unsupported: { class: 'caller', summary: "The target database is missing a prerequisite (server version, vector extension with halfvec, CREATE privilege or a matching column).", docs: 'docs/guides/move-to-postgres.md#target-requirements', reasons: ['server_version', 'vector', 'halfvec', 'create_privilege', 'column', 'env_override'] },
  graduation_unclassified_table: { class: 'server', summary: "A database has a relation the graduation inventory does not classify, so moving it could lose data.", docs: 'docs/guides/move-to-postgres.md#inventory', reasons: ['newer_schema', 'missing_inventory_row'] },
  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'] },
  grant_scope: { class: 'host_only', actor: 'user', summary: "A managed sync pass ran under a grant that covers only part of the source, so it admitted what the grant can see and cannot finish (stamp) the source.",
    why: "A slug-fenced grant never stamps a pass (design v3.2 §5): converging the whole source needs a writer that can see every page, which is the owner host's own sync.",
    docs: 'docs/guides/write-refusals.md#drain-grant-scope',
    suggestion: 'On the host that owns the source, run gbrain sync --source <id> --no-pull; check the result with gbrain sync status --source <id> --json.' },
  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 } },
  head_blocked: { class: 'server', retryable: false, actor: 'host_admin',
    summary: "The queued write at the head of a managed source cannot be claimed by any consumer, and its blocker needs an operator; a managed sync drain stops `drain_stalled` with `cause: head_blocked` and `blocked_by` names the predicate.",
    why: "#6543: the drain used to wait the whole no-progress window and print a constant `claimable here: no`. The head probe evaluates each predicate of the claim query for the head itself. Only intervention-required blockers stop the drain, after one governor tick of confirmation: a refresh fence no refresh process holds, or a running request ahead held by a process that reports restart_required. Live blockers (a foreground publication, a lapsed lease, a refresh or recovery making progress) keep the progress-aware wait.",
    reasons: ['refresh_fence', 'zombie_publication'],
    docs: 'docs/guides/write-refusals.md#head-blocked',
    suggestion: 'Run next.fix: for refresh_fence resume the refresh (gbrain sources refresh <source> --resume); for zombie_publication restart the named gbrain process on the brain host. Then rerun the same sync.',
    fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: names the blocker of every queued head (predicate, ids, owner) and, when the caller may cancel the blocking request, the cancel-write-request command.', requires_exclusive: false } },
  held_failed: { class: 'unavailable', summary: "A managed atom origin (a page or transcript) failed atom extraction 3 times on the same content, or its atom write did not commit 3 times, so the drain stopped retrying it; doctor `extract_atoms_held_failed` lists it with its last request id.", why: "Every automatic attempt is a paid model call. After MAX_DETERMINISTIC_FAILURES completed failures of one content the origin leaves the atom backlog instead of being paid for every cycle; a batch whose write did not commit is struck each time the drain meets it, with no model call, and held at the same bound (#7514). Editing the content starts a new count, and an explicit retry runs it again.", fix: { argv: ['gbrain', 'doctor', '--only', 'extract_atoms_held_failed', '--json'], consent: [], actor: 'agent', why: 'Lists the held atom origins with their last request id, failure and retry command, read-only.', requires_exclusive: false } },
  held_out_overlaps_benchmark: { class: 'caller', summary: "Held out overlaps benchmark." },
  held_out_required_for_bundled: { class: 'caller', summary: "Held out required for bundled." },
  idempotency_conflict: { class: 'caller', summary: "The request_id already belongs to a different accepted operation." },
  independent_principal_required: { class: 'consent', summary: "This local CLI principal already owns another source/destination for this harness." },
  insufficient_scope: { class: 'host_only', summary: "The connection lacks the OAuth scope the operation requires.", legacy_error: 'permission_denied' },
  integrate_conflict: { class: 'consent', summary: "Local and remote commits changed the same file; nothing was merged and the checkout is unchanged.", docs: 'docs/guides/shared-checkout-git.md#conflicts', actor: 'user' },
  internal: { class: 'server', summary: "A memory verb failed on the server; this is not a caller mistake." },
  internal_error: { class: 'server', summary: "The server failed while running the operation; this is not a caller mistake." },
  interrupted: { class: 'server', summary: "The operation was interrupted by a signal before it finished.", exit: 130 },
  invalid_acknowledgment: { class: 'caller', summary: "The shared-skills delivery acknowledgment does not match a batch issued to this enrollment.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
  invalid_client: { class: 'caller', summary: "Google connect credential error: invalid client.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  invalid_connector_text: { class: 'caller', summary: "Invalid connector text." },
  invalid_fence: { class: 'caller', summary: "A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written.", why: "Facts and takes fences are the page's structured rows. Importing a fence that does not parse, repeats a marker or reuses a row number would silently drop or renumber rows, so coordinated writers refuse it and managed sync holds the one file while the rest of the source syncs.", reasons: FENCE_REASON_CODES, legacy_error: 'invalid_params', docs: 'docs/guides/write-refusals.md#invalid_fence', suggestion: 'A refused write: fix the fence the message names (fence, section and rows; the reason says what is wrong) and send the page again with a new request_id, or write rows with remember / takes_add. A held file or stored page: the maintenance run repairs it; preview it now with gbrain repair fences --source <id> on the brain host.' },
  invalid_frontmatter: { class: 'caller', summary: "The file's YAML frontmatter cannot be read without guessing, so it was not imported.", why: "gbrain imports frontmatter it can read exactly (quoting an unquoted value at most). Guessing could store a wrong title, merge a duplicate, or read a protected key such as `visibility` as a broader value.", reasons: ['yaml_parse', 'needs_interpretation', 'ambiguous_identity_key', 'ambiguous_protected_key'], suggestion: 'Fix the named line in the file (one line per key, the whole value quoted), then commit and sync or import again.' },
  invalid_grant_clock_skew: { class: 'caller', summary: "Google connect credential error: invalid grant clock skew.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  invalid_grant_revoked: { class: 'caller', summary: "Google connect credential error: invalid grant revoked.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  invalid_grant_testing_expiry: { class: 'caller', summary: "Google connect credential error: invalid grant testing expiry.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  invalid_params: { class: 'caller', summary: "A parameter is missing, has the wrong type, or has an invalid value.", exit: 2 },
  invalid_rating: { class: 'caller', summary: "A rating must be an integer from 1 to 5.", docs: 'docs/guides/retrieval-feedback.md#invalid_rating' },
  invalid_receipt: { class: 'server', summary: "A company-source ingestion receipt input failed validation inside gbrain; nothing was written.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
  invalid_receipt_transition: { class: 'caller', summary: "An ingestion receipt cannot skip a phase or complete while files failed, writes are pending or verification failed.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
  invalid_request: { class: 'caller', summary: "submit_agent over the local CLI: use `gbrain agent run` instead." },
  invalid_source: { class: 'caller', summary: "The source argument or source state is invalid for this operation." },
  invalid_source_pin: { class: 'caller', summary: "The .gbrain-source pin names an invalid source id." },
  invalid_source_uri: { class: 'caller', summary: "The page has a stored file source_uri that cannot be resolved to a local filesystem path." },
  invalid_token: { class: 'host_only', summary: "The bearer token is missing, invalid, or revoked." },
  invalid_write_wait: { class: 'caller', summary: "Invalid write wait." },
  ipc_path_too_long: { class: 'host_only', summary: "The brain's local IPC socket path is longer than the operating system allows, even after the per-user run-dir fallback, so hooks and local commands cannot reach gbrain serve.", why: 'A Unix-domain socket path must fit sockaddr_un (107 bytes on Windows afunix, 103 on macOS); on Windows a long PGLite data-dir path already moves to %USERPROFILE%\\.gbrain\\run, and only a profile path too long for that is reported.', docs: 'docs/guides/troubleshooting.md#ipc-path-too-long', suggestion: 'Stop gbrain serve, move the brain to a shorter path (`gbrain config set database_path <shorter path>` after moving the data directory), then restart serve.', fix: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the socket path, its byte count and the limit.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'ipc_socket_path', '--json'] } } },
  legacy_twin_mass_merge_refused: { class: 'consent', summary: "gbrain repair legacy-twins refused to merge legacy twin pairs that are more than half of a source's file-backed pages; nothing was changed.", why: "The sync mass-delete valve (#2828) applied to legacy twins: each merge soft-deletes a file-backed twin, and that many twins at once almost always means a re-import under another slug fold or the wrong checkout, not a backlog of forked pairs.", docs: 'docs/guides/repair.md#legacy-twins', suggestion: 'Check the source and its checkout on the owner host first. If merging these pairs is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host, to check the checkout before anything is merged.", requires_exclusive: false } },
  legacy_twins_storage_unknown: { class: 'unavailable', summary: "Legacy twin pairs of a source cannot be checked because its canonical root is missing or is not a readable directory; nothing was listed or changed.", why: "Whether a twin's file is still there and agrees with it is only known from the checkout, so the repair fails closed rather than merge on a guess.", reasons: ['storage_unavailable'], docs: 'docs/guides/repair.md#legacy-twins', suggestion: 'Inspect the source checkout on its owner host (writer status shows its root), fix it, then preview gbrain repair legacy-twins --source <id> again.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's canonical root and owner host.", requires_exclusive: false } },
  legacy_job_selection_invalid: { class: 'caller', summary: "The legacy job selection is invalid." },
  legacy_jobs_active: { class: 'caller', summary: "Legacy jobs are still active." },
  legacy_lock_removal_refused: { class: 'host_only', summary: "`gbrain pglite-repair --legacy-lock` refused to move a legacy PGLite lock aside: a process on this host still uses the data dir, the data dir is on a network or shared filesystem, or gbrain could not confirm the filesystem is local.", why: "The evidence the repair reads (kill -0, the process command, an open-file scan) covers only this host and PID namespace. A process that still holds the data dir, or a filesystem other hosts can mount or whose locality cannot be confirmed (neither Linux nor macOS, a failed probe, an unrecognised type, a macOS mount without the local flag), means the old owner may still be writing, and removing its lock would let two writers corrupt the brain.", reasons: ['live_holder', 'network_filesystem', 'filesystem_unverified'], docs: 'docs/ENGINES.md#legacy-pglite-lock', suggestion: 'Stop the process the message names (on a shared filesystem: every gbrain on every host that mounts it), then preview again with gbrain pglite-repair --legacy-lock --dry-run. For filesystem_unverified, run the repair on a Linux or macOS host where the folder is on a local disk; elsewhere only the user can confirm no gbrain on any computer reaches the folder and move the lock folder aside.' },
  // #6876: get_links / get_backlinks continuations are bound to their listing.
  link_cursor_invalid: { class: 'caller', summary: "A get_links / get_backlinks cursor was not one this listing returned: it belongs to another slug, direction, source scope or filter set, or is not a cursor.", why: "A cursor is a link-id position bound to the exact listing that issued it; continuing a different listing from it could skip or repeat edges without saying so. Nothing was read.", legacy_error: 'invalid_params', suggestion: 'Restart the listing with the same slug and filters and no cursor, then pass each next_cursor unchanged.', fix: { argv: ['gbrain', 'links', '{slug}'], mcp: { tool: 'get_links', arguments: { slug: '{slug}' } }, consent: [], actor: 'agent', why: 'Restarts the listing from its first page (read-only); pass each next_cursor it returns unchanged.', requires_exclusive: false, verify: { mcp: { tool: 'get_links', arguments: { slug: '{slug}', limit: 1 } } } } },
  link_dates_unattributed: { class: 'caller', summary: "add_link or remove_link would re-create or change a links section whose dated statements were stored before each row kept its own dates, and gbrain cannot tell which row each date belongs to; nothing was changed.", why: "Each row of a page's links section (target, type, source) keeps its own valid_from and valid_until. Statements stored before that have no source: with several rows for one target and type, or dates that do not fit the one row, any pairing would be a guess that could put one row's dates on another.", reasons: ['several_rows', 'dates_do_not_fit'], suggestion: "Add the page's ## Links section back with edit_page, one row per source with that row's own valid_from and valid_until, then submit the request again." },
  local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },
  lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },
  loops_extraction_skipped: { class: 'unavailable', summary: "A Google sweep or the managed catch-up queued no paid loop extraction; the sync summary's `skipped_reason` says why. Nothing failed and the email pages still imported.", why: "Extraction is gated before any model call: a kill switch, a missing chat provider, the day's spend cap (`loops.extraction_max_usd_per_day`, default $2.00; `spend_cap_zero` means the user set it to 0), or an exclusion label (`g_loops_exclude_labels` / `loops.extraction_exclude_labels`) that did not resolve against the account's labels, which fails closed until a sweep resolves it.", reasons: ['no_candidates', 'extraction_disabled', 'chat_unavailable', 'enqueue_failed', 'daily_spend_cap', 'spend_cap_zero', 'excluded_label', 'excluded_label_unresolved'], docs: 'docs/guides/open-loops.md#two-detectors', suggestion: 'Read the reason. `daily_spend_cap` clears at the next UTC day or when the user raises `loops.extraction_max_usd_per_day`; `excluded_label_unresolved` names the label token to fix in `gbrain sources status <id>` or `gbrain config get loops.extraction_exclude_labels`; the threads are extracted on their next touch or by `gbrain sync --source <id> --full`.', fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the last sweep\'s loop extraction report with its skipped_reason and the unresolved label tokens.', requires_exclusive: false, verify: { argv: ['gbrain', 'config', 'get', 'loops.extraction_max_usd_per_day'] } } },
  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, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, 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_failure_unsettled: { class: 'caller', summary: "The recorded managed sync failure is not settled by the imported state, so it was not acknowledged.", why: "Acknowledging removes a failure record only when the file it failed on is already imported unchanged (or deleted in both the commit and the brain); anything else would hide content that never reached the brain.", suggestion: 'Resume or retry the sync the failure names (gbrain sync status --source <id> --json shows it), then acknowledge again if the record remains.' },
  managed_remedy_unavailable: { class: 'caller', summary: "gbrain repair rename-identity cannot carry a page identity on a managed source; nothing was written.", why: "On a managed brain page tables change only through coordinated publications, and the carry is a classic-source maintenance transaction, so on a managed source the remedy can only close the pair.", suggestion: 'Release the purge hold without carrying identity: preview gbrain repair rename-identity --source <id> --slug <new-slug> --close, then run the apply command it prints after the user agrees; or keep the old page as its own page with gbrain restore <old-slug> --source-id <id> --force.', docs: 'docs/guides/repair.md#rename-identity' },
  memory_setting_write_outcome_unknown: { class: 'server', retryable: false, summary: "A memory writeback setting change did not confirm, so it may or may not have been saved.", why: "A database write that throws can be a rollback or a lost acknowledgement, and the two look the same to the caller. The setting and its audit row commit together, so a re-read shows which happened.", docs: 'docs/guides/ambient-writeback.md#reading-and-changing-it-remotely', suggestion: 'Call get_memory_settings to read the mode in effect, and change it again only if the change did not land.' },
  merge_recommended: { class: 'caller', retryable: false, actor: 'user',
    summary: "The content-repair model judged a held file and the page its frontmatter `slug:` names to be the same page, so gbrain recommends merging them instead of removing the slug line; nothing was written.",
    why: "A `frontmatter_slug_conflict` hold whose two sides describe the same person, company or topic is a duplicate, and the deterministic repair (delete the `slug:` line) would mint a second page for it. gbrain does not merge pages by itself yet (a lossless merge needs a coordinated two-page write with both revisions, withdrawal and metadata preservation; it ships separately), so the lane records the recommendation on the hold as codes and slugs (`meta.content_repair`: the canonical slug that keeps the page), `gbrain sync status` renders a paragraph for a person, and nothing retries it until the file changes.",
    docs: 'docs/guides/write-refusals.md#merge_recommended',
    suggestion: 'Show the user the paragraph gbrain sources status <id> --json renders for the hold (the path, the canonical slug and the recommendation). After they agree, merge the unique sections of the duplicate into the canonical page, delete the duplicate file, commit, and run gbrain sync --source <id> --no-pull; the hold clears on that sync.',
    fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,
      why: 'Read-only: lists the held file with the canonical slug gbrain recommends and the rendered paragraph; merging two pages is the user\'s decision.',
      verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
  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'] } } },
  movement_unknown: { class: 'server', retryable: true, actor: 'agent',
    summary: "`gbrain sources writer movement` could not read the managed sync backlog, so whether sync work is pending is unknown.",
    why: "A failed backlog read is not an empty backlog: reading it as `nothing_pending` turned a stalled sync into an all-clear. The movement reader reports `movement_state: unknown` (`unknown.reason: backlog_read_failed`) on every surface, doctor warns, and the movement command exits 1 with this code instead of `managed_sync_not_moving`.",
    reasons: ['backlog_read_failed'],
    docs: 'docs/guides/troubleshooting.md#managed-sync-not-moving',
    suggestion: 'Rerun gbrain sources writer movement <id>; if the backlog read keeps failing, run gbrain doctor --json.',
    fix: { argv: ['gbrain', 'sources', 'writer', 'movement', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: reads the managed sync backlog again and judges movement over one window.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },
  managed_sync_flag_refused: { class: 'caller', summary: "A managed source refuses --skip-failed and --include-gitignored, and a strict (git-canonical) source also refuses --working-tree: managed sync keeps every failed-receipt and ignored-file guard and a strict source indexes commits only, so the run was refused before anything ran.",
    why: "--skip-failed would acknowledge a failed receipt instead of retrying it, and --include-gitignored would import files Git ignores; neither has a managed meaning. `detail` names the flag.",
    docs: 'docs/guides/write-refusals.md#managed_sync_flag_refused',
    suggestion: 'Rerun the same gbrain sync command without the named flag; fix a failed file and the plain sync retries it, or commit an ignored file to sync it.',
    fix: { argv: ['gbrain', 'sources', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists each source with its recorded failures and held files, the work the refused flag would have skipped.',
      verify: { argv: ['gbrain', 'sources', 'status', '--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' },
  membership_not_found: { class: 'caller', summary: "This principal has no shared-skills membership with that installation id.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
  method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },
  migration_lease_lost: { class: 'server', summary: "This apply-migrations run's own migration lease no longer matched its fence, so it stopped before the next migration.",
    why: 'The lease row still names this process (pid and host), but the fenced refresh matched no row: the direct and main database connections may reach different databases, or the row was rewritten. The details say whether the acquisition token and acquisition time still match (never the token itself). Run `gbrain doctor --json` and report it (#6028).' },
  migration_declined: { class: 'consent', exit: 3, actor: 'user', summary: "An explicit apply-migrations --migration named a migration the brain's config declines, so nothing was run or written.",
    why: "The migration's opt-out key (for v0.53.0: shared_skills.migration.enabled=false) is brain-level config shared by every machine on that database; an explicit run from one machine would rewrite config for all of them, so the runner refuses instead of overriding the owner's choice. Ordinary runs skip a declined migration and list it as declined.",
    suggestion: 'Do not retry. Tell the user the migration is declined on this brain and give them the fix command (gbrain config set <key> true) if they want it to run; --list --json shows it declined.' },
  migration_failed: { class: 'server', summary: "A migration orchestrator failed, so the migration chain stopped; finished migrations stay recorded.",
    reasons: ['orchestrator_failed', 'orchestrator_threw', 'ledger_write_failed', 'preview_failed', 'schema_failed'] },
  migration_host_work_pending: { class: 'host_only', summary: "A migration's mechanical checkpoint is recorded, but its stored report still names host work (for v0.53.0 a source's inventory, writer, projection or publication-policy stage, or a brain-level pending action); apply-migrations --list shows it applied_pending_host_work.",
    why: 'The ledger row is complete so the schema work never reruns, and v0.53.0 records apply_migrations_pending on every run because member enrollment is never verified, so the stored report decides (#6796): unenrolled members and sources that opted out are not host work. The next apply-migrations --yes re-check rewrites the report once the work is done.',
    docs: 'docs/guides/shared-brain-skills.md#migrate-an-existing-brain',
    suggestion: 'Run the read-only inventory `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host, do each source\'s next step it names (ask the user before publishing or activating), then run `gbrain apply-migrations --yes`.',
    fix: { argv: ['gbrain', 'apply-migrations', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists each migration\'s status and the read-only inventory command for host work still pending; changes nothing.', requires_exclusive: false } },
  migration_host_work_owed: { class: 'host_only', retryable: false, actor: 'user', summary: "Doctor warning: a migration stopped three or more runs in a row on a conflict in one or more sources and recorded that host work is still owed (today only v0.53.0).",
    why: 'Each source in conflict needs the user\'s decision. The migration\'s read-only preview names each source, its conflict code and the step that settles it, and doctor stops warning once the preview finds no source in conflict.',
    docs: 'docs/guides/shared-brain-skills.md#reviewed-changes-after-inventory',
    suggestion: 'Run the read-only inspect `gbrain apply-migrations --migration <version> --dry-run --json` on the brain host to see each source\'s conflict, its code and its next step, and settle each one with the user. For shared_skills_unmanifested, declare the skills to share in a skillpack.json at the source\'s root, or keep the source out with `gbrain sources shared-skills <id> off`.',
    fix: { argv: ['gbrain', 'apply-migrations', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists each wedged migration that still owes host work (wedged_host_work) with its read-only inspect command; changes nothing.', requires_exclusive: false } },
  migrations_pending: { class: 'caller', summary: "Schema migrations are behind (or could not be confirmed at head), or an orchestrator migration is wedged, so the command did not report success.",
    why: 'apply-migrations reasons: not_applied: the run had no --yes (or --non-interactive), so it did not apply the schema migrations; the fix applies them with --yes. still_behind: an authorized run tried them and they did not apply; another --yes repeats the failure, so run `gbrain doctor --json` and report; when a migration ran out of its statement budget (#7108) the error names it and its fix depends on the case: recorded by another release (rerun), an idle-in-transaction blocker (end it once the user agrees, rerun) or nothing blocking (once the user agrees, one run with --statement-timeout). schema_unreadable: the schema version could not be read back after the orchestrators ran, so the run cannot confirm it reached head; report it. wedged: an orchestrator migration ended partial three or more times in a row, so runs skip it until a person fixes the cause and clears it with --force-retry. Each failure names the migrations still pending. schema_behind (#6904): a managed write was refused at admission because the brain schema is below the version this build needs. Not retryable as is (class caller): the same write refuses until the migrations are applied; nothing was admitted, so the request_id was not consumed and the same request_id commits once the schema is migrated (a replay of an already accepted id still reconciles).',
    suggestion: 'schema_behind: apply them with `gbrain apply-migrations --yes` as the database role that owns the gbrain tables (the brain host operator when this connection does not own them), then resubmit the write with the same request_id. not_applied: apply them with `gbrain apply-migrations --yes`. still_behind or schema_unreadable: run `gbrain doctor --json` and report it to the user; another --yes repeats the failure (a still_behind that names a timed-out migration carries its own fix: follow it). See docs/guides/troubleshooting.md#migration-statement-timeout. wedged: ask the user, read the migration\'s partial rows in the brain home\'s migrations/completed.jsonl (phases[].detail, if present; apply-migrations prints the resolved path), fix the cause, then `gbrain apply-migrations --force-retry <version>` and `gbrain apply-migrations --yes`.',
    reasons: ['not_applied', 'still_behind', 'schema_unreadable', 'wedged', 'schema_behind'] },
  migrations_running: { class: 'retryable', summary: "Another apply-migrations run holds the migration orchestration lock.", exit: 75 },
  missing_source_scope: { class: 'server', summary: "A remote tool call reached dispatch without a resolved source scope; the shared default source is refused." },
  missing_source_value: { class: 'caller', summary: "A source flag was given without a value." },
  models_strict_violation: { class: 'caller', summary: "A configured model is not allowed under models strict mode." },
  no_context_ceiling: { class: 'unavailable', summary: "The model has a known price but no known context-token ceiling, so a user-set cost cap cannot bound one call; the job stopped before any provider call.",
    why: "A user cap is enforced per provider attempt by reserving the most that attempt could cost: its input ceiling times the input price plus its output ceiling times the output price. Some providers (OpenRouter) declare no ceiling for their models, so the reservation has no bound even though the price is registered.",
    docs: 'docs/guides/write-refusals.md#no_context_ceiling',
    suggestion: "Do not retry unchanged and do not re-register the price. Ask the user whether to rerun without the user cap (the model then runs unmetered under the default cap), or to give the model's context size to the brain-host operator.",
    fix: { argv: ['gbrain', 'pricing', 'list', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows that the model already has a registered price, so the missing input is its context size.', requires_exclusive: false } },
  no_pricing: { class: 'unavailable', summary: "gbrain has no price for the model, so a user-set cost cap cannot be enforced." },
  no_refresh_token: { class: 'caller', summary: "Google connect credential error: no refresh token.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  no_routing_eval: { class: 'caller', summary: "The skill has no routing-eval rows to bootstrap a benchmark from." },
  no_skill_md: { class: 'caller', summary: "The skill directory has no SKILL.md." },
  no_worker: { class: 'caller', summary: "No worker is running for this queue, so a queued job would wait until something runs it.", why: "PGLite brains have no background worker (the database is single-writer), and a Postgres queue needs a running `gbrain jobs work` or supervisor. Queuing without one leaves the job waiting with no error." },
  no_worker_surface: { class: 'caller', summary: "No worker surface." },
  not_a_git_repo: { class: 'caller', summary: "The source path must contain committed Git content." },
  not_converged: { class: 'retryable', retryable: true, actor: 'agent', summary: "A managed sync pass used its rounds without the level settling (another writer kept changing it), so it ended resumable; everything it admitted stands.",
    why: "A pass re-reads the level each round and stamps only when nothing is left to admit. Concurrent writes can keep producing new work; the next pass starts from what this one settled. Three in a row (the pass row's not_converged_streak) mean rerunning is not converging.",
    docs: 'docs/guides/write-refusals.md#drain-not-converged',
    suggestion: 'Rerun the same gbrain sync; after three consecutive not_converged passes, stop and report it with gbrain sync status --source <id> --json and gbrain doctor --json.' },
  not_owner_host: { class: 'host_only', summary: "This host does not own the source's active canonical worktree, so ghost pages (live pages whose canonical file is missing) cannot be checked or removed here; nothing was changed.", why: "Whether a page's canonical file is missing is only known on the host that holds the source's checkout; another host would read its own disk.", reasons: ['not_owner_host', 'not_applicable'], docs: 'docs/guides/repair.md#ghost-pages', suggestion: 'Run gbrain repair ghost-pages --source <id> in a terminal on the source\'s canonical owner host (writer status names it).', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: names the canonical owner host of the source.', requires_exclusive: false } },
  not_connected: { class: 'caller', summary: "Google connect credential error: not connected.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  no_brain: { class: 'caller', summary: "No brain is configured on this machine.", suggestion: 'Run `gbrain init --pglite --no-embedding` to create a local keyless brain (or `gbrain init --help` for hosted and Postgres options).' },
  not_found: { class: 'caller', summary: "The requested resource does not exist or is not visible to this caller.", legacy_error: 'invalid_params' },
  overlapping_path: { class: 'caller', summary: "Sources cannot claim overlapping canonical directories." },
  owner_marker_missing: { class: 'host_only', retryable: false, actor: 'host_admin',
    summary: "The ownership marker (`.gbrain-owner.json`) is missing from a managed source's checkout root while the reservation beside the checkout still names this owner, so no write publishes there.",
    why: "The marker binds the checkout directory to its owner. A cleanup or a restore that drops dotfiles removes it; a retry never brings it back, so a write refused with this code ends terminally and releases its outstanding-request slot. The verified self-transfer re-creates it for the same root on the owner host; creating or copying it by hand is refused.",
    docs: 'docs/guides/write-refusals.md#owner_marker_missing',
    suggestion: 'On the brain host: gbrain sources writer status --source <id> --json (note admin_state), then gbrain sources writer transfer prepare <id> --self-transfer and transfer accept with the manifest it prints; then run the same gbrain sync again (a sync stops blocked_by_failures on the refused file, with no hold).',
    fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: shows admin_state and the refused writes before the self-transfer that re-creates the marker.', requires_exclusive: false } },
  owner_unavailable: { class: 'retryable', summary: "The source's canonical owner cannot run this write or maintenance step right now; `reason` says which condition.",
    why: "A managed source publishes only through the host that owns its checkout. `host_mismatch`: another host id owns it (two GBRAIN_HOME identity files on one machine look the same; both ids are printed, and a retry on this host cannot help). `transfer_in_progress`: the worktree is draining for a writer transfer, which ends when the successor accepts it or the owner host runs `gbrain sources writer transfer cancel`; a drain prepared over 30 minutes ago asks the user which (`ask_user`) instead of waiting. `clone_in_progress`: a topology clone is recovering it and clears by itself. `binding_missing`, `incarnation_changed`, `local_path_missing` and `coordination_path_missing` name an incomplete or outdated registration. `not_sent` / `outcome_unknown`: the local owner's IPC lane did not take the write, or lost its acknowledgment. `detail: unbound_source`: on Postgres the source has a checkout but no canonical owner, a configuration state rather than a transient one (not retryable); in classic mode the write path is the file, a commit and `gbrain sync`.",
    reasons: ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'binding_missing', 'incarnation_changed', 'coordination_path_missing', 'local_path_missing', 'not_sent', 'outcome_unknown'],
    docs: 'docs/guides/troubleshooting.md#owner-unavailable',
    suggestion: 'Read gbrain sources writer status --source <id> --json on the brain host. A transfer or clone in progress: wait and retry. host_mismatch: run the step on the owner host, or give the worker and the shell one GBRAIN_HOME; never copy or regenerate host.json. Nothing claims or transfers ownership to run maintenance.' },
  page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--include-content', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },
  page_projection_conflict: { class: 'retryable', summary: "Another worker installed a newer search projection of the page while this command prepared its own.", why: "The projection guard keeps the newer installation instead of overwriting it; the canonical page revision did not change.", docs: 'docs/guides/repair.md#page-projection-conflict', suggestion: "Re-run the same command; it re-reads the current projection. If it conflicts again, wait for the other worker to finish." },
  page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },
  page_body_rows_unreadable: { class: 'server', summary: "This large page's segment rows readable on this connection do not cover its body, so the read returned nothing rather than a short or empty body.", why: "A segmented page keeps its body in manifest rows that must tile the stored body from its first byte to body_bytes; a role that sees the page row but not its manifest rows (a row-level security policy or grant that covers pages only), or rows missing from the database, would otherwise read as an empty or truncated page with nothing to say so.", docs: 'docs/guides/windowed-reads.md#page_body_rows_unreadable', suggestion: "Give the role that reads the brain the same access to page_body_manifest and page_segment_texts it has to pages (the brain host's operator), then read again; run gbrain doctor --json to check the segment tables. When doctor segmented_tiling lists the page, its rows are missing: preview gbrain repair segmented-tiling --source <id>, which republishes it from Git." },
  page_projection_stale: { class: 'server', summary: "A segment of this large page has projection metadata gbrain cannot use, so the read returned nothing for it rather than unsanitized text.", why: "Windows of a segmented page are cut from each segment's stored protected regions; when they are stale (another segmenter version, a text that does not match its hash) gbrain recomputes them from the segment's carried parser state, and refuses when that state is missing or of another version, or when a facts fence block crosses a forced cut while the source has withdrawals.", docs: 'docs/guides/windowed-reads.md#page_projection_stale', suggestion: 'Rewrite the page body (import or sync its file again), which segments it with this gbrain version, then read it again; other windows and the outline still work.' },
  label_edit_refused: { class: 'caller', summary: "A label-only repair left a page unchanged because its file holds the page but cannot take the label edit line by line.", why: "Operator label repairs (gbrain repair visibility, gbrain repair private-labels) change only the label lines of a page's file and never re-render it, so a person's formatting, key order and comments survive. A label line with a block or multi-line value or a duplicate key, a file with no frontmatter block, or a file that still differs from the page once its label lines are edited (a frontmatter key, the title, the type, the tags or the body; never a stamp gbrain keeps only in the database) cannot be edited that way. The repair counts the page as declined, writes nothing, and the next preview lists it as held with what blocks it.", reasons: ['file_differs', 'label_line'], docs: 'docs/guides/write-refusals.md#label_edit_refused', suggestion: "Make the field the refusal names in the page's file match the page, or write the label line as one plain line, commit it, run gbrain sync for the source, then preview the repair again." },
  page_body_segmented: { class: 'caller', summary: "This page's body is stored in segments, and the path that hit it reads or writes the whole body as one string, so it stopped before reading or changing anything.", why: "With pages.segmented_storage on, a page over 1 MiB keeps its body in segments instead of the page row; a whole-body path would otherwise see an empty body and could overwrite the page or drop the unread rest. Windowed reads and segment-aware writers replace these paths.", docs: 'docs/guides/windowed-reads.md#page_body_segmented', suggestion: "Retrying refuses the same way. Read the page in pieces: get_page body: 'auto' returns its outline and first window, and body: 'window' reads any lines or bytes.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--body', 'auto', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'auto' } }, consent: [], actor: 'agent', why: "Returns the page's outline and its first window, with next_cursor to read on.", requires_exclusive: false } },
  page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },
  page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },
  parse_error: { class: 'caller', summary: "The request body is not valid JSON." },
  part_splits_code_point: { class: 'caller', summary: "An upload part starts or ends inside a code point (half of a surrogate pair), so it was not stored.", why: "Each part is stored as raw UTF-8 bytes; half of a surrogate pair has no UTF-8 encoding, so a part cut there would corrupt the character.", suggestion: 'Move the cut before the high surrogate so the pair travels in one part, then send the part again.' },
  part_too_large: { class: 'caller', summary: "An upload part's encoded frame is over the connection's part limit (part_max_frame_bytes), so it was not stored.", why: "part_max_frame_bytes is the connection's inbound request cap (at most 4 MiB) minus a 4 KiB envelope; JSON escaping makes quotes, backslashes and control characters count more than once.", suggestion: 'Cut the part so the whole call stays within part_max_frame_bytes, then send it again with the same part number.' },
  frontmatter_alias_limit: { class: 'caller', summary: "A file an older gbrain imported nests YAML aliases in its frontmatter that expand past the size limit, so sync holds it alone.", why: "#7018 bounds YAML alias expansion on purpose (a few hundred bytes of nested anchors expand into gigabytes), so refusing bytes an older gbrain imported is intended, not a parser regression: the page keeps its last imported version and the rest of the source syncs.", suggestion: 'Reduce the alias nesting in the frontmatter (or write the values out), or remove the file, then commit and sync again.' },
  parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; such a file is held and the rest of the sync continues (`GBRAIN_SYNC_PARSER_REGRESSION=stop` for the process that syncs stops the run instead).", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again.' },
  pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },
  path_not_utf8: { class: 'caller', summary: "A committed file's name is not valid UTF-8, so managed sync holds that file alone.", why: "Git hands the name back with U+FFFD for the bytes that are not UTF-8 (a Latin-1 name from an older system, an archive or a network share), and no Git read or file matches that decoded name, so nothing is imported from it. The rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#path_not_utf8', suggestion: 'Rename the file to a UTF-8 name (git ls-files with core.quotePath shows its exact bytes; convmv -f latin1 -t utf8 converts a Latin-1 name), commit, then sync again; the rename clears the hold.' },
  pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'write-requests', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Lists the write receipts of the source, newest first, so the held rewrites show, read-only.', requires_exclusive: false } },
  patterns_min_interval: { class: 'consent', summary: "An in-cycle dream patterns run was skipped because the partition's last completed patterns run ended less than dream.patterns.min_interval_hours ago; nothing was submitted.", why: 'Every maintenance pass writes new reflections, so the evidence watermark alone re-ran a paid patterns child on each pass. The skip names next_eligible_at; a direct `gbrain dream --phase patterns` or `--once` is not held to the interval, and `gbrain config set dream.patterns.min_interval_hours 0` turns it off.', docs: 'docs/guides/dream-patterns.md#cadence', suggestion: 'Wait for next_eligible_at, or, with the user\'s paid authorization, run `gbrain dream --phase patterns` now.', fix: { argv: ['gbrain', 'dream', '--phase', 'patterns'], consent: ['paid'], actor: 'agent', why: 'A direct run is not held to the cadence; it is a paid model run, so ask the user first.', requires_exclusive: false } },
  pending_verify: { class: 'host_only', summary: "`gbrain bootstrap harness --token` wired the harness on a PGLite brain while no `gbrain serve` answered, so the wiring is not verified yet; nothing failed.", why: 'On PGLite the serve holds the single-writer lock, so a stopped serve is the normal state for wiring; the smoke test needs the serve, so it waits for the re-run.', docs: 'docs/guides/bootstrap.md#pending-verify', suggestion: 'Start `gbrain serve --http` for this brain, then re-run the same `gbrain bootstrap harness` command with the same --token; `gbrain bootstrap harness --status` stays partial until that run passes its smoke test.', exit: 13 },
  pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },
  permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },
  persistence_restart_required: { class: 'host_only', summary: "This gbrain serve's persistence consumer reports restart_required, so it claims no write until the process restarts; `/health?deep=1` answers 503 with this code.", why: "A preparation abandoned past the ceiling (a zombie) or a publication that never settled past its deadline makes the owner stop claiming on every root, because the abandoned work may still hold locks or write files; only a process exit releases it. The deep health probe reports it so a supervisor can restart serve; it never acts on its own (GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS opts into an exit).", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart the serve process (for the installed service: systemctl --user restart gbrain-serve; otherwise stop and start it in the foreground); to let a supervisor do it unattended, set GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=300 in the serve environment (~/.gbrain/env for the installed service). Then run gbrain sources writer status --json.' },
  pool_inflight_over_budget: { class: 'host_only', summary: "A pooled statement of this gbrain serve has run longer than its in-flight budget (the read pool's statement_timeout plus grace, or the longer statement_timeout its operation declared); `/health?deep=1` answers 503 with this code.", why: "Since #6543 the in-flight watchdog retires a statement past its budget whether or not bytes keep arriving (reason=age), so this code means the watchdog is off (GBRAIN_PG_STUCK_GRACE_MS=off), the serve runs a driver without per-statement budgets, or the retirement is still in progress; a transaction that declared a longer statement_timeout, or an index build that declared 0, is measured against its own budget and not reported. Through a transaction-mode pooler a pipelined answer can also be misrouted. The probe reports it and never retires the connection, because the endpoint is unauthenticated.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart this gbrain serve. On a transaction-mode pooler check the transport block of /health?deep=1: max_pipeline should read 0 (set PGMAX_PIPELINE=0 in the serve environment to force it) and session_timeouts_not_applied names the ALTER ROLE fix. GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS does not act on this code: restart serve yourself or from your health check.' },
  deep_health_probe_failed: { class: 'retryable', summary: "The pooled `SELECT 1` of `/health?deep=1` did not answer: an earlier probe is still pending, it timed out, or it failed.", reasons: ['pending', 'timeout', 'error'], why: "The deep probe runs through the ordinary pooled dispatch, where handler statements wait, so a saturated or wedged pool fails it while plain /health (a reserved idle connection) may still answer 200. One deep probe runs per engine at a time.", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Retry in a few seconds; if it keeps failing, run gbrain doctor --json from a fresh process to check the database and pooler, then restart this gbrain serve.' },
  refresh_required: { class: 'caller', actor: 'agent', summary: "A GitHub push arrived for a managed source: a managed source never pulls, so the pushed commit is recorded as wanted and waits for a refresh.", why: "Managed sync imports the checkout's own HEAD; remote commits come in through gbrain sources refresh, which updates the worktree under the writer lock. The push's commit is kept as a wanted marker until the source reaches it.", docs: 'docs/guides/on-commit-sync.md#refresh-required', suggestion: 'Run gbrain sources refresh <id> on the brain host, then gbrain sync --source <id> --no-pull (a resident notifier runs the sync on its own).' },
  serve_self_exit_suppressed: { class: 'host_only', summary: "gbrain serve stayed at restart_required past GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS but did not exit, because it had already exited on its own 3 times within the hour; `/health?deep=1` reports self_exit_suppressed.", why: "The opt-in self-exit keeps a durable ledger (serve-self-exit.json under the gbrain home). A serve that reaches restart_required again right after every restart has a cause a restart does not fix, so after 3 self-exits in an hour it keeps serving reads and leaves the decision to a human instead of looping.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Run gbrain sources writer status --json and gbrain doctor --json, report both with the serve log lines, then restart serve by hand.' },
  serve_unhealthy_exit: { class: 'unavailable', exit: 69, summary: "gbrain serve exited on its own because its persistence consumer reported restart_required continuously for GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS.", why: "Opt-in (off by default, at least 120 s): a supervisor that restarts on failure, such as the installed gbrain-serve service, then starts a fresh serve without a human. Cleanup is bounded (5 s) because the consumer's stop waits on the stuck work, so the process exits even when it cannot drain. Abandoned claims lapse with the exited process's heartbeat; journaled writes resume on the next owner.", docs: 'docs/ENGINES.md#serve-unhealthy-exit', suggestion: 'Let the supervisor restart serve; if it exits this way again soon after, run gbrain doctor --json and gbrain sources writer status --json and report both with the exit line.' },
  persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },
  publish_secret_found: { class: 'consent', summary: "An automatic publish found values that look like secrets (or text too large to scan) in the commits it was about to push; nothing was pushed.", docs: 'docs/guides/shared-checkout-git.md#publish_secret_found', actor: 'user' },
  publish_scan_unreadable: { class: 'host_only', summary: "An automatic publish could not read its local commits in full to scan them for secrets (a missing or corrupt object, git output the scan does not recognise, or the 300 s budget); no secret was reported and nothing was pushed.", docs: 'docs/guides/shared-checkout-git.md#publish_scan_unreadable', actor: 'user' },
  push_credential_refused: { class: 'host_only', actor: 'user', retryable: false, reasons: ['not_found', 'forbidden'], summary: "The Git host refused the push for the credential git used (\"Repository not found\", HTTP 404, or HTTP 403); the commit is durable locally and nothing was pushed or retried.", why: "A host answers \"Repository not found\" to an account that cannot see a private repository, and 403 to one that may not write to it. The same credential is refused on every attempt, so a retry only hides the fault while commits stay on this machine; which credential git uses is the user's configuration, and gbrain never changes it.", docs: 'docs/guides/shared-checkout-git.md#push_credential_refused', suggestion: 'Relay the message to the user: it names the credential helpers git asked (with the scope and file that configure each), which one answered and its account login. Once they make git use a credential for an account that can push there, run gbrain git commit-push --push-only.' },
  push_unconfirmed: { class: 'retryable', summary: "The commit is durable locally but no push destination confirmed it.", docs: 'docs/guides/shared-checkout-git.md#outcomes', exit: 4 },
  schema_lock_blocked: { class: 'retryable', summary: "A schema step (the schema.sql replay in init/upgrade, or one migration) waited its lock_timeout for a table lock another session holds and stopped instead of hanging.", why: "Every ALTER TABLE in the replay takes an ACCESS EXCLUSIVE lock even as a no-op, so one open transaction in another client (idle in transaction, a stuck job) blocked gbrain init and upgrade forever with no output. The wait is now bounded (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60) and the refusal names the blocking sessions by pid, application and state, sampled while the wait was active; query text is never shown. The cancelled step changed nothing.", docs: 'docs/ENGINES.md#schema-lock-blocked', suggestion: 'Let the named session finish or, with the user\'s agreement, end it on the database host with SELECT pg_terminate_backend(<pid>), then rerun the same gbrain command; init retries a few times on its own with a short backoff.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the database, the pooler and the schema version so the rerun is judged against the current state.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },
  postgres_tls_required: { class: 'host_only', actor: 'user', retryable: false, summary: "TLS was required by default for a non-local Postgres host, and the server does not accept TLS connections, so gbrain did not connect.", why: "gbrain connects with sslmode=require to any Postgres host that is not on this machine (localhost, 127.0.0.0/8, ::1 or a Unix socket) unless the database URL names an sslmode, so the password and page contents never cross a network in plaintext without an explicit choice. Brains whose URL had no sslmode connected in plaintext before this default.", suggestion: 'Turn TLS on at the database server and keep the default (sslmode=require encrypts; sslmode=verify-full with the server CA also verifies the certificate). To keep connecting without TLS on a network you trust, add sslmode=disable to the database URL.', fix: { ask_user: true, argv: ['gbrain', 'engine', 'status', '--probe', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows where the database URL comes from (an environment variable or the config file), which is where the sslmode setting goes.', user_message: 'Your database server does not accept TLS, and gbrain now requires it for a server that is not on this machine. Either turn TLS on at the server (then nothing else changes), or, if this network is trusted, add sslmode=disable to the database URL to keep the old plaintext connection. sslmode=require and sslmode=verify-full are the secure choices.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'postgres_tls', '--json'] } } },
  pg_connection_recovery_failed: { class: 'retryable', summary: "A Postgres connection the driver retired after an incident (stuck, desynced, or closed under running statements) could not reconnect; statements waiting for it failed with the connect error.", why: "The database or pooler refused or dropped the new connection (unreachable host, exhausted connection slots, rotated credentials). The next statement retries the connect, and the connection stays marked until one succeeds, so a repeating line means the pool is not recovering on its own.", docs: 'docs/ENGINES.md#pg-connection-recovery-failed', suggestion: 'Check the database and pooler from the serve host (gbrain doctor --only pool_reap_health --json); a serve that keeps logging this line needs the database reachable again, then a restart if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--only', 'pool_reap_health', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the recent stuck, desync and recovery events serve recorded.', requires_exclusive: false } },
  pg_connection_stuck: { class: 'retryable', summary: "A pooled Postgres statement ran past its in-flight budget (the pool's statement_timeout plus grace, or the longer statement_timeout its operation declared) with nothing coming back from the server (reason=idle) or while bytes kept arriving (reason=age), so the driver retired that connection; the statement and everything queued behind it failed with CONNECTION_STUCK.", why: "Nothing arriving for that long usually means the connection is wedged: a pipeline the server and client no longer agree on, a transaction-mode pooler that swallowed a CancelRequest and left the backend in ClientRead, or a dead peer. It is not proof: behind a transaction-mode pooler the startup statement_timeout never applies (SHOW statement_timeout reads 0), so a legitimately slow statement can reach the budget too. reason=age is a statement that kept streaming rows or notices past its budget (#6543); an operation that needs longer declares it with SET LOCAL statement_timeout (0 for no limit), which the driver tracks per statement. Before #6383 such a connection held its queue forever while /health answered 200. The pool reconnects on its own; the warn line names the pool, the age, the queue depth and the statement by keyword and table.", docs: 'docs/ENGINES.md#pg-connection-stuck', suggestion: 'Retry the failed call. If the line repeats, run gbrain doctor --json and report the warn lines with the operations that preceded them; GBRAIN_PG_STUCK_GRACE_MS raises the grace, and off disables the watchdog.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports pool pressure, the pooler mode and the recent persistence hold lines beside this warning.', requires_exclusive: false } },
  pg_pool_stalled: { class: 'retryable', summary: "The Postgres pool of a resident gbrain process has had connections checked out or statements waiting for one across two 30 s ticks without completing a single statement.", why: "One slow statement is one quiet tick; two in a row with nothing settled means every checked-out connection is waiting on the server at once, which is what a wedged pool or an unreachable database looks like from inside the process. With the in-flight watchdog on, the stall ends within statement_timeout plus grace and a pg_pool_recovered line follows; with it off this line is the only trace.", docs: 'docs/ENGINES.md#pg-pool-stalled', suggestion: 'Wait one more tick for pg_pool_recovered or pg_connection_stuck; if the line keeps repeating, check the database and pooler (gbrain doctor --json) and restart the process if the pool never recovers.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: checks the database and pooler from a fresh process beside the stalled one.', requires_exclusive: false } },
  pg_statement_build_failed: { class: 'server', summary: "A Postgres statement could not be built from its parameters (UNDEFINED_VALUE: a parameter was undefined; MAX_PARAMETERS_EXCEEDED: more than 65534 parameters) and was answered in its place in the pipeline by a query the server refuses; it failed, and a transaction it was part of was aborted rather than committed without it.", why: "Either a gbrain programming error at the call site the warn line names by keyword and table (and by `param=$n`), or, behind a transaction-mode pooler (port 6543, prepare off), a value read from a row that belonged to another statement: a pooler that misroutes pipelined answers hands a statement someone else's row, and binding one of its missing columns fails here. Before #6383 the same failure, when it happened behind another statement on the connection, rejected that other statement, desynced the connection and left every later statement on it hanging; the driver now answers the culprit in its place (the approach of porsager/postgres#1236), so only it rejects and a transaction it was in aborts.", docs: 'docs/ENGINES.md#pg-statement-build-failed', suggestion: 'On a transaction-mode pooler, check /health?deep=1 transport (max_pipeline should be 0; PGMAX_PIPELINE=0 on the serve environment forces it) and treat earlier reads as suspect (docs/guides/pooler-misroute-audit.md); otherwise report the warn line (it names the statement and parameter) as a gbrain bug so the call site gets a null where it bound undefined.' },
  pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve', 'legacy_owner_unverified'], reason_overrides: { legacy_owner_unverified: { class: 'consent', exit: 3 } }, docs: 'docs/ENGINES.md#legacy-pglite-lock', suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock. Reason legacy_owner_unverified is different: a lock folder from an older release whose owner cannot be proven dead never frees itself, so ask the user and run the read-only preview in fix (gbrain pglite-repair --legacy-lock --dry-run).' },
  pglite_vector_index_too_large: { class: 'unavailable', summary: "A PGLite vector (HNSW) index build was refused before it started because its in-memory graph would not fit PGLite's WebAssembly heap.", why: "pglite.wasm caps memory at 2 GiB and pgvector keeps the whole HNSW graph in memory while it builds; a build past the budget used to run out of memory or fall back to hours of on-disk inserts. Vector search keeps working with exact scans.", docs: 'docs/ENGINES.md#pglite-vector-index-ceiling', suggestion: 'Preview a move to Postgres (read-only): gbrain migrate --to postgres --plan --json', fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists what moves to Postgres, the blockers and the exact run command.', requires_exclusive: false } },
  plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },
  plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },
  port_in_use: { class: 'retryable', summary: "Google connect credential error: port in use.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  preparation_stalled: { class: 'server', retryable: false, actor: 'host_admin',
    summary: "A managed write's preparation was cut off at its deadline persistence.max_preparation_attempts times (default 2), so the owner finished it failed instead of claiming it again.",
    why: "One request whose preparation never finished used to hold its root for as long as its owner renewed the claim; now each attempt has a budget, a cut-off attempt is counted (a kill mid-preparation included), and at the limit the request is terminal so the rest of the root keeps moving. A sync holds that file with the same code; the receipt names the last recorded step and what it was waiting on.",
    docs: 'docs/guides/write-refusals.md#preparation_stalled',
    suggestion: 'Inspect the owner with gbrain sources writer status --source <id> --json (the step and its wait cause), fix or report the cause, then gbrain sources retry-held <id> and the same gbrain sync with the same options; a foreground write needs a new request_id.',
    fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: lists the held files of the source with their repair route.', requires_exclusive: false } },
  preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },
  profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },
  projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },
  // #6643, retired by #6712 (one page, one fate): no page waits on another page's fate any more, so nothing re-freezes knock-ons.
  knock_on_exhausted: { class: 'server', retired_in: '0.60.255.0',
    summary: "Retired: an older gbrain stopped a managed sync that kept re-freezing a page cancelled only because another page of the same sync did not commit. This build never cancels a page for another page's failure, so the stop is superseded.",
    why: "Since #6712 each page of a sync has its own fate: a page that does not commit is held or stops the run on its own, and the pages after it still publish. A ledger row or receipt with this code was written by an older build.",
    docs: 'docs/guides/sync-unblock-runbook.md#decision-table',
    suggestion: 'Rerun the same plain gbrain sync --source <id> --no-pull; it resumes the stopped entry under a fresh request. gbrain sync status --source <id> --json shows what remains.',
    fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the cursor and the next step; read-only. A plain sync of the source resumes the stopped entry.' } },
  keyword_candidates_incomplete: { class: 'unavailable', summary: "Hybrid search's keyword arm returned a bounded result on a large corpus (the CJK arm's deadline or candidate cap, or a common-word match ranked from a sample), so some keyword matches can be missing.", why: 'The CJK fallback is an unindexed LIKE scan, and a query whose words match hundreds of thousands of chunks ranks a bounded sample of them (an OR retry also keeps only its rarer words); each bound keeps a large brain from stalling every hybrid search. An incomplete keyword search is not evidence of absence.', docs: 'docs/guides/multi-language-fts.md#cjk-keyword-budget', suggestion: 'Add a rarer word or an exact "phrase", or narrow the search with --source-id (MCP source_id) or --types; for CJK text, ask the user to raise search.cjk_keyword_deadline_ms.', fix: { argv: ['gbrain', 'config', 'get', 'search.cjk_keyword_deadline_ms'], consent: [], actor: 'agent', why: 'Shows the deadline in effect (unset means 3000 ms); read-only.', requires_exclusive: false } },
  keyword_skipped_after_timeout: { class: 'unavailable', summary: "Hybrid search's Postgres keyword arm skipped a statement that hit the keyword statement timeout within the negative-cache TTL; the search reports keyword_arm_failed with reason skipped_after_timeout and the vector arm still answers.", why: 'Running the same broad keyword statement again would hold a backend for the whole search.keyword_statement_timeout_ms and fail the same way. The skip covers that exact statement and scope only, lasts at most search.keyword_timeout_negative_cache_seconds (default 600, 0 turns it off), ends as soon as a background re-run of the statement in the serve answers, and is per serving process. A skipped keyword arm is not evidence of absence.', docs: 'docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain', suggestion: 'Narrow the search (source_id, types, since or until) to run keyword search now, or wait for the entry to expire; the user may raise search.keyword_statement_timeout_ms or change the TTL.', fix: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the keyword statement bound, the recorded keyword timeouts and skips, and whether broad terms can be ranked inside the bound.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'] } } },
  projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },
  proposal_closed: { class: 'caller', summary: "The memory proposal is no longer awaiting the owner (approved, denied, expired, cancelled, failed or in conflict), so it was not approved or denied again.", why: 'A proposal is decided once; the decision and the receipt it left stay as they are.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'Read how it ended with gbrain memory-proposals show <request_id>; the proposer sends a new proposal if the change is still wanted.' },
  proposal_expired: { class: 'caller', summary: "The memory proposal passed its TTL (proposals.ttl_hours) before the owner decided, so nothing was written.", why: 'A held proposal is only as current as the page QM showed the person; an old one is closed rather than applied.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'The proposer sends a new proposal if the change is still wanted; the operator raises proposals.ttl_hours to give owners longer.' },
  proposals_pending_limit: { class: 'retryable', summary: "Too many memory proposals already await the owner for this person (proposals.max_pending_per_actor) or this credential (proposals.max_pending_per_credential), so this one was not saved.", reasons: ['actor', 'credential'], why: 'The caps keep one system credential from flooding the owner with held text.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'Wait for the owner to decide or for a proposal to expire, or cancel one with cancel_write_request; the operator sets the caps.' },
  provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },
  provider_response_unparseable: { class: 'host_only', retryable: false, summary: "A model provider answered with a success status, but its response body could not be parsed as one JSON document; no response text is kept.", why: "The same request gets the same body, so retrying spends another paid call on the same failure. The common cause is a provider route that streams (Server-Sent Events) when a request omits `stream`; a job that hits it ends on its first attempt.", suggestion: "Ask the operator to make the route return one JSON body for a non-streaming request, for example with gbrain config set provider_chat_options.<provider>:<model> '{\"stream\": false}', then retry the job." },
  publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },
  pull_blocked_local_changes: { class: 'caller', retryable: false, actor: 'user',
    summary: "A gbrain-owned clone (sources add --url) has local changes in its checkout, so git pull --ff-only cannot fast-forward it and every sync of the source stops at the pull.",
    why: 'Older gbrain releases appended ## Facts fence rows to clone files on unmanaged brains (#6946); a local change to a file the upstream also changed blocks every fast-forward. Current releases keep facts about a clone database-only.',
    suggestion: 'Ask the user, then preview the repair: gbrain repair url-clone-fences --source <id>. It proves which files differ from HEAD only by gbrain fence rows and restores those after keeping their facts database-only; a file with any other edit is named and left for the user.',
    docs: 'docs/guides/repair.md#url-clone-fences' },
  purge_blocked_pending_recovery: { class: 'retryable', summary: "A purge was refused because a pending, running or recovering write still needs the content it would remove; nothing was purged.", why: "Purge redacts stored write intents and rewrites pages; doing that under an unfinished publication or recovery would lose or resurrect content.", suggestion: 'Wait for the named write to finish or recover (gbrain write-request <id>), then retry the purge with the same request id.', docs: 'docs/guides/memory-boundaries.md#purge' },
  purge_lookup_timeout: { class: 'caller', retryable: false, actor: 'host_admin',
    summary: "A page purge's in-transaction journal lookup hit the publication transaction's statement budget, so the purge failed terminally; nothing was removed, tombstoned or redacted, and later writes to the source move again.",
    why: "The lookup is deterministic on a large request table, not contention: retrying it as `database_contention` requeued the same purge forever and held every later write to its source behind it. The substring search for the page's claims now runs at preparation under the preparation budget; this code is for the lookups that still run inside the transaction (the slug lookup, the tail and pending re-checks, the locking read).",
    docs: 'docs/guides/write-refusals.md#purge_lookup_timeout',
    suggestion: 'Do not assume the requested content was erased. If the receipt names the slug index as missing or INVALID, run gbrain repair request-indexes --apply first; then submit the purge again with a new request_id (a retry with the same id returns this failure).',
    fix: { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'host_admin', why: 'Previews the request-table indexes without changing anything; the purge receipt says whether the slug index is the cause.', requires_exclusive: false } },
  purge_mirror_unwritable: { class: 'caller', retryable: false, actor: 'host_admin',
    summary: "A purge could not append its intent line to the purge mirror (<brain home>/.gbrain/purge-events.jsonl), so it was refused; nothing was removed, tombstoned or redacted.",
    why: 'Restore replays the purges recorded in that text-free mirror; a purge that committed without its line would come back silently from an older backup.',
    docs: 'docs/guides/write-refusals.md#purge_mirror_unwritable',
    suggestion: 'Do not assume the requested content was erased. Make the mirror a writable regular file owned by the brain\'s user (mode 0600), then run the purge again with a new request_id.' },
  purge_replay_incomplete: { class: 'caller', retryable: false, actor: 'host_admin',
    summary: 'A restore stopped because the replay of a purge could not sweep every stored request that carries the purged page; that purge was not replayed and nothing was restored.',
    why: 'A replayed purge removes what the live purge removed, the request journal included; reporting a partial sweep as replayed would leave purged text in the restored brain.',
    docs: 'docs/guides/write-refusals.md#purge_replay_incomplete',
    suggestion: 'Do not use the restored copy. Report the purge request named in the message with the output of gbrain doctor --json; restore again once it is fixed.' },
  purged_content: { class: 'caller', summary: "The content matches a purged fact, take or page in this source, so it was not saved.", why: "A purge leaves a text-free tombstone (the claim fingerprint or the page content hash) so stale files, re-syncs, reverts and re-extraction cannot bring purged content back.", suggestion: 'Do not retry the same content. Write it in new words if it is still true, or ask the user to clear the tombstone on the brain host (gbrain pages purges list, then gbrain pages unpurge <slug> for a page).', docs: 'docs/guides/memory-boundaries.md#purge' },
  question_not_found: { class: 'caller', summary: "No pinned question has this id in the caller's scope; ids are source-qualified (default:questions/<slug>).", docs: 'docs/guides/pinned-questions.md#ids-and-scope' },
  question_owner_only: { class: 'host_only', summary: "Pinned questions are owner-private: this connection cannot read private pages (or is slug-fenced or delegated), so the owner runs the command on the brain host.", docs: 'docs/guides/pinned-questions.md#who-can-see-pinned-questions' },
  queue_capacity: { class: 'retryable', summary: "The bounded queue is full; existing requests keep their place." },
  rank_entities_timeout: { class: 'caller', summary: "rank_entities did not finish within its statement deadline (Postgres statement_timeout); nothing was ranked.", why: 'The ranking aggregates every edge in scope in one statement; a whole-brain ranking on a large graph can exceed the deadline, and a partial ranking would misstate the top rows.', docs: 'docs/guides/graph-ranking.md#rank_entities_timeout', suggestion: 'Narrow the ranking with source_id, types or link_type, then call rank_entities again.' },
  rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },
  read_budget_exhausted: { class: 'caller', summary: "A subagent's get_page result came back as a short summary because the job has used its read budget (for the dream patterns child, dream.patterns.child_read_budget_kb).", why: 'A CLI-backed model replays the whole transcript on every turn, so a child that read every page in full filled the model window. The summary keeps the slug, title, type and a short excerpt; writes still work.', docs: 'docs/guides/dream-patterns.md#child-read-budget', suggestion: 'Work from the pages already read and append with add_timeline_entry instead of rewriting a summarized page. An operator who needs more reads raises dream.patterns.child_read_budget_kb (0 turns the budget off).' },
  reason_purge_scan_capped: { class: 'consent', exit: 3, summary: "A fact purge stopped before deleting anything: the source's Git history has more commits than the purge reads (200,000) when it looks for change reasons quoting the claim.", why: 'Purge tombstones every commit whose gbrain-reason trailer quotes the claim, so no later sync or re-import stores that reason again. Past the limit it cannot say which older commits do, so the user decides.', docs: 'docs/guides/page-history.md#purge-and-reasons', suggestion: 'Ask the user: purge now and check only the newest commits (--reason-scan-limit <n>, their choice; older commits are not tombstoned), or stop.' },
  reason_purge_scan_failed: { class: 'retryable', summary: "A fact purge stopped before deleting anything: reading the change reasons in the source's Git history failed (a Git error or a timeout).", why: 'Purge reads the reason trailers that quote the claim before it changes anything, so it can tombstone them; nothing was removed, so retrying is safe.', docs: 'docs/guides/page-history.md#purge-and-reasons', suggestion: 'Wait, then run the same purge again.' },
  reason_scan_capped: { class: 'unavailable', summary: "A sync imported its files but did not read their change reasons from Git: the range held more than 10,000 commits. Each reason in the pass is stored as empty and each page it changed is marked with a history gap.", why: 'Reasons are metadata, so content import never waits on them. The pass still advances last_commit and this release does not backfill reasons for that range; they stay in Git.', docs: 'docs/guides/page-history.md#reasons-from-git', suggestion: 'Nothing to repair. The reasons for the range are in Git: git log --first-parent <range> shows them.' },
  reason_scan_failed: { class: 'unavailable', summary: "A sync imported its files but could not read their change reasons from Git (a Git error or a timeout). Each reason in the pass is stored as empty and each page it changed is marked with a history gap.", why: 'Reasons are metadata, so content import never waits on them. The pass still advances last_commit and this release does not backfill reasons for that range; they stay in Git.', docs: 'docs/guides/page-history.md#reasons-from-git', suggestion: 'Nothing to repair. The reasons for the range are in Git: git log --first-parent <range> shows them.' },
  reason_trailer_secret: { class: 'host_only', summary: "A gbrain-reason trailer already pushed to Git looks like it holds a secret; sync stored no reason for that commit and path.", why: 'A secret in a reason is refused at write time; a commit made outside gbrain can still carry one. Git history keeps commit messages, so the credential stays exposed until it is rotated.', docs: 'docs/guides/page-history.md#reasons-from-git', suggestion: 'Rotate the credential the notice names (by commit and path); the brain stores nothing of it.' },
  receipt_conflict: { class: 'retryable', summary: "The ingestion receipt changed since it was read.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
  receipt_fence_changed: { class: 'caller', summary: "The managed owner, topology or source binding changed while the ingestion ran.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
  receipt_fence_required: { class: 'host_only', summary: "Ingestion into a managed or bound source needs the worktree owner's fence.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },
  receipt_identity_mismatch: { class: 'caller', summary: "The receipt ID is already bound to different approved ingestion metadata.", docs: 'docs/guides/company-brain-ingestion.md#agent-and-ci-use' },
  pat_file_unreadable: { class: 'caller', summary: "The --pat-file token file is missing, empty, holds more than one token, or is readable by other users, so it was not read.", why: "The token is read from a private file so it never appears on a command line or in a process list; a file other users can read would leak it, so the verb refuses before any credential is written.", suggestion: 'Write exactly one token on one line to a file, chmod 600 it, and pass its path with --pat-file.' },
  // #6712 PR 4a: a Git listing the reconcile reads did not finish cleanly (sync-git-stream.ts).
  reconcile_host_required: { class: 'host_only', actor: 'user', summary: "A remote caller's managed sync admitted what it could, and the rest of the source needs the owner host (holds, markers, keep_db writes or the stamp).",
    why: "Remote callers admit only one-sided work and never write holds, markers, keep_db writes or stamps (design v3.2 §5), so only the owner host's sync converges the source.",
    docs: 'docs/guides/write-refusals.md#drain-reconcile-host-required',
    suggestion: 'On the host that owns the source, run gbrain sync --source <id> --no-pull; verify with gbrain sync status --source <id> --json.' },
  reconcile_read_incomplete: { class: 'server', actor: 'agent', summary: "A Git listing the managed-sync reconcile reads (`ls-tree`, `ls-files`, `diff-tree`) did not finish cleanly: Git exited non-zero, was killed by a signal or its time or size cap, or its output did not end at a record boundary.",
    why: 'A partial listing would make files look deleted or new, so the level is refused rather than classified. In PR 4a only the read-only convergence shadow reads it, and it reports `status: unavailable` with this code.',
    docs: 'docs/guides/sync-unblock-runbook.md#dry-run-convergence-classes',
    suggestion: "Check the checkout with git -C <dir> status, then rerun the read-only status; report it with gbrain doctor --json if it repeats.",
    fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--detail', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-reads the convergence shadow; writes nothing.' } },
  recovery_prior_stage_unavailable: { class: 'consent', actor: 'user', summary: "gbrain repair stuck-recovery cannot apply that --keep choice to a page recovery over the single-string ceiling, because the staged copy of its prior file is missing, does not match its recorded SHA-256, or is not a regular file; nothing was changed.", why: "A prior file over 24 MiB is not embedded in its recovery record: the record names a staged copy beside the file by path and SHA-256, and only that copy can put the prior bytes back. Without it --keep prior has nothing safe to restore, so the remaining exit is --keep disk, which the user must agree to.", docs: 'docs/guides/repair.md#recovery-prior-stage-unavailable' },
  recovery_version_unsupported: { class: 'host_only', actor: 'host_admin', summary: "A newer gbrain wrote this recovery record (its version is unknown here), so this gbrain left the record, its staged files and the canonical file untouched; writes on that worktree wait for it.", why: "A recovery record says how to finish an interrupted publication; reading a newer layout as an older one can publish wrong bytes, delete a staged file or clear the record. Only a gbrain that knows the version may recover it, so the fix is upgrading gbrain on the canonical owner host and restarting its writer processes.", docs: 'docs/guides/write-refusals.md#recovery_version_unsupported' },
  recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes.", why: "Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it) and physical_root_moved (the checkout was moved to a new path or its parent folder renamed; `sources add`, `set-path` and `writer claim`, dry runs included, name the recorded path and the symlink-then-set-path or move-back exit, and a remote caller sees no path). All three are explained in docs/guides/write-refusals.md." },
  redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  ref_not_in_answer: { class: 'caller', summary: "The rated page is not one of the pages the answer used.", docs: 'docs/guides/retrieval-feedback.md#ref_not_in_answer' },
  refresh_dirty: { class: 'caller', summary: "The worktree has uncommitted changes." },
  refresh_diverged: { class: 'caller', summary: "The worktree diverged from its upstream; a fast-forward is impossible." },
  refresh_drain_timeout: { class: 'retryable', summary: "In-flight work did not drain before the refresh deadline." },
  refresh_lock_timeout: { class: 'retryable', summary: "Another database transaction held a row the refresh fence locks past the fence's 5 s lock timeout; nothing moved." },
  refresh_no_upstream: { class: 'caller', summary: "The worktree has no upstream to refresh from." },
  refresh_not_managed: { class: 'host_only', summary: "The source is not managed, so it cannot be refreshed." },
  refresh_not_owner: { class: 'host_only', summary: "This process does not own the worktree it would refresh." },
  pending_import_expired: { class: 'caller', actor: 'provider', summary: "A write that waited for managed sync to import a committed change to its page's file was not applied, because the import had not landed after the barrier's wait limit.", why: "With persistence.refresh_barrier on, a put_page, capture, remember or add_timeline_entry whose page file holds a change committed through Git that managed sync has not imported yet is accepted and waits for that import instead of being refused pending_import. An import that never lands (no sync owner running, a sync stopped on the file) would hold the write forever, so the owner finishes it failed once one hold has lasted persistence.refresh_barrier_max_wait_ms (15 minutes by default), or once it has waited four of those limits (at least 4 hours) since its admission across repeated holds. Nothing was applied. A remember ends as its pending_import refusal did instead: one that named its entity is replayed by the first sync that imports the file, and gbrain repair failed-writes lists the rest for a person to replay.", docs: 'docs/guides/write-refusals.md#pending_import_expired', suggestion: 'Check the source with gbrain sync status --source <id> --json, then read the page again and submit the write with a new request_id.' },
  refresh_barrier_expired: { class: 'caller', actor: 'provider', summary: "A write that waited behind a worktree refresh was not applied, because the refresh was still unfinished after the barrier's wait limit.", why: "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.", docs: 'docs/guides/write-refusals.md#deferred-writes', suggestion: 'Check the refresh with gbrain sources writer status --source <id> --json, then submit the write again with a new request_id.' },
  refresh_source_changed: { class: 'caller', summary: "The source changed during the refresh." },
  refresh_sync_timeout: { class: 'retryable', summary: "A refresh's member sync committed nothing within the refresh sync budget." },
  relay_disabled: { class: 'caller', summary: "Google connect credential error: relay disabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  relay_session_expired: { class: 'caller', summary: "Google connect credential error: relay session expired.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  relay_unreachable: { class: 'retryable', summary: "Google connect credential error: relay unreachable.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  rename_held: { class: 'caller', summary: "A renamed file is held because the page it was renamed from changed after the rename was recorded.", reasons: ['rename_source_changed'], why: "Moving the page now could carry the newer edit to the wrong file, so the rename waits for an explicit re-bind.", suggestion: 'Preview the frontmatter repair with --include-ambiguous to re-bind the rename to the current page, and approve it.' },
  rename_identity_unreadable: { class: 'caller', summary: "A renamed file is held because the database refused to compare its title or frontmatter id (SQLSTATE 22021/22P05), so sync could not tell whether it is the page it replaces.", why: "Which page a file is cannot be decided without comparing its identity; the old page keeps its id, links, facts and timeline and the rest of the source keeps syncing.", suggestion: 'Remove the NUL byte or broken Unicode character from the file title and id, commit, and sync again; the pair is decided again when the file changes.' },
  rename_reconcile_failed: { class: 'caller', summary: "A renamed file imported, but removing the page of its old name failed unexpectedly, so that page was kept and may be a duplicate.", why: "An unexpected error is deterministic, so a blocking marker would stop the source on every run; the rename is held instead and the rest of the source keeps syncing.", suggestion: 'Ask the user before a full sync of the source (gbrain sync --source <source> --full --no-pull), which removes pages whose file is gone, or remove the old page with gbrain delete.' },
  repair_preview_timeout: { class: 'caller', retryable: false, actor: 'agent',
    summary: "A `gbrain repair failed-writes` preview read ran past the database statement timeout, so the preview stopped; nothing was saved, no approval checkpoint was written and no page changed.",
    why: "The preview classes every refused caller write against the write journal (replay attempts, later requests of the same page, recovered fact requests) in a few set reads. They use the `persistence_requests_replay_id` and `persistence_requests_slug_sequence` indexes; when either is missing or INVALID, or the journal is large enough that a set read outlasts the timeout, the server ends the read.",
    docs: 'docs/guides/troubleshooting.md#repair-preview-timeout',
    suggestion: 'Build the request indexes with gbrain repair request-indexes --apply, then run the same preview again; if it stops again with the indexes valid, run it once with a longer statement timeout on the brain host.',
    fix: { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'agent', why: 'Previews the request-table indexes without changing anything; the refusal names the ones the preview needs when they are not valid.', requires_exclusive: false } },
  request_already_submitted: { class: 'caller', summary: "This optimizer publication request has already been submitted." },
  request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },
  requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },
  requires_local_engine: { class: 'host_only', summary: "This command needs the brain's local database, and this install is a thin client of a remote brain." },
  restart_refused: { class: 'consent', exit: 3, actor: 'user', summary: "`gbrain upgrade` (or `--restart-only`) found a gbrain process on this host it cannot restart onto the new build (a serve or worker started by hand, an autopilot started outside its service by a launcher gbrain does not know, a running sync, or an MCP server an agent harness started), so it restarted nothing and, before a swap, installed nothing.", why: "A process keeps the build it started with, so restarting only some of them leaves serve, workers and MCP servers on different builds; the upgrade refuses instead of leaving that skew. Each process is named with the exact step that restarts it.", docs: 'docs/guides/upgrades-auto-update.md#restart', suggestion: 'Handle each listed process as the message says (MCP servers only: rerun with --stop-mcp after the user agrees), then run the same command again; `gbrain upgrade --no-restart` installs without restarting.', fix: { argv: ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every gbrain process on this host with its build and how each one restarts.', requires_exclusive: false } },
  restart_unverified: { class: 'host_only', summary: "After `gbrain upgrade` restarted this host's gbrain processes, one of them still runs another build, did not come back, or the warm CLI socket refused the new build.", why: "The restart is done only when every gbrain process on the host reports the installed build and serve's warm CLI socket accepts it; anything less is the version skew the restart exists to remove.", docs: 'docs/guides/upgrades-auto-update.md#restart', suggestion: 'Restart each process the message lists with the command the plan printed, then run `gbrain upgrade --restart-only` again.', fix: { argv: ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every gbrain process on this host with its build and how each one restarts.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } },
  reset_upstream_refused: { class: 'caller', summary: "gbrain sources reset-upstream changed nothing: the checkout moved since the reset was proposed, has no upstream, has uncommitted tracked edits, or has local commits that were never on the upstream (named, with the backup ref a reset would create).", why: "The reset is bound to the HEAD and upstream the user agreed to and drops only commits the upstream once had; anything else needs the user's decision first.", reasons: ['expect_mismatch', 'no_upstream', 'dirty_tree', 'local_commits'], reason_overrides: { dirty_tree: { class: 'consent' }, local_commits: { class: 'consent' } }, docs: 'docs/guides/troubleshooting.md#upstream-rewritten' },
  response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },
  resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },
  result_too_large: { class: 'caller', summary: "The tool's result is larger than this connection can carry in one response, so it was replaced by this error; nothing was cut.", why: "Results are measured as the complete encoded JSON-RPC frame (every block, notice and escape). A frame over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be rejected or silently cut by the client.", docs: 'docs/guides/windowed-reads.md#result_too_large', legacy_error: 'invalid_params', suggestion: "Ask for less in one call: a window (get_page body: 'window'), a page of rows (limit / from_index), or metadata only (get_versions include_body: false).", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size and outline, which name the windows to read.", requires_exclusive: false } },
  revision_changed: { class: 'caller', summary: "The page changed since the cursor or chunk id was issued, so that position no longer names the same text.", why: "Cursors and chunk positions are bound to one page revision; reading on from them after an edit could skip or repeat text without saying so.", docs: 'docs/guides/windowed-reads.md#revision_changed', legacy_error: 'invalid_params', suggestion: "Read again from the position in fix (the same byte offset at the current revision), or start over with body: 'outline'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the current revision and size.", requires_exclusive: false } },
  revision_backfill_pending: { class: 'caller', summary: "The page was written before page revisions existed and the revision backfill has not reached it, so it has no revision a write or preview can bind to.", fix: { argv: ['gbrain', 'apply-migrations', '--force-schema'], consent: [], actor: 'agent', why: "Re-runs the schema migration pass on the brain host, which resumes the page revision backfill and prints its progress; it changes no page content.", requires_exclusive: true }, docs: 'docs/guides/write-refusals.md#revision-backfill' },
  revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--include-content', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },
  revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed.", fix: { argv: ['gbrain', 'get', '--include-content', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },
  revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },
  schema_owner_required: { class: 'caller', summary: "The database role this command connects as may not create schema objects (Postgres 42501), so the schema repair created nothing.", why: "On a brain whose tables belong to a separate owner role, the application role cannot run DDL; only the owner can recreate a missing table.", docs: 'docs/guides/repair.md#missing-tables', suggestion: 'Run the same apply connected as the role that owns the brain tables (the one apply-migrations uses).' },
  scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },
  scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  search_cursor_requires_keyword: { class: 'caller', summary: "A search cursor was sent without match: \"keyword\"; cursors continue keyword listings only (hybrid rows are a ranked top-K with no next page).", suggestion: 'Send the next object from the previous search response unchanged; it carries match: "keyword".' },
  search_mode_local_only: { class: 'caller', summary: "An agent-facing caller set search's mode, which only the brain's operator chooses.", suggestion: 'Omit mode; for keyword-only matching with a total and paging, pass match: "keyword".' },
  scorecard_group_by_local_only: { class: 'caller', summary: "An agent-facing caller asked takes_scorecard for group_by or min_n, which read the private forecast journal and run only from the trusted local CLI.", suggestion: 'Omit group_by and min_n; the brain owner runs gbrain takes scorecard --group-by on the brain host.' },
  search_offset_over_cap: { class: 'caller', summary: "A search offset was over the 10,000 limit.", suggestion: 'Page with match: "keyword" and the next object each response returns; a cursor has no depth limit.' },
  segmented_mirror_writer_gate: { class: 'host_only', actor: 'host_admin', summary: "A withdrawal mirror of a page stored in segments waits because a gbrain that cannot read its recovery record, and that doctor segmented_storage still warns about, wrote to this brain in the last 7 days; the withdrawal is committed and the canonical file keeps the withdrawn row until the mirror runs.", why: "The mirror's version 2 recovery record names a streamed staging file; a gbrain below the segmented writer floor (v0.60.290.0) misreads it and wedges the worktree, so no record is written while the segmented-storage writer gate sees such a live writer (this host's own pre-upgrade writes, superseded by the upgraded build, do not count). The mirror retries, parks, and runs again by itself once the gate clears.", docs: 'docs/guides/write-refusals.md#segmented_mirror_writer_gate' },
  serve_build_drift: { class: 'host_only', summary: "A live `serve` or resident worker on this host runs an older gbrain build than this checkout: its `persistence_consumers` heartbeat `version` is below this binary's VERSION.", why: "Upgrading or pulling the checkout does not restart the processes already running from it, so one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts`) run newer code against the older consumer until serve and its workers restart. A serve older than the heartbeat table writes no row; `consumers_without_heartbeat` names it.", docs: 'docs/guides/troubleshooting.md#serve-build-drift', suggestion: 'Restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker; nothing restarts automatically.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the consumers alive on this host with each heartbeat row\'s kind, pid and gbrain version.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'serve_build_drift', '--json'] } } },
  runtime_build_skew: { class: 'host_only', summary: "Long-running gbrain processes on this host run different builds, or one runs an older build than its install holds on disk: serve, the jobs supervisor, worker parents (in memory) and the job children they spawn from the install (on disk).", why: "A process keeps the code it loaded at start, and `gbrain jobs run-child` spawns a fresh process from the install on disk for every job, so after a checkout reset or an upgrade on disk newer job code runs under an older worker and next to an older serve until each process restarts.", docs: 'docs/guides/troubleshooting.md#runtime-build-skew', suggestion: 'Restart the process the check names (serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid so its supervisor respawns it), then each other listed process on an older build; nothing restarts automatically.', fix: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the serve, supervisor, worker and recent job-child builds on this host with each pid and version.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } },
  serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },
  serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed', 'unavailable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },
  settle_mismatch: { class: 'server', retryable: false, actor: 'agent',
    summary: "A managed sync settled a file at the same level in three consecutive passes, but the next round never classified it settled, so the file is held instead of being re-imported every pass; the rest of the source synced.",
    why: "A pass records the level it settled each path at and the next round expects the same path to classify settled at that level. A path that keeps coming back unsettled at one level points to a broken writer, a stuck effect or a damaged record, not to the file; re-importing it every pass would spend work without converging, so after three passes sync holds it and stamps the rest.",
    docs: 'docs/guides/write-refusals.md#settle_mismatch',
    suggestion: 'Run gbrain doctor --json and gbrain sources writer status --source <id> --json (both read-only), fix or report what they name with the gbrain version, then gbrain sources retry-held <id> and gbrain sync --source <id> --no-pull.',
    fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: names a broken writer, a stuck effect or a damaged record.', requires_exclusive: false } },
  openclaw_not_found: { class: 'caller', summary: "gbrain setup openclaw --wakeshift found no openclaw on PATH, so Wakeshift's OpenClaw plugin was not installed; nothing changed.", why: 'The plugin installs through OpenClaw\'s own installer where the gateway runs, so setup never writes OpenClaw\'s plugin directory itself.', docs: 'docs/mcp/OPENCLAW.md#have-gbrain-report-back-to-this-chat', suggestion: 'Run gbrain setup openclaw --wakeshift where the OpenClaw gateway runs (in its container, if it is in one).' },
  setup_harness_unsupported: { class: 'caller', summary: "gbrain setup does not wire this harness yet; its guide has the manual connection steps.", why: 'Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host\'s config format.', docs: 'docs/guides/repair.md#setup-harness-unsupported', exit: 2, fix: { argv: ['gbrain', 'setup', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the harnesses setup wires and the guide for each.' } },
  setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },
  setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },
  setup_serves_several: { class: 'caller', summary: 'gbrain setup for one person was run on a brain that serves several people, and neither this harness\'s entry (--stdio-member) nor config mcp.stdio_member binds its stdio connection, so setup wrote nothing.', why: 'On a brain that serves several people an unbound connection reads every page no rule restricts, for whoever is asking; setup never writes one.', suggestion: 'Run gbrain setup <harness> --serves several --members <id,...> to label each person; add --stdio-member <member> only for a harness that one person alone uses.', fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows why the brain counts as several people, its members, its owner and the member the stdio server reads as.' } },
  setup_history_choice_required: { class: 'caller', summary: 'gbrain setup --serves several would turn a brain that serves one person shared while it holds pages no rule restricts, and nobody chose what happens to them, so setup wrote nothing.', why: 'Each member key setup mints reads every page no rule or readable_by restricts, so the owner\'s journal, DMs, chat, mail and conversation archive would reach every member; only the admin can decide that.', suggestion: 'Run setup again with --labelled-only to keep that history private (each member reads only pages labelled for them) or with --open-history to let the members read it.', fix: { argv: ['gbrain', 'doctor', '--only', 'open_shared_pages', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: counts the pages members\' keys can read, by folder.' } },
  setup_serves_unreadable: { class: 'caller', summary: 'gbrain setup could not read whether the existing brain serves several people, so it wrote nothing.', why: 'Setup writes an unbound connection only on a brain it knows serves one person; a brain it cannot read might serve several.', suggestion: 'Run gbrain access serves --json to see why the brain cannot be read, fix that, then run setup again.', fix: { argv: ['gbrain', 'access', 'serves', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: shows whom the brain serves, or the error that stops setup reading it.' } },
  hook_session_cwd: { class: 'caller', summary: "A gbrain hook or stdio MCP entry (setup, the turn-rule lane, gbrain bootstrap's lanes) starts gbrain in the session's directory, or the hook launcher it names would not run.", why: 'Script-mode gbrain is a Bun script, and Bun runs the working directory\'s bunfig.toml preload and loads its .env before gbrain starts; harnesses run hooks and stdio MCP servers in the session directory, so a cloned repository could run code on every prompt or session.', reasons: ['session_cwd', 'missing', 'stale', 'foreign'], docs: 'docs/guides/repair.md#hook-session-cwd', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the hook and the setup command that rewrites it through the launcher.' } },
  turn_hook_not_loaded: { class: 'caller', summary: "The per-turn hook that puts \"check gbrain first\" next to every user turn is missing, untrusted, or does not load in the harness.", why: 'Agents use the brain when that rule reaches them on every turn; registering the MCP server or writing an instruction file alone leaves them answering without it.', reasons: ['missing', 'untrusted', 'hook_failed', 'no_rule', 'not_loaded'], docs: 'docs/guides/repair.md#turn-hook-not-loaded', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which harness has no working per-turn hook and the command that wires it.' } },
  shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },
  shared_skills_unmanifested: { class: 'host_only', summary: "A conflict in the v0.53.0 shared-skills migration: a source's skills/ folder holds skills but the source has no skillpack.json declaring them, so the migration left them as they are.",
    why: 'Adopting skills nobody declared could publish private or half-finished ones, so the migration never adopts them and records the source as a conflict until a person decides. The conflict affects only shared-skills adoption; every other command works.',
    docs: 'docs/guides/shared-brain-skills.md#migrate-an-existing-brain',
    suggestion: 'Review the skills in that source\'s skills/ folder with the user, then either declare the ones to share in a skillpack.json at the source\'s root, or keep the source out of shared-skills adoption with `gbrain sources shared-skills <id> off`.',
    fix: { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists each source\'s shared-skills stage and names the sources in this conflict.', requires_exclusive: false } },
  shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },
  skill_asset_not_found: { class: 'caller', summary: "The requested file is not in the approved revision manifest." },
  skill_bundle_required: { class: 'caller', summary: "Import cannot publish skill paths." },
  skill_candidate_invalid: { class: 'caller', summary: "The optimized candidate changed protected frontmatter or has an empty/invalid body." },
  skill_not_found: { class: 'caller', summary: "No authorized published skill matches this key." },
  skill_catalog_mismatch: { class: 'caller', summary: "The skill catalog was built from a different skill list than the caller expects (expected_catalog_hash / --expect-catalog), so no suggestion was made and no session state was committed.", why: 'A block built from another skill list could name skills the harness cannot load.', docs: 'docs/guides/skill-resolver.md#skill_catalog_mismatch', suggestion: 'Rebuild the catalog from the current skill list (an adapter passes its new snapshot to gbrain skills index build --from-json -), then retry.', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows each catalog and its catalog_hash; changes nothing.' } },
  skill_catalog_too_large: { class: 'caller', summary: 'A skill source is over the resolver bounds (10,000 SKILL.md files or 100,000 directories per catalog), so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_catalog_too_large', suggestion: 'Split the source into several catalogs and pass them together with --catalog a --catalog b.' },
  skill_catalog_unknown: { class: 'caller', exit: 2, summary: 'The catalog name is not valid, or no catalog was named while several exist.', docs: 'docs/guides/skill-resolver.md#skill_catalog_unknown', suggestion: 'Pass --catalog with a name from gbrain skills index status (a-z, 0-9, _ and -, up to 64 characters).', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists every built catalog; changes nothing.' } },
  skill_index_incompatible: { class: 'caller', summary: 'The skill index is damaged or was built by an incompatible gbrain (another index format, ranker or tokenizer), so it was not read.', docs: 'docs/guides/skill-resolver.md#skill_index_incompatible', suggestion: "Rebuild the catalog with the command its receipt recorded (gbrain skills index status shows it); a catalog an adapter built from stdin is rebuilt by that adapter.", fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows each catalog, its receipt and its rebuild command; changes nothing.' } },
  skill_index_locked: { class: 'retryable', summary: 'Another process holds the skill-index lease for this catalog (a build, or a remove racing it), so this call gave up after its bounded wait.', why: 'Builds are serialized per catalog; a crashed holder is reclaimed only when its lease expires, never because its pid looks dead.', docs: 'docs/guides/skill-resolver.md#skill_index_locked', suggestion: 'Retry after the holder finishes or its lease expires (gbrain skills index status names the holder).', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows a running rebuild and its holder; changes nothing.' } },
  skill_index_missing: { class: 'caller', summary: 'The named skill catalog (or any catalog, when none was named) has not been built.', docs: 'docs/guides/skill-resolver.md#skill_index_missing', suggestion: 'Build it: gbrain skills index build --catalog <name> --dir <skills dir> (or --bundled, or --from-json <file>).', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the catalogs that exist; changes nothing.' } },
  skill_index_removed: { class: 'caller', summary: 'The catalog was removed while a build ran, so the build published nothing (a remove always wins).', docs: 'docs/guides/skill-resolver.md#skill_index_removed', suggestion: 'Run the build again if the catalog should exist.' },
  skill_resolve_invalid_input: { class: 'caller', exit: 2, summary: 'The turn or build input is not valid: bad JSON, an unknown field or harness, or a value out of range.', docs: 'docs/guides/skill-resolver.md#skill_resolve_invalid_input', suggestion: 'Send input that matches docs/schemas/skill-resolver.v1.turn-input.json (or the build flags in gbrain skills index --help).' },
  skill_resolve_no_input: { class: 'caller', exit: 2, summary: 'gbrain skills resolve got no message: no --text, and stdin was a terminal or empty.', docs: 'docs/guides/skill-resolver.md#skill_resolve_no_input', suggestion: 'Pass --text "<message>", or pipe turn JSON to gbrain skills resolve --input-json -.' },
  skill_resolve_timeout: { class: 'retryable', summary: 'The skill resolver ran past its deadline, so the turn got no block and no session state was committed.', docs: 'docs/guides/skill-resolver.md#skill_resolve_timeout', suggestion: 'The turn proceeds without a block; check the catalog size with gbrain skills index status.' },
  skill_resolver_config_invalid: { class: 'caller', summary: 'A skill resolver setting is out of range (skills.resolver.session_token_budget must be 0 or 100-50000; top_k, min_match, pinned and per_harness must be valid) or GBRAIN_HOME is not an absolute path.', docs: 'docs/guides/skill-resolver.md#skill_resolver_config_invalid', suggestion: 'Fix the value in config.json under skills.resolver (default budget 2000), or GBRAIN_HOME.' },
  skill_resolver_config_unreadable: { class: 'caller', summary: 'config.json exists but cannot be read or parsed, so the skill resolver lane stays silent and setup writes none of its keys (the file is never rewritten).', docs: 'docs/guides/skill-resolver.md#skill_resolver_config_unreadable', suggestion: 'Fix or move config.json in the gbrain config directory (GBRAIN_HOME/.gbrain, else ~/.gbrain; it must be a JSON object), then run gbrain doctor --only skill_resolver.', fix: { argv: ['gbrain', 'doctor', '--only', 'skill_resolver', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolver lane state and the config problem; changes nothing.' } },
  skill_resolver_setup_incomplete: { class: 'caller', summary: 'gbrain setup --skill-loading resolve found no skill to index (or could not build the catalog or wire the hook), so it wrote no config keys and no hook.', docs: 'docs/guides/skill-resolver.md#skill_resolver_setup_incomplete', suggestion: 'Add a skill to one of the scanned directories (the message names them), then run setup again.' },
  skill_resolver_plugin_not_installed: { class: 'caller', exit: 3, actor: 'user', summary: 'gbrain setup openclaw wrote the skill-resolver plugin, but OpenClaw has not installed or loaded it: no openclaw on PATH, an openclaw command failed, or plugins inspect does not show it loaded.', why: 'A partial install injects nothing, so setup never reports it as success; the files and the state are kept so the remaining commands finish it.', docs: 'docs/guides/skill-resolver.md#skill_resolver_plugin_not_installed', suggestion: 'Run the remaining openclaw commands the message names on the OpenClaw host, restart the gateway, then gbrain doctor --only skill_resolver.' },
  skill_resolver_host_not_local: { class: 'caller', summary: 'The OpenClaw skill-resolver plugin runs inside the gateway and needs this gbrain home, library and bin on the same machine, but this machine has no openclaw and no OpenClaw state directory.', docs: 'docs/guides/skill-resolver.md#skill_resolver_host_not_local', suggestion: 'Run gbrain setup openclaw --skill-loading resolve on the OpenClaw host itself.' },
  skill_resolver_selftest_failed: { class: 'caller', summary: 'The OpenClaw skill-resolver plugin is installed, but one turn through it under Node did not resolve (the library would not load or the worker did not answer).', docs: 'docs/guides/skill-resolver.md#skill_resolver_selftest_failed', suggestion: 'Read the code in the message (a library or worker code), fix it, then run gbrain setup openclaw --skill-loading resolve again.' },
  skill_resolver_pin_unknown: { class: 'caller', summary: 'A pinned skill is not in the catalog it is pinned to, so it is left out of the pinned block (an unchecked name never reaches the model).', docs: 'docs/guides/skill-resolver.md#skill_resolver_pin_unknown', suggestion: 'Check the name with gbrain skills pin list --catalog <c>, then remove or correct the pin.' },
  skill_resolver_library_missing: { class: 'caller', summary: 'The OpenClaw skill-resolver plugin found no library file for the sha256 its state names, so turns proceed without suggestions.', docs: 'docs/guides/skill-resolver.md#skill_resolver_library_missing', suggestion: 'Run gbrain setup openclaw --skills-index-only to rebuild the library and state.' },
  skill_resolver_library_mismatch: { class: 'caller', summary: 'The OpenClaw skill-resolver library file is outside the gbrain lib directory, not owned by the gateway user, writable by others, or does not hash to the recorded sha256, so the plugin refused to load it.', docs: 'docs/guides/skill-resolver.md#skill_resolver_library_mismatch', suggestion: 'Run gbrain setup openclaw --skills-index-only to rewrite the library; check who else writes the gbrain home.' },
  skill_resolver_library_skew: { class: 'caller', summary: 'The installed gbrain CLI is a different version from the library the OpenClaw plugin runs, and a refresh did not bring them in step, so the plugin keeps the last good library and stops retrying for a day.', docs: 'docs/guides/skill-resolver.md#skill_resolver_library_skew', suggestion: 'Run gbrain setup openclaw --skills-index-only and read its error.' },
  skill_resolver_worker_crash: { class: 'server', summary: 'The OpenClaw skill-resolver worker thread could not start or crashed; turns proceed without suggestions and it restarts with backoff.', docs: 'docs/guides/skill-resolver.md#skill_resolver_worker_crash', suggestion: 'Run gbrain doctor --only skill_resolver; report it if it repeats.' },
  skill_resolver_worker_stuck: { class: 'retryable', summary: 'The OpenClaw skill-resolver worker missed the turn deadline three times in a row, so it was restarted with backoff.', docs: 'docs/guides/skill-resolver.md#skill_resolver_worker_stuck', suggestion: 'Check the deadline-miss rate with gbrain doctor --only skill_resolver; a loaded host misses more often.' },
  skill_resolver_worker_unavailable: { class: 'retryable', summary: 'The OpenClaw skill-resolver worker is restarting after a crash or a stall, so this turn proceeded without suggestions.', docs: 'docs/guides/skill-resolver.md#skill_resolver_worker_unavailable', suggestion: 'Nothing to do if it is rare; gbrain doctor --only skill_resolver shows the rate.' },
  skill_resolver_state_missing: { class: 'caller', summary: 'The OpenClaw skill-resolver state file has no entry for this agent, so the self-test had nothing to run.', docs: 'docs/guides/skill-resolver.md#skill_resolver_state_missing', suggestion: 'Run gbrain setup openclaw --skill-loading resolve --agent <id>.' },
  skill_resolver_host_load_cut: { class: 'caller', summary: 'OpenClaw does not list some skills in the agent\'s skill directories (dropped at load by skills.limits.maxCandidatesPerRoot), so setup leaves them out of the agent\'s suggestions.', docs: 'docs/guides/skill-resolver.md#skill_resolver_host_load_cut', suggestion: 'Raise skills.limits.maxCandidatesPerRoot in openclaw.json, or split the skill root, then run setup again.' },
  skill_resolver_internal: { class: 'server', summary: 'The skill resolver failed unexpectedly; a scrubbed trace (no turn text) was written under skill-index/logs/.', docs: 'docs/guides/skill-resolver.md#skill_resolver_internal', suggestion: 'Run gbrain skills index status and report the trace if it repeats.', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows each catalog and its last build error; changes nothing.' } },
  skill_source_invalid: { class: 'caller', exit: 2, summary: 'The --from-json catalog or --routing file is not valid (not JSON, a malformed entry, over 10,000 skills or 8 MB, or a routing file over 1 MB), so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_invalid', suggestion: 'Pass a JSON array of {id, name, description, triggers?, routing?, body?, path?, eligible?} objects.' },
  skill_source_unreadable: { class: 'caller', summary: 'A --dir or --routing path (or, for `gbrain skills library`, gbrain\'s own source in a compiled binary) does not exist or cannot be read, so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_unreadable', suggestion: 'Pass an existing directory (or file) you can read; for the Node library from a compiled binary, download the release asset.' },
  skill_retention_capacity: { class: 'caller', summary: "Retained skill revisions exceed this source storage budget." },
  skill_unavailable: { class: 'caller', summary: "The qualified shared skill is not in this installation's current authorized view.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
  skillpack_backup_corrupt: { class: 'server', exit: 2, summary: "A skillpack update backup does not hash to the journal's pre-update hash, so restore will not write it.", why: "Restore only writes bytes it can prove are the file's pre-update content. Side effects: files restored before this one stay restored; this file and the rest are untouched.", suggestion: 'Leave the file as it is, or compare it with gbrain skillpack reference <skill> and edit it by hand.', docs: 'docs/guides/skillpacks-as-scaffolding.md#updating-installed-skills', fix: { argv: ['gbrain', 'skillpack', 'restore', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists every skillpack update backup, its status and its skills; changes nothing.', requires_exclusive: false } },
  skillpack_journal_not_found: { class: 'caller', exit: 2, summary: "No skillpack update backup has that id.", why: "Backups live under ~/.gbrain/skillpack-backups/<id>/ and are kept 30 days or the newest 10. Side effects: none.", suggestion: 'List the backups with gbrain skillpack restore --list.', docs: 'docs/guides/skillpacks-as-scaffolding.md#updating-installed-skills', fix: { argv: ['gbrain', 'skillpack', 'restore', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists every skillpack update backup, its status and its skills; changes nothing.', requires_exclusive: false } },
  skillpack_restore_conflict: { class: 'caller', exit: 2, summary: "A file changed after the skillpack update it would restore, so restore refused.", why: "Restore never overwrites an edit made after the update. Side effects: nothing was restored (a file that changes mid-restore stops the run; files already restored stay restored and a rerun is a no-op for them).", suggestion: 'Keep the later edit and restore the rest: gbrain skillpack restore <id> --skip <file>.', docs: 'docs/guides/skillpacks-as-scaffolding.md#updating-installed-skills', fix: { argv: ['gbrain', 'skillpack', 'restore', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists every skillpack update backup, its status and its skills; changes nothing.', requires_exclusive: false } },
  skillpack_state_locked: { class: 'retryable', exit: 2, summary: "Another gbrain skillpack command holds the lock on ~/.gbrain/skillpack-state.json.", why: "Scaffold, update, pin and restore read-modify-write the state file one at a time. Side effects: nothing was written by this command. A lock left by a crash is reclaimed after 10 minutes.", suggestion: 'Wait for the other command to finish and run this one again.', docs: 'docs/guides/skillpacks-as-scaffolding.md#updating-installed-skills', fix: { argv: ['gbrain', 'skillpack', 'restore', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists every skillpack update backup, its status and its skills; changes nothing.', requires_exclusive: false } },
  skillpack_update_incomplete: { class: 'caller', exit: 2, summary: "An earlier skillpack update of this skills root did not finish (a crash left its journal pending), so no new update runs.", why: "Some files of the interrupted skill may hold the new version and others the old. Side effects: nothing was changed by this run; --dry-run still previews.", suggestion: 'Run gbrain skillpack restore <id> (named in the message), then update again.', docs: 'docs/guides/skillpacks-as-scaffolding.md#updating-installed-skills', fix: { argv: ['gbrain', 'doctor', '--only', 'skillpack_update_incomplete', '--json'], consent: [], actor: 'agent', why: 'Reports skillpack updates a crash left unfinished and the restore command for each; changes nothing.', requires_exclusive: false } },
  skillpack_workspace_locked: { class: 'retryable', exit: 2, summary: "Another gbrain skillpack command holds this workspace's writer lock (.gbrain-skillpack.lock).", why: "One writer per skills root keeps an update and a restore from interleaving. Side effects: nothing was written. A lock left by a crash is reclaimed after 10 minutes.", suggestion: 'Wait for the other command to finish and run this one again.', docs: 'docs/guides/skillpacks-as-scaffolding.md#updating-installed-skills', fix: { argv: ['gbrain', 'skillpack', 'restore', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists every skillpack update backup, its status and its skills; changes nothing.', requires_exclusive: false } },
  slug_page_mismatch: { class: 'caller', retryable: false, actor: 'agent',
    summary: "Managed sync files a held file as a page whose slug the file does not carry as written, so removing its frontmatter `slug:` line would not clear the `frontmatter_slug_conflict` hold; nothing was written.",
    why: "The content-repair lane judges a held file with the screen managed sync froze it with (#6696). Sync keys a file to the page that records it as its origin (or its path-derived slug) and accepts a `slug:` line only when it equals the path-derived slug or that page's slug as written. When the page's slug differs from the path-derived slug (an older import that honored the line, or a source in a subdirectory of its Git repository), or the line reaches the page only through an alias, neither removing the line nor keeping it imports the file, so the lane records `slug_page_mismatch` with both slugs instead of a generic `still_invalid`.",
    docs: 'docs/guides/write-refusals.md#slug_page_mismatch',
    suggestion: 'Make the slug: line of the held file name the page it is filed as exactly (the hold slug in gbrain sources status <id> --json), or move the file to the path that derives that slug; commit and run gbrain sync --source <id> --no-pull. gbrain repair content --source <id> --only <path> previews the current state read-only.',
    fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
      why: 'Read-only: lists the held file with the slug sync files it as and its fix, which names the exact edit and the content-repair preview; nothing is written.',
      verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
  // #6694: a managed-sync checkpoint whose run's slug-root mode is not the mode the source pins (a subdirectory source only).
  slug_root_mode_mismatch: { class: 'caller', actor: 'user',
    summary: "A managed sync of a subdirectory source ran under one slug-root mode while the source pins the other (sources.config.slug_root_mode), so its checkpoint did not advance.",
    why: "At a subdirectory the two modes give different slugs (git-root keeps the subdirectory prefix, source-root does not), and the pin exists so a later sync never re-namespaces the source; the pages this run wrote already carry its mode. The pin changed after the run was discovered. A source rooted at its repository root never gets this code: both modes give it identical slugs, and its checkpoint keeps the pin it has. Older releases reported this refusal as revision_conflict.",
    suggestion: 'Ask the user which mode the source keeps. To keep the mode the run used, set sources.config.slug_root_mode back to it and run gbrain sync --no-pull --source <id>; the refused checkpoint is retried by itself. To keep the new pin, preview gbrain repair managed-sync-orphans --source <id> (it lists the refused cursor as slug_mode_refused), apply it with the hash it prints, and run gbrain sync --no-pull --source <id>, which discovers the source again under the pin; the pages the refused run wrote keep their old slugs beside the new ones.',
    fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,
      why: 'Read-only: last_error names the pinned mode and the mode the run used; the choice between them is the user\'s.' } },
  source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },
  source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed.", why: "Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). When that file is a committed Git change sync has not imported yet, the reason is pending_import: a refused remember is replayed once by the sync that imports it, any other write is resubmitted after that sync (docs/guides/write-refusals.md#pending_import). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. A canonical file that is gone while its page is live (reason canonical_file_missing, a ghost page) never clears by retrying or syncing: a person restores the file and syncs, or removes the page (docs/guides/write-refusals.md#canonical_file_missing)." },
  source_id_taken: { class: 'caller', summary: "This source already exists and does not match this exact admitted request." },
  source_mismatch: { class: 'caller', summary: "The request names a different source than the one this serve is bound to; it is refused, never rerouted." },
  source_not_ready: { class: 'caller', summary: "A committed source and approved schema are required." },
  source_profile_no_backfill: { class: 'unavailable', summary: "This source profile disables automatic embedding backfill." },
  source_pages_remain: { class: 'host_only', summary: "A source delete did not cascade to the source's pages, so it was rolled back and the source and its pages are unchanged.", why: "Every source delete relies on the pages -> sources ON DELETE CASCADE foreign key; without it the pages would stay live with no sources row, where no write, export or per-source audit can reach them (#7072)." },
  source_referenced: { class: 'caller', summary: "OAuth clients still reference this source." },
  source_retire_superseded: { class: 'caller', summary: "A retried source remove or purge was superseded: its source has since been removed, replaced or changed by another lifecycle operation; nothing was changed.", why: "A remove or purge records the source incarnation it was admitted against before it deletes its first page, so a retry of its request id can never delete the pages of a source re-added under the same ID, and a later lifecycle change to the source (such as a restore) abandons the request. A request refused this way stays refused.", suggestion: "Do not retry this request id. Read the source's current state; removing the current source is a new decision for the user, made with a new request id.", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: shows the source's current incarnation, binding, pending work and its stopped or superseded remove and purge requests (topology_requests).", requires_exclusive: false } },
  source_root_conflict: { class: 'caller', summary: "Multiple active sources alias this canonical skill root; resolve ownership before publishing." },
  source_root_unreadable: { class: 'host_only', retryable: false, reasons: ['missing', 'not_directory', 'permission_denied', 'symlink_loop', 'unreadable'], summary: "The source's registered root on its owner host cannot be read as a directory (gone, unmounted, not a directory, no permission or a symlink loop), so `gbrain sources canonical` planned and wrote nothing.", why: "Converting a source reads its whole checkout; a root that cannot be listed would otherwise surface as a raw filesystem or Git error, or as a missing-checkout refusal whose fix creates an empty repository there.", suggestion: 'Restore or remount the directory on the brain host (or make it readable to the account that runs gbrain), compare it with the root gbrain sources writer status --source <source> --json names, then preview again.' },
  source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },
  sources_not_readable: { class: 'host_only', retryable: false, summary: "An unscoped search, query, recall or list_pages came back empty and was refused: every source this connection can read (the default source and federated sources) holds no page every reader of that source can read (pages kept to named readers or private do not count; for recall and query, no active world fact either), while other sources on the brain hold such pages it cannot read (not federated, and no source grant).", why: "Answering would return an empty result that reads like a clean miss. The check is one yes/no about the whole brain, independent of the query: whether another source holds pages; it never says another source matches the question. Quarantined pages count on neither side, nor private pages when remote reads exclude them. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused.", docs: 'docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages', suggestion: 'Ask the user which source these connections should read; the brain host runs `gbrain sources federate <source>`, or grants the token its sources with `gbrain auth rescope --token <name> --sources <ids>`.' },
  split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },
  split_unparseable: { class: 'caller', summary: "Split unparseable." },
  stable_channel_unresolved: { class: 'unavailable', retired_in: 'TBD', reasons: ['unreadable', 'no_stable', 'no_release_tag'],
    summary: "Retired: an older gbrain could not name the stable release from the repository's tags alone. This build resolves stable from the published evidence record and reports stable_missing, stable_invalid or stable_unreadable instead.",
    why: "Since GBRA-224 the stable channel is the default and accepts only a release whose evidence record proves its gates passed on that exact tree; a message with this code came from an older build.",
    docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors',
    suggestion: 'Rerun gbrain self-upgrade --check-only --json on this build; it names the current stable code and its fix.',
    fix: { argv: ['gbrain', 'self-upgrade', '--check-only', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: checks the channel in effect and reports the current stable code, if any.' } },
  stable_invalid: { class: 'unavailable', summary: "The stable channel has no usable release: the published evidence record is missing, malformed, lacks an evidence key its generation needs (soak_run; matrix_run from the matrix cutover on), or names a version whose release tag is not the stable commit. Nothing was installed.", why: "A stable install accepts only a release whose record proves its gates passed on that exact tree; a record that does not prove it is never trusted, and the client never falls back to alpha by itself.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors', suggestion: 'Wait for a maintainer to repair or re-promote stable, or follow every release on alpha: gbrain config set self_upgrade.channel alpha (or the --channel / GBRAIN_RELEASE_CHANNEL override named in the message).' },
  stable_missing: { class: 'unavailable', summary: "No release has been promoted to the stable channel yet (no stable tag or no published evidence record), so the stable channel has nothing to install. Nothing was installed.", why: "Stable installs only promoted releases; an empty channel installs nothing rather than guess, and the background update check only reports it.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors', suggestion: 'Wait for the first stable promotion, or follow every release on alpha: gbrain config set self_upgrade.channel alpha (or the --channel / GBRAIN_RELEASE_CHANNEL override named in the message).' },
  stable_unreadable: { class: 'retryable', summary: "The stable channel could not be read: the evidence record or the repository's tags did not answer, or the stable tag and the record disagree while a promotion propagates. Nothing was installed.", why: "Without a verified answer the client installs nothing and keeps any earlier verified answer for the notice only; the channel is unchanged.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel-errors', suggestion: 'Retry in a few minutes: gbrain self-upgrade --check-only. Check network access to github.com and raw.githubusercontent.com if it repeats.' },
  stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
  state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  store_unavailable: { class: 'retryable', summary: "The object store an engine opened from settings names did not answer a file check (file_register, file_verify, file_url), so nothing was recorded and no file was reported missing.", why: 'A failed read says nothing about whether the object exists; reporting it missing could lead a host to re-upload or delete a file that is still there.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Check the store named in settings.storage (its path, or its endpoint, bucket and keys), then call again." },
  storage_adopt_field_refused: { class: 'consent', actor: 'user', summary: "Interim storage records carry fields a card refuses (a command, an unknown field, or a field stamped by gbrain), and the adopt apply did not name each one with --drop-field; nothing was written.", why: 'Adopting leaves those fields out of the card, so the user decides; the original pages keep them until finalize soft-deletes the originals.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Show the user the refused fields the adopt preview lists; with their agreement, run the apply the refusal names, which drops each with --drop-field.' },
  storage_adopt_unverified: { class: 'caller', summary: "An adopted interim original has no card on the storage shelf that matches its record, so finalize deleted nothing.", why: 'Finalize soft-deletes an original only when its card holds everything the record mapped to, so no archive record is lost.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Compare the original with its card (gbrain storage-get), fix the card or the record, then preview gbrain storage adopt --finalize again.' },
  storage_card_exists: { class: 'caller', summary: "A storage card with this id is already on the storage shelf; nothing was written.", why: 'Registering never overwrites a card, so two archives cannot silently share one id; a change to an existing card names the revision it read.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Change the card with gbrain storage-update <id> --expected-revision <revision from storage_get>, or register the new item under another id.' },
  storage_manifest_missing: { class: 'consent', actor: 'user', summary: "This brain has no storage shelf to write to (or the storage source ID belongs to another source); nothing was written.", why: 'On a brain with a Git checkout the shelf is a hosted git-canonical repository, created only after the user previews it, and hosting needs managed persistence. A repo-less brain gets its database-only shelf on the first register.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Preview gbrain storage init --dir <absolute path> --dry-run and apply the command it prints after the user agrees.' },
  storage_record_invalid: { class: 'caller', summary: "A storage card failed validation (a missing or malformed field, a command field, or a field gbrain stamps itself); nothing was written.", why: 'Every card must say where the item is, how big it is and how to restore it, and carries no commands, so a card is complete and safe to act on when it is found months later.', reasons: ['schema', 'command_field', 'stamped_field', 'not_json', 'not_object', 'too_large', 'id_change', 'no_record', 'truncated', 'duplicate_id', 'access_unpreservable', 'access_pending', 'labels', 'remote_written'], docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Fix the field the message names and send the card again; gbrain storage-register --help lists the card fields. For an adopt blocked on access_pending or access_unpreservable, settle the access rules over the interim page (gbrain access status) or give it readers its folder rules also list, then preview again. For truncated, move the ## Record section to the top of the interim page.' },
  storage_record_secret: { class: 'caller', summary: "A storage card field looks like a secret or has a credential shape; nothing was written and the value is not echoed.", why: 'Cards are read by agents and copied into the stores; credentials stay in the environment of the skill that restores an item.', reasons: ['secret_scanner', 'env_assignment', 'credential_variable', 'url_userinfo', 'presigned_url', 'credential_key'], docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Remove the secret, environment assignment, credential variable, URL password, signed-URL parameter or credential-named field from the card; a credential-named field that holds no credential can be renamed to end in _id, _ref or another suffix the rule passes.' },
  storage_revision_conflict: { class: 'caller', summary: "A storage card changed since the revision the update named was read; nothing was written.", why: 'Updates bind to the revision they read, so two writers never silently overwrite each other; the refusal carries the current revision in detail.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Read the card again with storage_get, apply the change to what it says now, and update once with its revision.' },
  storage_source_managed: { class: 'caller', summary: "A page write targeted the storage shelf outside the storage verbs; nothing was written.", why: 'The storage source holds only validated cards, so put_page, remember and the other page writers are refused there.', docs: 'docs/guides/write-refusals.md#storage-manifest-refusals', suggestion: 'Register cards with gbrain storage-register and change them with gbrain storage-update.' },
  storage_error: { class: 'server', summary: "Reading or writing durable storage failed.",
    reasons: ['database_contention'], reason_overrides: { database_contention: { class: 'retryable' } },
    why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `reason: database_contention`: a write admission that deadlocks, serialization failures, lock timeouts or statement timeouts kept refusing for its whole retry budget; no receipt was confirmed, so the same request_id is safe to retry once the contention clears. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",
    suggestion: 'For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json.' },
  strict_requires_managed: { class: 'consent', actor: 'user', summary: "A git-canonical source (config canonical: git) was written on a brain without managed persistence; nothing was written.", why: 'A strict source is committed to Git before the database indexes it, and only managed persistence (the writer coordinator) does that; the legacy writer of an unmanaged brain writes the database first.', docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#the-model', suggestion: 'Ask the user whether to turn on managed persistence for this brain, or to remove canonical: git from the source.' },
  sync_anchor_relative: { class: 'consent', exit: 3, actor: 'user', docs: 'docs/guides/troubleshooting.md#relative-source-path',
    summary: "Sync refused: the source's stored directory (sources.local_path, or sync.repo_path) is a relative path such as \".\", which names whatever directory gbrain runs from.",
    why: "A relative stored path cannot prove which folder is the brain. Before #7630 a sync run from an unrelated folder treated that folder as the brain repo: it Git-initialized it, committed everything in it and imported its markdown. gbrain now refuses before any Git probe or import, and nothing is changed.",
    suggestion: 'Ask the user which directory holds the source, then gbrain sources set-path <id> <absolute-directory>; or clear the pointer with gbrain sources set-path <id> --clear. A path that is absolute only on another operating system (a Windows drive path read on Linux or macOS) is refused the same way; set-path fixes it and --clear does not apply.' },
  sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own. `reason: plain_directory` (#7973): a plain directory registered with `sources add --force` is not a Git checkout, so the managed Git path refuses it; `gbrain sync --source <id>` imports its files without Git. `reason: checkout_missing`: a source that has synced from Git and whose root is no longer inside a Git checkout is refused, so its pages are not overwritten by an import; the user restores the checkout.", reasons: ['checkout_missing', 'content_directory', 'plain_directory'] },
  // #6712 PR 1: the drain lease (src/core/persistence/sync-lease.ts).
  sync_admission_restricted: { class: 'host_only', retryable: false, actor: 'user',
    summary: "`sync.admission` is not `normal`, so managed sync admits less than it classifies: `imports_only` admits no deletes and no keep_db writes (they wait as `paused_deletes` and `paused_keep_db`), and `classify_only` writes and stamps nothing.",
    why: "The owner sets the switch on the brain host (`gbrain config set`; it is never settable remotely) as the first response to a suspected sync bug. A pass reads it at pin and in every group's admission, and a destructive request re-reads it at publication, so the change applies at the next group; `sync status --json` reports `admission: {value, set_at, effective}`, where `effective` turns true once no pass pinned before `set_at` holds the lease and no delete or keep_db reconcile admitted before it is unpublished. Doctor warns, with the value's age, for as long as it stays restricted.",
    suggestion: 'Tell the user how long ago the switch was set and ask whether its reason still holds. Only they restore it: gbrain config set sync.admission normal on the brain host; the next sync admits what waited.',
    fix: { argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], consent: [], actor: 'user', requires_exclusive: false,
      why: 'Restores the default; the owner chose the restriction, so only they lift it, and gbrain never runs this on its own.',
      verify: { argv: ['gbrain', 'doctor', '--only', 'sync_admission_restricted', '--json'] } } },
  // GBRA-133 PR 3a: the sync watchdog's stop of a run that committed nothing before its progress-aware deadline (sync-reconcile.ts).
  sync_deadline_stalled: { class: 'server', retryable: false, actor: 'agent', summary: "A gbrain sync reached its progress-aware deadline having committed nothing (no page written, deleted or renamed, no cursor advanced), so it stopped as a stall instead of extending.",
    why: "The deadline extends only while a run commits work. Screening unchanged files, held files and legacy-sweep slices are not progress, so a run that spends its whole deadline on them reports a stall with its cause instead of \"still progressing\" or a clean resumable stop; rerunning the same way commits nothing again.",
    suggestion: 'Run gbrain sync status --source <id> --json (read-only): it names the step, holds and last error the source is stuck on. Fix what it names, then rerun the same sync.',
    fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: the source's state, holds, last error and the next step.", requires_exclusive: false } },
  sync_drain_lease_held: { class: 'retryable', actor: 'provider',
    summary: "Another process holds the source's drain lease and is still committing pages; this run followed it until its own budget ended, or lost the lease mid-pass, and stopped `resumable`.",
    why: "One managed drainer per source: two drainers on one cursor raced each other's checkpoints. A follower counts the holder's commits as its own progress, takes the lease when the holder releases it, and stops `drain_stalled` (cause `no_progress`) instead when the holder commits nothing for 5 minutes, so a wedged holder never reads as a clean exit.",
    docs: 'docs/guides/write-refusals.md#sync_drain_lease_held',
    suggestion: 'Rerun next.command after next.retry_after_ms (safe_to_loop), or let the holder finish; Ctrl-C while following leaves the holder running.' },
  sync_in_progress: { class: 'retryable', summary: "A sync is running on this source, or a write in flight or the sync's frozen manifest still names the file a repair would write.",
    why: "A repair that changed a file the running sync admits later would make that entry refuse on its raw hash, and a file a write in flight names would be written twice; so the one candidate waits while the rest of the source is repaired. `candidate_in_flight`: the file is named; `busy_set_unreadable`: the busy set could not be read, so every candidate waited.",
    reasons: ['candidate_in_flight', 'busy_set_unreadable'],
    suggestion: 'Nothing to do for the repair: the next run reads the file again. To finish the sync now: gbrain sync --source <id> --no-pull.' },
  // wave 18b #4960: doctor sync_freshness separates sync outcome from freshness for a source with no successful sync.
  content_receipt_stale: { class: 'unavailable', summary: "A gbrain-owned content source's shared-skills content receipt names another root than the source and its owner binding, so doctor sync_freshness cannot exempt it and sync does not apply.",
    why: "A writer transfer or relocation an older release ran (or a sources set-path still to run after a transfer accept) moved the canonical root but left the receipt (config shared_skills.content.v1.<source>.<incarnation>) on the old one. Current accepts and set-paths rebind it in their own transaction.",
    reasons: ['receipt_root_moved'], docs: 'docs/guides/repair.md#content-receipt-root',
    suggestion: 'Preview gbrain repair content-receipt-root --source <id> on the owner host and apply it with the hash it prints, or do what it names first (sources set-path, or a self-transfer).',
    fix: { argv: ['gbrain', 'repair', 'content-receipt-root', '--source', '{source_id}'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the receipt rebind and prints the apply command; writes nothing.' } },
  sync_first_run_in_progress: { class: 'retryable', summary: "A source's first sync is running (it holds a live sync lock inside the staleness ceiling) and no successful sync is recorded yet, so doctor sync_freshness warns instead of reading it as fresh.",
    why: "A sync stamps last_sync_at only when it succeeds; a running sync is not a fresh source, and starting a second one beside it only contends for the lock. Over the staleness ceiling the lock reads as wedged (fail) instead.",
    docs: 'docs/guides/troubleshooting.md#sync-freshness-no-successful-sync', suggestion: 'Wait for the running sync, then run gbrain doctor --only sync_freshness --json again.' },
  sync_no_successful_sync: { class: 'unavailable', summary: "No successful sync is recorded for a source (last_sync_at is NULL) and no sync of it is running; doctor sync_freshness fails with the last attempt's time, result and held files.",
    why: "The attempt comes from the newest sync job and, on a managed brain, the source's sync status (read-only). `reason` names the state: no_attempt (nothing recorded: run a sync), attempt_queued (a job is queued: wait), holds_pending (held files: inspect them first), last_attempt_unsuccessful (inspect the job or failure, then retry).",
    reasons: ['no_attempt', 'attempt_queued', 'holds_pending', 'last_attempt_unsuccessful'], docs: 'docs/guides/troubleshooting.md#sync-freshness-no-successful-sync',
    suggestion: 'Follow the check fix: it waits, inspects holds (gbrain sync status --source <id> --json) or retries (gbrain sync --source <id>) depending on the state.' },
  // wave 16 (GBRA-79) #6513: a managed-sync checkpoint whose cursor another run of the source replaced.
  sync_cursor_replaced: { class: 'caller', summary: "Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish.",
    why: "The replacing run (a rediscovery that retried a recorded failure, or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict.",
    suggestion: 'Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source.' },
  // GBRA-133 PR 3a: a live pass's checkpoint refused because its pass ended or another pass started (sync-checkpoint-replaced.ts).
  sync_pass_superseded: { class: 'caller', summary: "A sync pass's checkpoint did not publish because the pass that admitted it no longer holds the source (it ended, or another pass started); the next pass stamps its own checkpoint.",
    why: "A pass's checkpoint is bound to its drain lease and pass row, so it can never publish after that pass ends. Its receipt is a conflict that records no managed-sync failure and reads superseded in gbrain sources writer failures; a pass that stops with the checkpoint still pending reports disposition superseded instead of a request to resume.",
    suggestion: 'Nothing to repair or resubmit: the pages the pass committed stand. Let the next sync pass run (gbrain sync --source <id> --no-pull), and read gbrain sync status --source <id> --json to confirm the source converges.' },
  sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported; with `GBRAIN_SYNC_PARSER_REGRESSION=stop` set for the process that syncs (the default holds the file), the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull.' },
  tail_changed: { class: 'caller', summary: "The end of the page no longer has the sha256 the append expected, so nothing was appended.", why: "append_page's expected_tail_sha256 binds an append to the tail its caller read; another write changed it, and appending anyway could interleave text with a tail the caller never saw.", suggestion: "Read the page again (get_page body: 'none' returns tail_sha256), check whether the text is still missing, and append against the current tail with a new request_id.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the current revision and tail_sha256.", requires_exclusive: false } },
  tail_exposure_approval: { class: 'caller', summary: "A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended.", why: "Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself.", actor: 'user', docs: 'docs/guides/write-refusals.md#tail_exposure_approval', suggestion: 'Show the user the preview\'s exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull.' },
  tag_too_long: { class: 'caller', summary: "A page's tag is longer than the 2688 bytes a tag can be, so nothing was written (sync holds the file).", why: "Tags are stored in a btree index whose entries are at most 2704 bytes; a longer tag would fail the database insert (error 54000) and report a storage failure instead of naming the tag (#7052). The message names the tag's position and size, never its text.", docs: 'docs/guides/write-refusals.md#tag_too_long', suggestion: 'Shorten that tag or split it into shorter tags, then write the page again (for a file: edit it, commit and sync).' },
  take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },
  target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
  timeline_comment_markup: { class: 'caller', summary: "A stored timeline row carries HTML comment markup, so gbrain keeps it database-side and never writes it back into the page; clean it with gbrain repair timeline-comments.", docs: 'docs/guides/repair.md#timeline-comments' },
  source_writer_restricted: { class: 'caller', summary: "A write to a guest source came from a credential that is not on its writer list (the local CLI, an enforced member, or a removed writer included); nothing was written.", why: "A guest source holds notes saved for people outside the brain; only the writers the brain owner listed create pages there, so nothing else can make a guest's words look like the owner's or change them.", docs: 'docs/guides/write-refusals.md#source_writer_restricted', suggestion: "Do not retry. Write to another source; who may write a guest source is the brain owner's decision." },
  guest_page_immutable: { class: 'caller', summary: 'A guest page is saved once, as a new page, and never changed, and a guest source holds no facts, takes or timeline entries; nothing was written.', docs: 'docs/guides/write-refusals.md#guest_page_immutable', suggestion: 'Save the note again under a new slug, or ask the brain owner to promote it and edit the owner page.' },
  guest_page_promoted: { class: 'caller', summary: 'The brain owner kept this guest note as an owner page, so it is not deleted remotely; nothing was deleted.', why: 'A guest note the owner promoted is kept on the owner\'s word, so a broker\'s retention sweep cannot remove it.', docs: 'docs/guides/write-refusals.md#guest_page_promoted', suggestion: 'Do not retry. Treat the note as kept; only the brain owner removes it, on the brain host.' },
  guest_attribution_missing: { class: 'caller', summary: 'A write to a guest source carried no valid guest attribution (the X-Gbrain-Guest header or request-level _meta.guest with sender_label and group); nothing was written.', docs: 'docs/guides/write-refusals.md#guest_attribution_missing', suggestion: 'Send sender_label and group in _meta.guest or the X-Gbrain-Guest header, then save with a new request_id.' },
  guest_frontmatter_refused: { class: 'caller', summary: "A guest page's frontmatter held a key outside the allowlist, or a guest_sender or guest_group that differs from its attribution; nothing was written.", docs: 'docs/guides/write-refusals.md#guest_frontmatter_refused', suggestion: 'Send only type, title, readable_by, guest_group, guest_sender and saved_at, matching the attribution.' },
  guest_readers_invalid: { class: 'caller', summary: "A guest page's readable_by is not exactly the brain owner plus the one member or group the call speaks for; nothing was written.", docs: 'docs/guides/write-refusals.md#guest_readers_invalid', suggestion: 'Speak for one member or group and set readable_by to the owner and that principal.' },
  guest_promotion_owner_only: { class: 'caller', summary: 'Only the brain owner can keep a guest note as an owner page (promote_guest_note); nothing was read or written.', why: "A guest's words become the owner's only on the owner's word: the trusted local CLI, or a credential bound to the owner that speaks for no one else.", docs: 'docs/guides/write-refusals.md#guest_promotion_owner_only', suggestion: 'Do not retry. Ask the brain owner; if they want to keep the note, they run gbrain guests promote <slug> on the brain host.' },
  guest_mark_immutable: { class: 'caller', summary: 'A guest mark is never changed; it leaves only with its page.', docs: 'docs/guides/write-refusals.md#guest_mark_immutable' },
  guest_source_database_only: { class: 'caller', summary: 'A guest source is database-only: it takes no local path or repository, and a source with one cannot become a guest source.', docs: 'docs/guides/write-refusals.md#guest_source_database_only' },
  readable_by_invalid: { class: 'caller', summary: 'A remote write\'s readable_by is malformed, removes the field from a page that names readers, or would leave the page unreadable by the writer; nothing was written.', docs: 'docs/guides/write-refusals.md#readable_by_invalid' },
  timeline_rows_would_be_removed: { class: 'caller', summary: "A remote put_page or put_pages entry has no Timeline section and would delete the page's dated entries; resend it with the section or with drop_timeline: true.", docs: 'docs/guides/write-refusals.md#timeline_rows_would_be_removed' },
  timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },
  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'] } } },
  transcript_source_mismatch: { class: 'caller', reasons: ['corpus_source_other', 'corpus_source_unresolved', 'corpus_legacy_unstamped', 'corpus_stamp_missing', 'corpus_source_missing', 'corpus_source_archived', 'corpus_source_incarnation_changed', 'corpus_path_unresolvable', 'transcript_outside_corpus'], summary: "An explicit atom retry was refused before it started: its transcript does not resolve to the retry's source (a captured session of another source, a session with no known source, or a transcript outside the session corpus on a source other than default).", why: "A batch that failed before session routing may hold another source's session transcript; retrying it would write that session's atoms into the wrong source. Captured sessions resolve through their stamp, frozen record or the registered path containing their cwd, and nothing falls back to the retry's source.", suggestion: 'Run the atom drain for the source the session belongs to (corpus_source_other), or map a held session with gbrain sweep --assign-corpus <source> (preview first) and run that source.' },
  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 } },
  trust_raise_refused: { class: 'consent', exit: 3, actor: 'user', summary: "A write tried to raise the trust tier of a fact, take, page or timeline entry without the owner's confirmation, so nothing was changed.", why: "Only the owner can make memory more trusted: confirming on an interactive terminal, or through a connection that holds the memory_confirm scope. The database refuses any other raise so a bug or an agent write cannot promote its own content.", docs: 'docs/guides/error-codes.md#trust_raise_refused', suggestion: 'Do not retry. Ask the user to confirm the row themselves on the brain host (gbrain trust confirm <ref>), or leave its tier as it is.' },
  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." },
  unclosed_ambiguous_tail: { class: 'caller', summary: "A fence has no end marker and text follows its table, and the repair model read that tail as table rows written without pipes or could not tell, so gbrain will not choose where the fence ends; nothing was written.", why: "Closing after the wrong row would hide rows behind the privacy boundary or expose text; a deterministic rule cannot place the end marker and the model declined to, so a person decides. The attempt memo keeps the same bytes from costing a second model call.", actor: 'user', docs: 'docs/guides/write-refusals.md#unclosed_ambiguous_tail', suggestion: 'Read the page (gbrain get --source <id> -- <slug>), add the end marker after the last real row of the named fence (moving any rows the tail holds into the table), commit, then gbrain sync --source <id> --no-pull. The preview (gbrain repair fences --source <id> --only <path>, read-only) names the fence, section and last row.', fix: { argv: ['gbrain', 'repair', 'fences', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Read-only: names each held fence with its section and last parsed row so the person knows where the end marker belongs; writes nothing and calls no model.', requires_exclusive: false, verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },
  unexpected_file_bytes: { class: 'server', actor: 'user', summary: "A canonical file a write was publishing (or its file mode) matches neither its recorded prior nor its published bytes, so recovery left it untouched and its worktree stays blocked.", why: 'Something outside gbrain edited, split or restored the file while its write was publishing or recovering; gbrain never overwrites bytes it cannot account for.', suggestion: "Do not delete the file to unblock it. Inspect the owner (gbrain sources writer status --json shows the request and its blocked reason) and ask the user which version to keep: the bytes on disk, or the request's recorded prior or published bytes.", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the blocked request, its source and its blocked reason.', requires_exclusive: false } },
  unexpected_staging_bytes: { class: 'server', summary: "Recovery staging has unexpected bytes or identity; the root and its recovery capacity remain reserved." },
  unknown: { class: 'server', summary: "An unclassified failure (legacy StructuredError fallback code)." },
  unknown_command: { class: 'caller', summary: "The CLI has no command by that name.", suggestion: 'Run `gbrain --help` for the command list.', exit: 2 },
  unknown_flag: { class: 'caller', summary: "The command does not accept one of the flags passed.", exit: 2 },
  unknown_method: { class: 'caller', summary: "The JSON-RPC method is not supported." },
  unknown_source: { class: 'caller', summary: "The named source is not registered or is archived." },
  unknown_tool: { class: 'caller', summary: "The named tool does not exist or is not callable on this connection.", legacy_error: 'unknown_operation' },
  unknown_transport: { class: 'unavailable', summary: "The caller's transport could not be identified." },
  unpriced_model: { class: 'caller', summary: "The configured decide model has no price, so its spend cannot be metered; nothing was sent.", why: 'A `typesafe:<model>` id that gbrain ships no tariff for (a gateway-fronted or self-hosted Jev) would otherwise be admitted as $0 against `decide.budget.daily_usd` and its remote share, and the spend ledger would record $0 for a real bill (#5980).', docs: 'docs/guides/system-one.md#unpriced_model', suggestion: 'Register the price the endpoint bills with `gbrain pricing set typesafe:<model> --rate <usd-per-1M-input-tokens> --source <pricing-page-url>`, then `gbrain decide probe`.', fix: { argv: ['gbrain', 'pricing', 'list', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows the operator prices already registered, so the missing `typesafe:<model>` row is visible before anything is written.', requires_exclusive: false, verify: { argv: ['gbrain', 'config', 'get', 'pricing.overrides'] } } },
  unmanaged_database_path: { class: 'host_only', summary: "`gbrain backup create` refused before writing anything: the PGLite data directory is not the managed `<root>/.gbrain/brain.pglite` (a flat config home, or a path reached through a symlink).", why: 'The archive records the managed root it can restore into and refuses to follow a symlink out of it, so a flat or aliased layout cannot be archived without risking a restore into the wrong place.', docs: 'docs/guides/in-agent-setup.md#large-or-non-standard-brains-quiesced-physical-copy', suggestion: 'Take a quiesced physical copy into a new managed root (`<new-home>/.gbrain/brain.pglite`); the copy is then a normal layout that `gbrain backup create` accepts while it is under the 8 GiB cap.', fix: { ask_user: true, argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only, after the user agrees to the physical copy: doctor opens the brain only when no other gbrain process holds it, so a clean run shows the writers are stopped.", user_message: "This brain is outside what `gbrain backup create` can archive. Stop every gbrain writer on it (gbrain serve, jobs, autopilot, agent sessions), copy the whole data directory and config.json into a new isolated GBRAIN_HOME, point the copy's database_path at the copied data directory, then run gbrain doctor --json with GBRAIN_HOME set to the copy before relying on it.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },
  unmanaged_path: { class: 'caller', summary: "Reclone only replaces a checkout created and managed by GBrain." },
  unsupported_export_data: { class: 'unavailable', summary: "The source contains data this export path cannot carry." },
  unsupported_path: { class: 'caller', reasons: ['not_utf8', 'control_character'], summary: "Classic sync held a file whose name is not valid UTF-8 or contains a control character, so it cannot be a page path; the rest of the source synced.", why: "Git stores a name as bytes and a page path is text, so importing a lossy decoding would store a path no file has. The hold key spells the exact bytes (`/gbrain-bytes/` plus %XX escapes), the message names an item id bound to them, and the hold re-screens on every sync and clears once the name leaves the tree.", docs: 'docs/guides/write-refusals.md#unsupported_path', suggestion: 'Rename the file to a valid UTF-8 name without control characters (the hold\'s fix spells the old name with printf escapes, never raw bytes), commit, then run gbrain sync --source <source> --no-pull.' },
  unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },
  untrack_not_db_only: { class: 'caller', summary: "gbrain git commit-push --untrack in a managed canonical worktree was refused before the index changed: a file to untrack is not under a storage.db_only dir that the source's gbrain.yml (in the folder the source is rooted in) declares at HEAD and on disk, .gitignore does not ignore it, it is a symbolic link out of the dir, it is a Markdown page whose slug falls outside the dir, or it is a code-extension file that is a page, or that a code-importing source's sync imports as one, or that the source's last finished sync has not seen at its current version; or the brain, which records the source's folder, could not be read, which refuses every file.", why: "The next sync deletes the page of a file that leaves Git unless sync keeps it as database-only, which it decides by page slug, and a file .gitignore does not ignore can be committed again by any later commit.", docs: 'docs/guides/shared-checkout-git.md#untrack', suggestion: 'Follow the fix the refusal prints for each file: declare the folder under storage.db_only in the gbrain.yml the refusal names and its <dir>/ line in .gitignore (commit both with gbrain git commit-push -m <msg> -- <that gbrain.yml> .gitignore), add the .gitignore line, declare the slug spelling, keep code-file pages tracked, run gbrain sync --source <id> for code files sync has not seen yet, or retry once the brain is free; then rerun the untrack.' },
  upload_expired: { class: 'caller', summary: "The upload session passed its idle or hard deadline before it was committed, so its parts were discarded and nothing was written.", why: "Open sessions hold staged bytes against per-connection and per-brain quotas; persistence.limits.upload_idle_seconds (1 h) and upload_max_seconds (24 h) bound how long they may.", suggestion: 'Begin the upload again with a new request_id and send every part from part 0.' },
  upload_not_found: { class: 'caller', summary: "No open upload session matches this upload_id for this connection.", why: "A session answers only its creating connection, in its source, while the page it began against is unchanged; every other case gets this same answer so an upload_id reveals nothing.", suggestion: 'Begin a new upload with begin_page_upload and a new request_id.' },
  upload_protected_content: { class: 'caller', reasons: ['takes', 'facts', 'timeline'], summary: "A remote replace upload over 24 MiB was refused because the page holds content it cannot carry over: a takes fence or facts rows remote reads hide, or timeline rows.", why: "put_page keeps a hidden takes fence and hidden facts rows and checks omitted timeline rows by comparing whole bodies; an upload over the single-string ceiling is never held whole, so it refuses instead of dropping them.", suggestion: 'Replace the page with content of at most 24 MiB through put_page, write it locally on the brain host, or (timeline only) commit with drop_timeline: true when deleting every entry is intended.' },
  upload_too_many_parts: { class: 'caller', summary: "An upload part was refused because the session reached its part limit (64 plus one per 64 KiB of total_bytes) without completing the content.", why: "Each part is a stored row; the limit keeps a session of tiny parts from growing without bound, and a client cutting parts near part_max_frame_bytes never reaches it.", docs: 'docs/guides/write-refusals.md#upload_too_many_parts', suggestion: 'Send the rest of the content in that part (within part_max_frame_bytes), or abort and begin again cutting parts near part_max_frame_bytes.' },
  upstream: { class: 'retryable', summary: "Google connect credential error: upstream.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  upstream_diverged: { class: 'caller', actor: 'agent', summary: "A classic source's pull cannot fast-forward: the checkout has commits that are not on the upstream and the upstream moved forward; local HEAD keeps syncing.", why: "The upstream still contains the commit this checkout last pulled, so nothing was force-pushed: bringing the upstream in beside the local commits loses nothing.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Run gbrain git commit-push --pull --path <checkout>, then gbrain sync --source <id>.' },
  upstream_rewritten: { class: 'consent', actor: 'user', summary: "A classic source's upstream was force-pushed: the upstream commit the checkout last contained is not in the new upstream history, so the pull cannot fast-forward; local HEAD keeps syncing.", why: "Merging would bring back the commits the force-push removed, so the fix resets the checkout to the new upstream after the user agrees, keeping the old history under a backup ref.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then run the gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> command doctor sync_failures prints (preview with --dry-run), then gbrain sync --source <id>.' },
  upstream_unknown: { class: 'consent', actor: 'user', summary: "A classic source's checkout and upstream diverged and gbrain has no record of the upstream before the fetch (first pull after an upgrade, or the recorded commit is gone), so it cannot tell a force-push from local commits; local HEAD keeps syncing.", why: "Merging could bring back commits a force-push removed; the reset preview names any local commit that was never on the upstream before anything moves.", docs: 'docs/guides/troubleshooting.md#upstream-rewritten', suggestion: 'Ask the user, then preview the gbrain sources reset-upstream command doctor sync_failures prints with --dry-run.' },
  vector_prewarm_extension_missing: { class: 'host_only', actor: 'host_admin', summary: "`gbrain embeddings prewarm` was refused before reading anything because the pg_prewarm extension is not created in the brain's database (or the server does not ship it).", why: "Prewarm loads index pages into shared_buffers with pg_prewarm, the Postgres contrib function for exactly that; creating an extension needs a database owner or superuser, so gbrain never creates it itself.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Ask the database administrator to run CREATE EXTENSION IF NOT EXISTS pg_prewarm; (install the PostgreSQL contrib package first if the server lacks it), then rerun gbrain embeddings prewarm.' },
  vector_prewarm_unsupported_engine: { class: 'caller', summary: "`gbrain embeddings prewarm` was refused because the brain is PGLite; nothing was read.", why: "Prewarm fills a Postgres server's shared_buffers so later processes find index pages cached; PGLite runs inside each gbrain process, with no server cache that outlives it.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Nothing to do on PGLite.' },
  vector_prewarm_wont_fit: { class: 'host_only', actor: 'host_admin', summary: "`gbrain embeddings prewarm` was refused before reading anything because the brain's HNSW indexes are larger than half of shared_buffers.", why: "Prewarm loads the indexes into shared_buffers, the cache Postgres sizes and keeps; past half of it the prewarm would evict heap and keyword-index pages other reads need, so the next searches would pay first-touch reads on those instead. effective_cache_size does not decide: it is a planner hint, not memory the server holds.", docs: 'docs/ENGINES.md#vector-index-prewarm', suggestion: 'Raise shared_buffers on the database host to at least twice the index size the message names and restart Postgres, or leave the indexes cold; read the fit with gbrain embeddings prewarm --dry-run --json.', fix: { argv: ['gbrain', 'embeddings', 'prewarm', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: prints the index sizes, shared_buffers, effective_cache_size and the fit, and reads no relation page.', requires_exclusive: false } },
  verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },
  visibility_noncanonical: { class: 'caller', summary: "A file asks for visibility: private in a spelling page privacy does not read, so sync or import held it instead of storing it world-readable.", why: "Page privacy reads only the exact lowercase key and value visibility: private. A file that spells it another way (Visibility: private, visibility: Private, a block scalar, a list, a flow mapping or a merge key) would be stored as a world page while its author believes it is private (#7848); put_page, edit_page, capture, ingest_capture, brainstorm --save and sources reconcile refuse the same request as visibility_not_applied.", docs: 'docs/guides/write-refusals.md#visibility_noncanonical', suggestion: 'Write visibility: private on its own frontmatter line (lowercase key and value), then commit and sync, or import the file again.' },
  visibility_not_applied: { class: 'caller', reasons: ['noncanonical_value', 'not_kept'], summary: "A page write asked for visibility: private, but the page would have stayed world-readable, so nothing was written.", why: "A write that reports success while the page stays world-readable leaves the caller believing it is hidden. Page privacy reads only the exact lowercase key and value visibility: private (#7841). When the frontmatter is unreadable or ambiguous, the write is refused invalid_frontmatter instead.", docs: 'docs/guides/write-refusals.md#visibility_not_applied', suggestion: 'Read the page and its revision, write visibility: private on its own frontmatter line (lowercase key and value), then submit again with a new request_id.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Read-only: shows the page as it is now, with its revision.', requires_exclusive: false } },
  wakeshift_key_invalid: { class: 'caller', actor: 'user', reasons: ['format', 'checksum', 'legacy', 'file_too_open', 'missing'], summary: "The Wakeshift key is missing, mistyped, in an older format, or in a key file other users can read, so reporting back was not turned on.", why: "A Wakeshift key is an Ed25519 private key (wst_ followed by 50 base58 characters whose last four bytes are a checksum). gbrain reads it from WAKESHIFT_API_KEY or ~/.gbrain/wakeshift.key, which must be readable by its owner only; it never stores the key in the database or prints it.", docs: 'docs/guides/wakeshift.md#the-key', suggestion: 'Ask the user to create a key in their Wakeshift console and put it in ~/.gbrain/wakeshift.key (chmod 600) or WAKESHIFT_API_KEY in ~/.gbrain/.env, then run gbrain wakeshift enable again.' },
  wakeshift_needs_conversation: { class: 'caller', summary: "A watch tool (watch_job, watch_write_request, watch_cron) wakes an MCP conversation, and a local CLI run has none to wake.", docs: 'docs/guides/wakeshift.md#delivery-and-latency', suggestion: 'Run gbrain jobs wait <id> for a job, or gbrain write-request -- <request_id> for a write.' },
  wakeshift_not_enabled: { class: 'caller', summary: "Reporting back through Wakeshift is off on this brain (the owner has not run gbrain wakeshift enable, or the key is missing).", why: "Wakeshift is off by default; only the brain owner turns it on, on the brain host, because it sends wake metadata to a third-party service.", docs: 'docs/guides/wakeshift.md#turn-it-on', suggestion: 'Use wait_job (or gbrain jobs wait <id>) instead, or ask the brain owner to run gbrain wakeshift enable.' },
  wakeshift_refused: { class: 'caller', summary: "Wakeshift refused the request; the reason carries its error code. Nothing was watched or sent.", why: "Wakeshift checks each request (the signed key, the event and its arguments, the conversation's session key). A refusal other than a rate limit does not go away on retry.", docs: 'docs/guides/wakeshift.md#troubleshooting', suggestion: 'Call wait_job to wait without Wakeshift; the brain owner can run gbrain wakeshift test to check the key and the app.' },
  wakeshift_shared_brain: { class: 'host_only', actor: 'user', summary: "Reporting back refused (gbrain wakeshift enable, or a watch tool): this brain has live access members and its operator has not set the terms and privacy links Wakeshift requires.", why: "Wakeshift's terms (6.2, 6.6) make the operator show each person its own terms and privacy policy, which refer them to Wakeshift's Connector Terms and Privacy Policy, before the first wake. gbrain shows that step from the two links the owner sets on the brain host.", docs: 'docs/guides/wakeshift.md#shared-brains', suggestion: 'Ask the brain owner to run gbrain wakeshift enable --terms-url <https url> --privacy-url <https url>; meanwhile agents can use wait_job or get_write_request.' },
  wakeshift_unavailable: { class: 'unavailable', retryable: true, summary: "Wakeshift could not be reached or answered with a server error or rate limit; nothing was watched.", why: "gbrain makes one request with a 10 s timeout and never retries inside a tool call, so a slow or down Wakeshift never holds the call.", docs: 'docs/guides/wakeshift.md#troubleshooting', suggestion: 'Retry in a minute, or call wait_job to wait without Wakeshift.' },
  whole_class_prefer_unsupported: { class: 'caller', retryable: false, summary: "gbrain repair file-drift --whole-class settles only --prefer file on held side unknown, database or both, so a --prefer database or deleted-side selection was refused before anything was read.", why: "Letting the database win rewrites files, and each deleted-side state is its own decision; neither is settled for a whole class with one approval.", docs: 'docs/guides/repair.md#whole-class', suggestion: 'Preview that selection one window at a time with the per-window command the message names (--held --side <side> --prefer <side>, without --whole-class).', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },
  withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },
  withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },
  withdrawal_mirror_pending: { class: 'retryable', summary: "A page's Git or embedding work is waiting because its withdrawal mirror is queued or running again (for example after retry-effects).", why: "Git and embedding work behind a withdrawal mirror touches only the pages the mirror recorded rewriting (GBRA-130 A-12); while the mirror runs, the effect worker releases the work and picks it up once the mirror settles.", suggestion: 'Nothing needs resubmitting; read the effects with gbrain sources writer status <source> --json and wait for the mirror to finish.' },
  withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },
  write_capacity_backpressure: { class: 'host_only', retryable: false, summary: "A background producer (maintenance, conversation facts, an autopilot phase or an autopilot catch-up sync) stopped admitting writes because a cumulative write cap is past `persistence.capacity.background_pause_pct` (default 80); interactive writes keep the rest. Nothing was submitted and no receipt was written.", why: "Near a cumulative cap the remaining request ids and receipt bytes are kept for the user's own writes (remember, put_page, edit_page, operator sync, approved repair). Request ids are never freed, so past the line on ids only the brain host's config raise resumes background work; receipt bytes also free as receipts compact.", docs: 'docs/guides/write-refusals.md#write_capacity_backpressure', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Names the cap past the pause line, its days left and the reversible config raise, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },
  write_capacity_low: { class: 'host_only', retryable: false, summary: "A cumulative write cap is at or past 80% or runs out within `persistence.capacity.warn_days` (30) days at its 7-day rate; writes still work.", why: "Request ids are permanent and receipt bytes free only as receipts compact, so the cap is raised before admission refuses.", docs: 'docs/guides/write-refusals.md#write_capacity_low', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the forecast and the one-year config value, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } } },
  write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },
  write_gate_rejected: { class: 'caller', summary: "The write gate refused external instruction-like content because the operator set `write_gate.external_mode` to `reject`.", why: "Text from an untrusted source that reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request) is refused instead of held under that setting, so nothing was written. The same content refuses on every retry.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], suggestion: 'Tell the user the content was refused; whether to accept it or switch `write_gate.external_mode` back to `quarantine` is their decision.' },
  write_held: { class: 'consent', summary: "The write gate held this content for the owner's review instead of saving it as memory.", why: "Content from an untrusted source read like an instruction to an agent, so it was quarantined in the write-gate holding table. It is not searchable or recalled until the owner releases it; retrying the same write only re-opens the same hold.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], actor: 'user', exit: 3, suggestion: 'Do not retry. Tell the user what was held and give them the release command from the fix; releasing is their decision.' },
  write_interrupted: { class: 'retryable', retryable: false, actor: 'agent',
    summary: "The database kept ending this managed write's statements (SQLSTATE 57014, a statement timeout or cancel, or 0A000, a plan cached before a migration changed the table), or its publication kept running past persistence.publication_ceiling_ms and was cancelled, after persistence.max_transient_retries retries with backoff (default 5), so the owner finished it failed instead of preparing it again; nothing was published.",
    why: "Each such interruption throws the write's preparation away. It is load or latency, not the write's content, so it has its own retry budget: the request is claimed again after a backoff (1 s, 2 s, 4 s, 8 s, then 15 s; no claim is held while it waits) up to persistence.max_transient_retries times, and the next interruption ends it instead of preparing it again without limit. It never charges persistence.max_preparation_attempts, which preparations cut off at their deadline keep. Contention with other transactions (lock timeout, serialization failure, deadlock), a dropped connection and a restarting database are never counted. The receipt names the interruptions (attempts), the retry limit, the cause and the SQLSTATE.",
    docs: 'docs/guides/write-refusals.md#write_interrupted',
    suggestion: 'Inspect the owner with gbrain sources writer status --source <id> --json (read-only), then submit the write again with a new request_id once the database is less loaded; a held sync file needs gbrain sources retry-held <id> and the same sync. If the same write ends this way again, report its request id with gbrain doctor --json.',
    fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the owner process, its pool and what its writes wait on.', requires_exclusive: false } },
  write_outcome_unknown: { class: 'retryable', retryable: false, actor: 'agent',
    summary: "The database connection dropped while a write was being admitted, and it kept dropping through the re-reads, so whether the write was accepted is unknown.",
    why: "A session that closes under an admission (a pooler reap, a failover, pg_terminate_backend) leaves the transaction either committed or rolled back with no way to tell from the lost socket. gbrain re-runs the attempt, which starts by reading the retained request_id, so a single drop resolves by itself; this code means the database stayed unreachable through those re-reads. Before #6355 the raw socket error reached the caller, and a receipt oracle took it for a refusal while the write committed.",
    docs: 'docs/guides/write-refusals.md#write_outcome_unknown',
    suggestion: 'Read the request first (the fix names it): a committed or pending row means the write was accepted, replay the same request_id to wait for it; no row means it was not, submit it again with the same request_id. Never resubmit under a new request_id without that read.' },
  write_pending: { class: 'retryable', summary: "The write was accepted and is still pending; it may commit later.", exit: 10 },
  write_quota_exhausted: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes', 'staged_bytes', 'open_uploads'], summary: "A write cap (permanent request ids, reserved receipt bytes, staged upload bytes or open upload sessions, for the principal or the brain) is full, so the write was not admitted and nothing changed.", why: "Request ids are permanent replay protection and a receipt keeps its bytes until it compacts, so waiting does not free the cap; the brain host raises it with gbrain config set (reversible).", docs: 'docs/guides/write-refusals.md#write_quota_exhausted', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads which cap is full and the config value that covers one more year, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },
  write_quota_insufficient: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'], summary: "A bulk run (managed sync catch-up, reclone or a repair) estimated more new receipts than the remaining write capacity allows before its producer's pause line, so it did not start; other writes still work.", why: "Starting a run that the cap would stop part way leaves a long tail of pending pages; the preflight refuses up front with the config raise that covers the run.", docs: 'docs/guides/write-refusals.md#write_quota_insufficient', fix: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], consent: [], actor: 'agent', why: "Reads the remaining capacity and the one-year config value, read-only.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'persistence_capacity', '--json'], mcp: { tool: 'get_brain_health', arguments: {} } } }, exit: 12 },
  worktree_dirty: { class: 'caller', retryable: false, actor: 'agent',
    summary: "A managed sync held a file whose uncommitted working-tree bytes match neither the pinned commit nor the current page; the rest of the source synced and the local edit was not overwritten.",
    why: "On a live checkout an agent may be mid-edit on a file the catch-up reaches. The bytes are not committed at HEAD, so sync cannot tell a deliberate local change from a stray one, and importing the pinned version would discard the edit; before #6340 this refusal stopped the whole run.",
    docs: 'docs/guides/write-refusals.md#worktree_dirty',
    suggestion: 'Commit the file (or restore it), then run gbrain sync unblock --source <id> --apply (it re-screens every held file that is now committed) and the same gbrain sync; a later commit that changes the file re-screens it on its own.' },
  worktree_refreshing: { class: 'retryable', actor: 'provider', summary: "A write reached a checkout while `gbrain sources refresh` was draining, fast-forwarding or syncing it, so it was not journaled; nothing was recorded.", why: "A refresh fences every source bound to the checkout until its syncs finish, so no write publishes onto a moving HEAD. An interactive write waits out the fence for up to 10 s before this refusal; a refresh tick can hold it for minutes.", docs: 'docs/guides/write-refusals.md#worktree_refreshing', suggestion: 'Repeat the call with the request_id the refusal names after retry_after_ms (in detail); over MCP, fix.mcp is that call. Nothing was recorded, so the retry cannot write twice. gbrain sources writer status --source <id> --json shows the refresh.' },
  writer_admin_intent_required: { class: 'host_only', summary: "Topology changes require an action-specific --admin-intent and the --expected-state from a reviewed writer status." },
  writer_admin_locked: { class: 'host_only', summary: "Writer administration is locked; deactivation was not applied." },
  writer_admin_state_changed: { class: 'caller', summary: "Writer topology changed since inspection; the administrative request was not applied." },
  writer_busy: { class: 'retryable', summary: "The canonical worktree is busy with another write." },
  writer_coordinator_required: { class: 'host_only', summary: "The operation needs managed persistence (a writer coordinator) on the brain host." },
  writer_identity_invalid: { class: 'host_only', summary: "The local writer identity is invalid." },
  writer_identity_publish_failed: { class: 'host_only', summary: "The replacement writer is durable but its credential file could not be published." },
  writer_lock_unavailable: { class: 'retryable', summary: "A writer lock could not be taken: another process holds it (busy), or this process cannot open the lock file at all.", why: "Busy clears when the holder finishes. A process that cannot open the lock file (a sandbox, an unwritable lock directory) fails the same way on every retry, so its write stays queued with blocked_reason writer_lock_unavailable until an owner process that can take the lock publishes it; the OS error is kept in the owner-only detail.", suggestion: 'For a queued write, wait for the owner (gbrain sources writer status --json names it) or run the write from a process that can open the lock directory; retrying from the same sandboxed process changes nothing. The lock path and the rule that chose it are in onboarding.sources[].coordination_lock of that status. A claim refused while another process repairs an old reservation whose lock was recorded inside the checkout (old_path_wedge: true) succeeds once that repair finishes: run the claim again; never delete the reservation.' },
  writer_manifest_mismatch: { class: 'caller', summary: "Successor checkout differs from the recorded canonical manifest." },
  writer_manifest_rescope_required: { class: 'host_only', summary: "A writer transfer prepared by an older release covers every file of the old checkout, ignored files included, so a clean Git clone cannot match it.", why: "Transfer manifests now cover the files Git tracks, so ignored secrets such as .env files are never read, hashed or required on the successor; a manifest recorded before that change is prepared again instead of asking the user to copy ignored files.", docs: 'docs/architecture/topologies.md#transfer-manifest-scope', suggestion: 'On the owner host, run gbrain sources writer transfer prepare <source> again with its admin intent and state, then accept with the new epoch and manifest.' },
  writer_manifest_unsafe: { class: 'caller', summary: "The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, a Git-scoped comparison ran on a directory Git cannot list, or Git cannot read a directory that holds .git." },
  writer_not_initialized: { class: 'host_only', summary: "Persistence identity is missing." },
  writer_not_quiesced: { class: 'host_only', summary: "Older writers or maintenance jobs are still running." },
  writer_pool_capacity: { class: 'retryable', summary: "Mirror recovery is waiting for publication capacity." },
  writer_registration_required: { class: 'host_only', summary: "Writer registration required." },
  writer_regrant_required: { class: 'host_only', summary: "This lane already has a different grant." },
  writer_transfer_conflict: { class: 'caller', summary: "Writer transfer conflict." },
  writer_transfer_required: { class: 'caller', summary: "Writer transfer required." },
  writer_upgrade_required: { class: 'host_only', summary: "Apply the canonical writer guard, outbox, and source lifecycle migrations before activation." },
  wrong_account_consented: { class: 'caller', summary: "Google connect credential error: wrong account consented.", docs: 'docs/guides/google-connect.md#troubleshooting' },
  // W14 PR1 P1.2 (#6432): schema-pack file growth. Both are SchemaPackMutationError/SchemaPackLoaderError codes (PACK_TOO_LARGE, EMIT_MISMATCH) in their snake_case registry form.
  schema_pack_too_large: { class: 'host_only', actor: 'user', summary: "The schema pack file is larger than the load bound, so it was not read; a pack this large is almost always a quoted scalar (a link-type regex) whose backslashes an older release doubled on every mutation.",
    why: 'Loading a pack of that size took every CLI process to tens of GB of memory. The original text cannot be recovered automatically: after N doublings only the author knows the intended regex, so the fix is a hand edit of the grown lines.',
    docs: 'docs/architecture/schema-packs.md#oversized-pack',
    suggestion: 'Open the pack file named in the message, restore the grown quoted lines (usually `inference.regex` under `link_types`) to their intended text, save, and re-run. `GBRAIN_SCHEMA_PACK_MAX_BYTES` raises the bound for one command when a pack is legitimately large.',
    fix: { argv: ['gbrain', 'schema', 'active', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which pack is active and where it resolved; changes nothing.' } },
  schema_pack_emit_mismatch: { class: 'server', summary: "A pack mutation refused to write because the YAML it emitted did not read back as the manifest it holds; the pack file on disk is unchanged.",
    why: 'The write boundary parses its own output and compares it to the manifest as normalized structures, so an emitter/parser asymmetry can no longer corrupt a pack silently.',
    docs: 'docs/architecture/schema-packs.md#oversized-pack',
    suggestion: 'Re-run the mutation on the current release; if it refuses again, run `gbrain schema validate <pack>` and report the named key with `gbrain doctor --json`.',
    fix: { argv: ['gbrain', 'schema', 'active', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which pack is active and where it resolved; changes nothing.' } },
} as const satisfies Record<string, CodeEntry>;

export type RegistryCode = keyof typeof CODES;

/** One notice code (agent contract v1, A6). Lanes add producers' codes here. */
export interface NoticeEntry {
  kind: 'safety' | 'degraded' | 'coaching' | 'ask' | 'info';
  summary: string;
}

/** Notice codes. Mute (`gbrain notices mute`, `mute_notice`) accepts only coaching/info codes. */
export const NOTICE_CODES = {
  atom_drain_budget: { kind: 'info', summary: 'An atom drain (`gbrain dream --drain`) stopped at its per-run spending cap (`cycle.extract_atoms.budget_usd`): the notice names the spend, the cap and the pages left; the fix raises the cap (paid, ask first).' },
  hosted_option: { kind: 'coaching', summary: 'Shown when gbrain setup or an in-agent install creates a brain, and when gbrain mcp expose writes its first receipt or stops at a Tailscale or service step: gbrain.io is hosted GBrain. Mute with `gbrain notices mute hosted_option`.' },
  backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },
  empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },
  room_above_level: { kind: 'safety', summary: 'The answer goes into a shared room (a harness declared it with X-Gbrain-Room, _meta.room or a room argument) and some items carry room_access readable false or unknown: the room could not have read them itself. Use them to do the work, keep them out of the reply unless the ask needs them, offer the rest in a private chat; never refuse the work. docs/guides/rooms.md' },
  room_hints_unavailable: { kind: 'degraded', summary: 'A room was declared but its marks could not be computed (reason: invalid, not_permitted, unknown_principal, unbound, mark_failed, deadline, op_not_covered): the answer is complete and every item is marked unknown, so treat all of it as above the room. docs/guides/rooms.md#when-marks-are-unavailable' },
  room_conflict: { kind: 'safety', summary: 'The room argument named a different room than the harness declared (X-Gbrain-Room or _meta.room); the answer was marked for everyone either names, because an argument can only add people. docs/guides/rooms.md#channels' },
  first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run settings (search mode, writeback, skills, upkeep) are in effect as listed and the user may change them later: relay them once in the reply that reports the install, never hold the install open on them. The one muteable ask.' },
  harness_wiring: { kind: 'info', summary: 'init finished and no agent harness is registered yet: connecting gbrain to the agent is an install step the agent does now (`gbrain setup claude-code|codex`, or registering the stdio serve command in another host), not a setting that waits for the user.' },
  first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },
  source_not_in_default_search: { kind: 'info', summary: 'gbrain sources add or sync left a source out of default search (its federated setting is unset): searches, queries and recalls that name no source skip its pages, and connections with no source grant cannot read them. The fix is gbrain sources federate <id>; on a brain that serves several people or is not marked personal, federating is the user\'s call. docs/guides/multi-source-brains.md' },
  migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },
  unscoped_multi_user_token: { kind: 'safety', summary: 'An install route (gbrain setup openclaw|hermes|grok-bot|muse, setup claude-code with a chat-channel plugin, mcp grant, connect, skillpack scaffold for a bot harness, auth create, auth register-client) set up access that reads the same pages whoever talks to a likely multi-user agent: a bot harness, or a grant that reads chat from 2+ channels. Several people talking to that agent may get each other\'s messages. The notice names the fixes (a one-source grant, gbrain sources unfederate, visibility: private, a credential bound to each person, or one shared agent with may_act_for and a per-request audience); a credential holding may_act_for is not flagged; doctor `unscoped_multi_user_token` reports the same detection. docs/mcp/ADMIN.md#one-token-several-people' },
  socket_identity_mismatch: { kind: 'degraded', summary: 'The running serve\'s warm CLI socket refused this CLI call because an identity part (named, never its value) differs from the serve\'s, so the call ran on the slower cold path; doctor `cli_socket_refusals` counts these.' },
  sync_retry_failed_deprecated: { kind: 'coaching', summary: '`gbrain sync --retry-failed` is a deprecated alias for a plain sync, accepted for two releases: a plain sync retries a failure the previous run recorded by itself. Drop the flag.' },
  reason_not_committed: { kind: 'degraded', summary: 'A write\'s reason is in gbrain\'s page history but in no Git commit: on a non-strict source a newer write to the same file committed first, carrying only its own reason. Nothing needs fixing and retrying the write is wrong (docs/guides/page-history.md#reasons).' },
  wakeshift_report_back: { kind: 'coaching', summary: 'A remote submit_job or submit_agent was accepted: gbrain can wake this conversation when the job finishes (watch_job, when reporting back through Wakeshift is on; otherwise the brain owner turns it on with gbrain wakeshift enable). Once per session; mute with `gbrain notices mute wakeshift_report_back`.' },
  skillopt_loop_deprecated: { kind: 'coaching', summary: 'SkillOpt\'s iterative loop (the skillopt loop flag, `run_skillopt` `optimizer_mode: "reflect"`, a resumed loop run or a queued loop job) is deprecated and is removed on or after 2026-12-03; the run continues unchanged. Nothing replaces it: edit the skill directly, or run the default one-shot rewrite.' },
  sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source-id <id>`, or doctor for the statistics).' },
  no_resident: { kind: 'degraded', summary: 'gbrain sync trigger recorded the request (and queued a job or nudged the serve), but no resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches the source, so the recorded request waits until one starts or a sync reaches it; the fix syncs the checkout HEAD now (`gbrain sync --source <id> --no-pull`). docs/guides/on-commit-sync.md#no-resident' },
  no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
  config_write_shadowed: { kind: 'degraded', summary: '`gbrain config set chat_model|expansion_model` stored the value in the database, but a models.* config key, an environment variable (GBRAIN_MODEL, GBRAIN_CHAT_MODEL, GBRAIN_EXPANSION_MODEL) or the config.json pin outranks it, so the model in use does not change; `shadowed_by` names it (never its value) and the fix clears it (`gbrain config unset <models key>`, `gbrain config unset <key> --file`, or the user unsets the variable).' },
  valid_from_unparsed: { kind: 'info', summary: "A page write kept a `valid_from` that is not a calendar date (YYYY-MM-DD, a YAML date or a midnight-UTC timestamp), so that version is undated and get_page `as_of` never picks it; the write result's `valid_time` names it." },
  valid_time_correction: { kind: 'info', summary: "A page write changed the body and kept `valid_from`, so `as_of` reads treat it as a correction of the edition in force since that date; set `valid_from` if the change takes effect later." },
  valid_time_date_only: { kind: 'ask', summary: "A page write changed only `valid_from`: a corrected date and a renewal of unchanged text look the same, so `as_of` reads around these dates carry `ambiguous_edition_dates`. Ask the user which one it was." },
  ambiguous_edition_dates: { kind: 'ask', summary: "A get_page `as_of` answer is the selection rule's pick, but the versions around the date have an ambiguous shape (the same body under another `valid_from`, or a later-recorded version with an earlier one); `valid_time.competing_version_ids` names them and the fix asks which date the edition took effect." },
  calls_not_scoped: { kind: 'safety', summary: 'gbrain import --calls on a brain that serves two or more people imported new calls open to everyone who reads their source, as before, instead of keeping each to the owner and its attendees, because some caller that could be the owner\'s own would have lost them: no owner is named (owner_unset), the owner is not enabled (owner_inactive), a token or OAuth client bound to no person still reads the brain (unbound_readers), or a local stdio connection bound to nobody still reads it (stdio_unbound). The fix is the user\'s command for that reason; the next import keeps new calls to their attendees.' },
  privacy_label_ignored: { kind: 'safety', summary: 'A write (put_page, import or sync) stored a page whose `access` or `confidentiality` value is not one gbrain reads as private, with no `visibility` key: the label is ignored, so remote callers read the page like an unlabelled one and, on a source with a git repository, it is not kept out of git. The notice names the key and value (counts by value for a bulk run, never page content); the fix asks the user before adding `visibility: private`.' },
  unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
  record_types_undeclared: { kind: 'info', summary: 'entity.record_types names a page type that neither the schema pack declares nor any page uses, so no record of that type is listed.' },
  references_unavailable: { kind: 'degraded', summary: 'The reference count and records on entity rows did not finish (deadline or read failure); rows marked references_unavailable are unread, not empty.' },
  listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },
  former_relationships_hidden: { kind: 'info', summary: 'A graph read returned live relationships only and left out ended ones; the fix repeats the call with status: "all" (or as_of) to see history.' },
  identity_siblings_capped: { kind: 'info', summary: 'More than three pages share an entity\'s title subject, so the card shows no identity siblings; the fix (for the user) lists them with `gbrain extract mentions --explain`.' },
  alias_fanout: { kind: 'info', summary: 'search fanned out over an entity\'s other names and stopped at the per-call cap; the skipped names are listed and can be searched directly.' },
  search_filter_hint: { kind: 'info', summary: 'A search or query looked like it wanted a filter it did not pass (the query names a page type or a time, or one type fills the top results); the notice names types, since/until or where and the call to repeat. Results are unchanged.' },
  graph_walk_truncated: { kind: 'degraded', summary: 'traverse_graph stopped at its walk cap (pages visited or edge rows), so the deepest edges were dropped and the result is not the whole neighborhood; above depth 1 the fix repeats the walk one level shallower with the same link_type and direction; at depth 1 it carries no fix, so narrow with link_type or direction.' },
  loops_source_read_failed: { kind: 'degraded', summary: 'open_loops could not read the sources table, so google-source presence, sync ages and held mail are unknown: the answer carries no_google_sources: null and completeness: "partial", and an empty answer is not "inbox clean". The notice carries no database error text; repeat the call.' },
  loops_no_google_in_scope: { kind: 'info', summary: 'A remote open_loops call read no google source, so the empty answer is not "inbox clean"; the notice names only the sources the call read, all inside the caller\'s grant (never one outside it) and the fix lists them for source_id.' },
  mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },
  degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },
  source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },
  access_policy_pending: { kind: 'degraded', summary: 'A read touched a source whose folder rules are being narrowed or whose policy file does not validate: pages under the affected prefixes read as nobody until the brain host finishes it, so a missing page there is not proof the brain has nothing on it; the fix shows the policy state, then the host runs gbrain access resume --source <id> (database store); a git store finishes with gbrain sync --source <id> --no-pull.' },
  degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },
  facts_calibration_unmeasured: { kind: 'info', summary: 'recall --question ranked facts with semantic matching on an embedding model whose fact admission floors were never measured (`facts_calibration: {status: "unmeasured", model_key}`); a short facts list is weaker evidence of "nothing matched". Once per brain per session; the fix is the read-only `gbrain doctor --only fact_admission_floors --json`.' },
  entity_page_missing: { kind: 'info', summary: 'remember saved a fact for an entity that has no page, on a source whose pages are in Git: the fact is stored in the database only (`write_through.skipped: entity_page_missing`, no `page` in the reply) until the page exists. The step is ask_user: relay the user_message (saved in the database only; create a page for the entity?), and once the user agrees make the put_page call that creates the page; the next maintenance cycle can then move the entity\'s facts into its Facts table. On a source canonical in Git the fact is committed instead, held on memory/unattributed (`write_through.held_for`) until the page exists, and the notice has no step.' },
  private_fact_not_pushed: { kind: 'info', summary: 'remember saved a private fact: only local CLI recall reads it, and session hooks never push it into a new agent session.' },
  local_transcripts: { kind: 'info', summary: 'The brain host keeps recent session transcripts that page reads never return and this connection cannot read; the fix is the CLI read (`gbrain transcripts recent --json`).' },
  synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },
  think_not_saved: { kind: 'info', summary: 'think save/take persist only for the local CLI, so this answer was not saved.' },
  model_override_ignored: { kind: 'info', summary: 'A remote think named a model the brain host does not allow for remote callers (think.remote_models) or cannot run, so the host think model answered instead.' },
  onboard_opportunities: { kind: 'coaching', summary: 'Onboarding checks found work that would improve this brain (gbrain onboard --check lists it).' },
  onboard_stale_chunks: { kind: 'coaching', summary: 'This search could not match chunks that have no embedding; the remedy is an embedding backfill (paid, ask first).' },
  onboard_link_coverage: { kind: 'coaching', summary: 'Few people/company pages have incoming links, so backlinks and graph answers are thin; the remedy is link extraction.' },
  onboard_timeline_coverage: { kind: 'coaching', summary: 'Few people/company pages have timeline entries, so dated answers are thin; the remedy is timeline extraction.' },
  onboard_no_takes: { kind: 'coaching', summary: 'The brain holds no takes, so think and recall cannot cite the user\'s own views; the remedy is recording or extracting takes.' },
  grant_blocked_operations: { kind: 'info', summary: 'Once per session (per grant revision for stateless HTTP): this connection\'s grant cannot call operations its scopes allow; the notice names the blocker (operation snapshot, client pin or server ceiling; a missing scope on a refused call) with counts only and the brain owner\'s preview-then-apply rescope command.' },
  hidden_tool_content: { kind: 'info', summary: 'A page read or search left out takes that a tool outside this connection\'s tool list serves; the fix is the next step this connection can take (call takes_list, widen with request_tools, or the brain owner\'s repair).' },
  surface_env_invalid: { kind: 'info', summary: 'GBRAIN_SURFACE holds a value other than verbs, starter or full; the server ignored it and names the surface it serves.' },
  features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },
  delta_incomplete: { kind: 'degraded', summary: 'delta delivered less than is waiting and moved no cursor past it: an arm failed or the deadline fired (retry after a short wait; report after 3 consecutive wakes), or budget_tokens cannot fit one item (the fix names the budget that does).' },
  post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },
  behavior_changes: { kind: 'safety', summary: 'One-time disclosure of behavior an upgrade turned on (a live chat_fallback_chain, managed-brain lint repairs, smaller transcript parts, a mention-linker rescan); everything stays on, and the fix is optional.' },
  chat_fallback_hop: { kind: 'safety', summary: 'chat_fallback_chain sent a request to another model for the first time in this process; names the failed and the next model.' },
  facts_drain_first_run: { kind: 'info', summary: 'The automatic facts drain is about to process its first backlog on this brain: the queued page count, the estimated spend, the caps and the opt-out.' },
  facts_drain_deferred: { kind: 'degraded', summary: 'The automatic facts drain left queued pages waiting (no key, a spend cap, an unpriced model under a user cap); the fix is the next step.' },
  relational_chain: { kind: 'degraded', summary: 'A typed relationship chain found no complete answer (start page not visible, no typed edges, an empty hop) or hit a cap; the notice names the hop and the next call.' },
  pinned_answer_stale: { kind: 'degraded', summary: 'A pinned answer has stale sentences (their evidence changed or was removed) or its refresh is blocked; stale sentences are flagged and withheld from context_pack, and the fix is the next step.' },
  held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import (held new files are missing, pages whose newer file is held are stale), or pages in scope are held from embedding (no vectors); search and query show it when some could match the query, once per session per state. The fix is the repair preview, or gbrain embed --held --dry-run, on the brain host.' },
  recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },
  quoted_unverified_origin: { kind: 'info', summary: 'A remote get_page or fetch quoted a page only because its origin is unverified (trust tier `unknown`: saved before gbrain tracked trust, its source unclaimed). Shown once per session; it names the owner commands that clear it, gbrain trust claim-sources (preview with --dry-run --json) and gbrain trust backfill. Quoting is unchanged.' },
  page_quarantined: { kind: 'safety', summary: 'The page was quarantined by the content-quality gate (hidden from search; its facts and takes are not extracted). A read says to treat its text as untrusted scraped content and, for an untrusted reader, that its body was withheld (an admin-scoped caller may pass include_quarantined: true); a write says the page was hidden and that the operator clears a false positive with gbrain quarantine clear <slug> --force.' },
  git_index_restored: { kind: 'info', summary: 'A strict (canonical: git) write restored index to HEAD after an interrupted door refresh: the path\'s index entry still held the version before an earlier gbrain commit, whose index update had failed, so the write replaced it. The notice names the paths; nothing was lost, the earlier version is in Git history.' },
  fence_normalized: { kind: 'coaching', summary: 'A write\'s facts or takes fence was rewritten losslessly (rows and classes named, never values): the stored page differs from what was sent, so re-read it with get_page before editing; remember and takes_add write rows that never need it.' },
  write_capacity_low: { kind: 'info', summary: 'A cumulative write cap (request ids or receipt bytes) is at or past 80% or runs out within `persistence.capacity.warn_days`; writes still work. Write and sync receipts carry it at most once an hour per process per scope; sync status, doctor and autopilot cycle output every time. Mute on receipts with `gbrain notices mute write_capacity_low`; doctor still reports it.' },
  write_capacity_backpressure: { kind: 'degraded', summary: 'A cumulative write cap passed `persistence.capacity.background_pause_pct`, so background producers (maintenance, conversation facts, autopilot phases and catch-up syncs) pause while interactive writes keep the rest; shown once when the pause starts.' },
  embed_backfill_skipped: { kind: 'info', summary: 'The brain is keyless by choice (`embedding_disabled`), so no embed-backfill was queued or run (reason `embedding_disabled`) and search stays keyword-only. Reported once per brain state; the fix is the optional step that turns embedding on (names the provider key it needs).' },
  reason_scan_failed: { kind: 'degraded', summary: 'A sync could not read change reasons from Git for its range (a Git error or a timeout): content was imported, every reason in the pass is stored as empty, the pages it changed are marked with a history gap, and the range is not rescanned later. The fix lists the reasons with git log.' },
  reason_scan_capped: { kind: 'degraded', summary: 'A sync range held more than 10,000 commits, so its change reasons were not read: content was imported, every reason in the pass is stored as empty, the pages it changed are marked with a history gap, and the range is not rescanned later. The fix lists the reasons with git log.' },
  reason_trailer_secret: { kind: 'safety', summary: 'A gbrain-reason trailer already in Git looks like a secret; the notice names the commit and path (never the value), no reason was stored, and the user should rotate the credential because Git history keeps it.' },
  cycle_already_running: { kind: 'info', summary: 'Unattended upkeep skipped this run because another maintenance cycle holds the brain cycle lock; it retries on its next turn.' },
  engine_degraded: { kind: 'degraded', summary: 'Unattended upkeep skipped this run because the brain database was unreachable (degraded engine).' },
  maintenance_disabled: { kind: 'info', summary: 'Unattended upkeep is off on this brain (maintenance.auto is false).' },
  maintenance_owned_by_autopilot: { kind: 'info', summary: 'An autopilot keeps this brain maintained, so free upkeep did nothing.' },
  maintenance_owned_by_serve: { kind: 'info', summary: 'A live gbrain serve owns this brain and runs free upkeep while idle, so the scheduled upkeep run did nothing.' },
} as const satisfies Record<string, NoticeEntry>;