Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): classic Postgres unbound_source names write, commit, sync; not retryable, asks the user (#6277)
time-attack74af2eb8e40a
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 8c446885b1..0b690fd5cc 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELSpec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-contract/v1/`.- `src/core/fix-routing.ts` — A1 render-time routing pin: `pinRouting(argv, routing)` appends `--brain`/`--source` before a bare `--` for commands that route them (shared ops registered by `operations.ts`; CLI-only commands from the generated `CLI_ROUTING_FLAGS`, built from the command table's `phase`/`routes_source` and each command's code). Holds the CLI process's routing provider (`installCliRouting`, installed by `src/cli/fix-routing-provider.ts`; never for `serve`) and the first source the invocation resolved (`noteResolvedSource`, called by the source resolver). Never imports the command table (its lazy loaders would bundle every command). Tests: `test/fix-routing.test.ts`; journey proof in `test/agent-journey-recovery.serial.test.ts`.-- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace; an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.+- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `command`, and carries `next` only as the escalation `next: 'ask_user'` for a refusal whose every way out is the user's decision) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (a stored `next: 'ask_user'` → `ask_user`; no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace; an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex cf40cdac99..1be4a5d89d 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -54,7 +54,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. FENCE REPAIR RECEIPT: `fence_repair` is a reserved `put_page` param; `preparePageAdmission` refuses it (`invalid_params`) on every operation unless the call is a trusted local (`ctx.remote === false`) `put_page` whose value `parseFenceRepairReceipt` accepts; `page-prepare.ts` re-parses it from the stored intent, returns it in the outcome as `fence_repair` and gives the page's file target the `fenceRepairCommit` note for its source-relative path. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode` and `commit`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).-- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).+- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex e813dedb8d..6739ad1d8d 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -615,6 +615,9 @@ runbook above.binary writes there. That first command removes the markers and registryrecords of the retired epoch; a marker from an unknown or newer epoch (forexample after restoring an older backup) is kept and reported.+ On Postgres every filesystem source is now unbound: page writes refuse+ `unbound_source`, and the write path is the file, a commit and+ `gbrain sync` ([unbound sources](../guides/write-refusals.md#unbound-sources-on-postgres)).`min_writer_version` is not implemented: while the brain is managed, the databasewriter guard is the enforcement, and after deactivation that guard is inert.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 1812789bc5..0a1cf78763 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -36,6 +36,7 @@| [Doctor warns `host_identity_mismatch`, or maintenance jobs report `owner_unavailable` / `host_mismatch` for weeks](#host-identity-mismatch) | set `GBRAIN_HOME` on that process's supervisor to the value the check prints (the owner's home; config appends `.gbrain` itself) and restart it; never edit or delete a `host.json` | brain host, after the user agrees | `persistent_install` when it rewrites a service definition | `gbrain doctor --only host_identity_mismatch --json` || [`fence_repair` or chronicle refused `owner_unavailable`, reason `host_mismatch`](#owner-unavailable) | `gbrain sources writer status --source <id> --json` on the brain host (the owner host id); run the step there, or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. Do not retry from the same host | brain host | none | `gbrain sources writer status --source <id> --json` shows this host's id as the owner || [`owner_unavailable`, reason `transfer_in_progress` or `clone_in_progress`](#owner-unavailable) | wait 30 s and retry the same step; the worktree is draining for a writer transfer or recovering from a topology clone | agent | none | `gbrain sources writer status --source <id> --json` shows state `active` |+| [A page write refused `owner_unavailable`, detail `unbound_source`, on a classic Postgres brain](write-refusals.md#unbound-sources-on-postgres) | don't retry; write the page as `<slug>.md` in the source's checkout, commit it, and run `gbrain sync --source <id>` (a remote agent gives those steps to the user); database-only pages or managed mode are the user's choice | agent, after the user agrees (remote: user) | none | `gbrain get <slug> --source <id>` || [`owner_unavailable`, reason `binding_missing`, `incarnation_changed`, `local_path_missing` or `coordination_path_missing`](#owner-unavailable) | `gbrain sources writer status --source <id> --json`; the registration is missing or outdated and re-binding or re-registering the checkout is the host administrator's decision | brain host | none | the same status read shows an active binding for this host || [`gbrain repair fences` skipped a file `sync_in_progress` while a sync runs](repair.md#fence-repair-during-a-sync) | nothing: a write in flight or the running sync's frozen manifest still names that file; every other candidate repairs now and the next run picks this one up (`gbrain sync --source <id> --no-pull` finishes the sync) | agent | none | `gbrain doctor --only fence_integrity --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex a59a1fc1a7..ee07e82d99 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -53,7 +53,7 @@ of making a duplicate.| <a id="connector-holds-exhausted"></a>`connector_holds_exhausted` | `connector_holds_exhausted` | A Google or GitHub source already holds 100 items and this sync would hold another. The sync stopped without advancing its cursor. So many held items usually means a source-wide problem (a broken renderer, a revoked scope), not bad items. | `gbrain sources status <source>` to see the held items and their error codes, fix the cause, then `gbrain sources retry-held <source>` and `gbrain sync --source <source>`. `gbrain sync --source <source> --full` also clears every hold. || <a id="connector-fence-below-timeline"></a>`fence_not_carried` | `connector_fence_below_timeline` | A managed connector re-render would have dropped a facts or takes fence the stored page keeps below its timeline sentinel, or one that is duplicated, unbalanced or unparseable. The write was refused so those rows are not expired; the item is counted toward a hold. | Preview `gbrain repair connector-fences --source <source>`, apply it after review with `--apply`, then `gbrain sources retry-held <source>`. A page the repair counts as ambiguous needs a manual edit (see [repair](repair.md)). || <a id="unsupported-mutation-protocol"></a>`consumer_upgrade_required` | `unsupported_mutation_protocol` | A connector on v0.60.11.0 or later sent a `connector_v2_*` write to a persistence consumer older than v0.60.11.0, which does not know the format. Other `permission_denied` refusals on connector receipts are never relabeled as upgrades. | `gbrain upgrade` on every consumer and worktree-owner host, then `gbrain sync --source <source>`. Upgrade those hosts before connector hosts. |-| `unbound_source` | `owner_unavailable` | On Postgres, a page write went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. See [unbound sources on Postgres](#unbound-sources-on-postgres). |+| `unbound_source` | `owner_unavailable` | On Postgres, a page write went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Classic mode: write the file, commit, `gbrain sync --source <source>` (a remote agent asks the user to). Otherwise bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. Not retryable. See [unbound sources on Postgres](#unbound-sources-on-postgres). || <a id="embedding_zero_norm"></a>`zero_norm`, `non_finite` or `empty_input` | `embedding_zero_norm` | The embedding provider returned a vector with no direction (all zeros, NaN or infinity) for a chunk, or the chunk text was empty. A vector index silently skips such a row, so gbrain refuses to store it. Only that chunk is refused: the page text and every other chunk's vector are saved, and the page is left for `gbrain embed --stale`. It is never retried as a rate limit or network error. | Inspect the named page's chunk text (empty, whitespace- or symbol-only chunks are the usual cause) or the embedding provider, fix it, then run `gbrain embed <slug>` (add `--source <source>` for a non-default source). If normal text also returns zero vectors, the provider or model is broken; check it with `gbrain doctor`. || `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. An effect `error_code` of `git_index_stale` means an index lock older than 10 minutes blocks the checkout: `.git/index.lock` in it (`git -C <checkout> rev-parse --git-path index.lock` for a linked worktree). Remove it only if no git command is running there, then run the `retry-effects` command. A fresher lock (`git_index_locked`) is retried as contention and never parks. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. || <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |@@ -479,8 +479,45 @@ that checkout, through the source's canonical owner. PGLite claims that ownerautomatically on the first write. Postgres does not, because several hosts canshare one Postgres brain and only one of them may own the files. Until someonebinds the source, page writes to it refuse with-`owner_unavailable` and `detail: unbound_source`. The suggestion names both-ways out with the real source filled in:+`owner_unavailable` and `detail: unbound_source`. The refusal is a+configuration state, not a transient one: it renders `retryable: false` and a+`fix` with `next: ask_user`, so an agent never retries it.++**Classic mode (managed persistence not activated).** This is the normal state+of a self-hosted Postgres brain that never ran+`gbrain sources writer activate`, and of any brain after+`gbrain sources writer deactivate`. In classic mode the checkout is the source+of truth: gbrain reads it and does not write files into it. Page writes through+`put_page`, `capture`, `delete_page`, `restore_page`, `revert_version`,+`add_tag`, `remove_tag`, `add_timeline_entry` and the `takes_*` tools refuse+with `unbound_source`. What works:++1. **Write the file, commit, sync** (the classic write path). Write or edit+ `<checkout>/<slug>.md`, check generated frontmatter with+ `gbrain frontmatter validate --stdin --path <slug>.md`, `git commit` it, then+ run `gbrain sync --source <id>`. Sync imports commits; `--working-tree`+ imports uncommitted edits for one run. Delete with `git rm`, commit, sync.+ Tags and timeline entries are frontmatter and `## Timeline` lines in the+ same file.+2. **Database-only pages**, if the user accepts that new pages never reach the+ checkout, its git history or file backups:+ `gbrain config set persistence.unbound_write database_only` (below). It+ never covers pages that came from files.+3. **Leave classic mode** (a brain-wide decision for the user): claim the+ source and activate managed persistence+ ([topologies](../architecture/topologies.md#pre-activation-claims)). A claim+ without activation blocks classic `gbrain sync` of that source, so never+ claim to get one refused write through.++**What the agent tells the user.** An agent with a shell on the brain host+asks once, then uses path 1 itself and reads the page back. A remote agent+(MCP) cannot write the checkout; it says: *"Your brain is in classic mode, so+I can't save pages directly. Save it as `<slug>.md` in the `<id>` folder,+commit it, and run `gbrain sync --source <id>`. Or I can explain the two other+options: database-only pages, or managed mode."* It does not retry the write.++**Managed mode, or a gbrain-owned checkout.** The suggestion names both ways+out with the real source filled in:1. **Bind the source** on the host that holds the checkout. Run`gbrain sources writer status <source> --json` and note `admin_state`, thendiff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex 2794761e41..e52efbc9f9 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -667,11 +667,12 @@ First matching row wins.| # | Condition | `next` ||---|---|---|-| 1 | no runnable step (no `argv`, no callable `mcp`, and not an MCP-only fix on the CLI) | `report`: relay `message`; run `gbrain doctor --json` where you can |-| 2 | `actor = provider` | `wait`: retry after the stated delay with the same request identity |-| 3 | `actor` is `user` or `host_admin`, or the fix is CLI-only and you are on MCP, or MCP-only and you are on the CLI | `tell_user_to_run` |-| 4 | `consent` is non-empty and not covered by a matching preapproval (`destructive` never is) | `ask_user` |-| 5 | otherwise | `run` |+| 1 | the stored fix asks the user (a refusal whose every way out is the user's decision, such as `owner_unavailable` with `detail: unbound_source`) | `ask_user` |+| 2 | no runnable step (no `argv`, no callable `mcp`, and not an MCP-only fix on the CLI) | `report`: relay `message`; run `gbrain doctor --json` where you can |+| 3 | `actor = provider` | `wait`: retry after the stated delay with the same request identity |+| 4 | `actor` is `user` or `host_admin`, or the fix is CLI-only and you are on MCP, or MCP-only and you are on the CLI | `tell_user_to_run` |+| 5 | `consent` is non-empty and not covered by a matching preapproval (`destructive` never is) | `ask_user` |+| 6 | otherwise | `run` |A CLI-only fix rendered for an MCP caller gets actor `user` on stdio and`host_admin` on HTTP, and `next: tell_user_to_run`. The mirror case: an@@ -1000,6 +1001,20 @@ stderr. If such a command exits non-zero without writing its document, gbrainwrites a fallback: `{error: "command_failed", code, message, suggestion,exit_code, contract_version: 1}`.+## A write refused `owner_unavailable` with `detail: unbound_source`++On a Postgres brain in classic mode the files in a source's checkout are the+truth, and gbrain only reads them. Do not retry, and do not claim the source or+activate managed mode to get one write through: both change the whole brain and+claiming blocks classic sync. If you can run commands on the brain host, write+`<checkout>/<slug>.md`, commit it, run `gbrain sync --source <id>`, then read the+page back. If you are connected remotely, tell the user: "Your brain is in+classic mode, so I can't save pages directly. Save it as `<slug>.md` in the+`<id>` folder, commit it, and run `gbrain sync --source <id>`." Offer+`persistence.unbound_write database_only` or managed mode only as the user's+choice, with what each costs+([unbound sources](../guides/write-refusals.md#unbound-sources-on-postgres)).+## Marker grammarText output without a terminal uses one block format, built by one modulediff --git a/skills/RESOLVER.md b/skills/RESOLVER.mdindex df0523acfb..a737aa46d1 100644--- a/skills/RESOLVER.md+++ b/skills/RESOLVER.md@@ -119,6 +119,7 @@ off until the user opts in, and paid enrichment is a separate choice.| Post-restart health + auto-fix, "did the container restart break anything", smoke test | `skills/smoke-test/SKILL.md` || `GBRAIN_DB_ACCESS`, "gbrain database error", "gbrain connection refused", "brain database is down", "cannot reach the brain database", "fix gbrain database access", "repair gbrain postgres" | `skills/db-repair/SKILL.md` || Doctor `timeline_history` / `derived_visibility` / unsealed pages, "repair timeline history", "fix atom visibility", "re-seal withheld pages" | Preview with `gbrain repair`, apply one kind with `gbrain repair <kind> --apply` on the brain host after the user agrees. See `docs/guides/repair.md` |+| A page write refused `owner_unavailable` with `detail: unbound_source` (classic Postgres) | Write the file, commit, `gbrain sync --source <id>` (remote: relay to the user); never claim or activate to get one write through. See `skills/conventions/agent-operator-protocol.md` || A write or sync refused with `file_database_drift`, `ambiguous_source_path`, `physical_root_device_changed`, `cursor_processing_options_conflict`, `take_row_collision`, `invalid_source_uri`, `queue_capacity`, or doctor `parked_effects` | Relay the error's `suggestion` command; see `docs/guides/write-refusals.md` before running it || A gbrain command or MCP tool returned an error, exited 3 (`confirmation_required`), 10 or 11, or printed `[AGENT]` / a notice block; "what does this error code mean" | Follow the agent operator protocol, `docs/protocol/AGENT_OPERATOR_v1.md` (read `code`, follow `fix.next`); look a code up offline with `gbrain errors <code>` || Cross-modal review, second opinion | `skills/cross-modal-review/SKILL.md` |diff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.mdindex 23ab8b5a25..d85259cf21 100644--- a/skills/brain-ops/SKILL.md+++ b/skills/brain-ops/SKILL.md@@ -255,6 +255,7 @@ the citation is `[gstack:plans/foo]`. That's the whole rule.Follow the [agent operator protocol](../conventions/agent-operator-protocol.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:- `put_page` returns `revision_conflict`: re-read the page, merge your change into the new text, and save with the new revision. `write_pending` (exit 10): poll `get_write_request` (`gbrain write-request <request_id>`) before claiming the write landed.+- `put_page` (or `capture`, tags, timeline) returns `owner_unavailable` with `detail: unbound_source`: this is a classic Postgres brain. Write the page as a file in the source's checkout, commit, and run `gbrain sync --source <id>`; if you are remote, give those three steps to the user. Never claim the source or switch modes to get the write through (see the [agent operator protocol](../conventions/agent-operator-protocol.md#a-write-refused-owner_unavailable-with-detail-unbound_source)).- A write is refused by the secret scan or a slug fence (`permission_denied`): do not strip or rename to dodge it; tell the user what was refused and why (see `docs/guides/write-refusals.md`).- `recall` / `search` returns nothing with a degraded notice or `search_degraded`: say the brain is searching keywords only right now, not that nothing is saved.- `insufficient_scope` / `scope_denied` over MCP: the connection lacks that scope. Tell the user; never ask for a broader token just to make a write pass.diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.mdindex f5a7ebabf3..d985233120 100644--- a/skills/conventions/agent-operator-protocol.md+++ b/skills/conventions/agent-operator-protocol.md@@ -669,11 +669,12 @@ First matching row wins.| # | Condition | `next` ||---|---|---|-| 1 | no runnable step (no `argv`, no callable `mcp`, and not an MCP-only fix on the CLI) | `report`: relay `message`; run `gbrain doctor --json` where you can |-| 2 | `actor = provider` | `wait`: retry after the stated delay with the same request identity |-| 3 | `actor` is `user` or `host_admin`, or the fix is CLI-only and you are on MCP, or MCP-only and you are on the CLI | `tell_user_to_run` |-| 4 | `consent` is non-empty and not covered by a matching preapproval (`destructive` never is) | `ask_user` |-| 5 | otherwise | `run` |+| 1 | the stored fix asks the user (a refusal whose every way out is the user's decision, such as `owner_unavailable` with `detail: unbound_source`) | `ask_user` |+| 2 | no runnable step (no `argv`, no callable `mcp`, and not an MCP-only fix on the CLI) | `report`: relay `message`; run `gbrain doctor --json` where you can |+| 3 | `actor = provider` | `wait`: retry after the stated delay with the same request identity |+| 4 | `actor` is `user` or `host_admin`, or the fix is CLI-only and you are on MCP, or MCP-only and you are on the CLI | `tell_user_to_run` |+| 5 | `consent` is non-empty and not covered by a matching preapproval (`destructive` never is) | `ask_user` |+| 6 | otherwise | `run` |A CLI-only fix rendered for an MCP caller gets actor `user` on stdio and`host_admin` on HTTP, and `next: tell_user_to_run`. The mirror case: an@@ -1002,6 +1003,20 @@ stderr. If such a command exits non-zero without writing its document, gbrainwrites a fallback: `{error: "command_failed", code, message, suggestion,exit_code, contract_version: 1}`.+## A write refused `owner_unavailable` with `detail: unbound_source`++On a Postgres brain in classic mode the files in a source's checkout are the+truth, and gbrain only reads them. Do not retry, and do not claim the source or+activate managed mode to get one write through: both change the whole brain and+claiming blocks classic sync. If you can run commands on the brain host, write+`<checkout>/<slug>.md`, commit it, run `gbrain sync --source <id>`, then read the+page back. If you are connected remotely, tell the user: "Your brain is in+classic mode, so I can't save pages directly. Save it as `<slug>.md` in the+`<id>` folder, commit it, and run `gbrain sync --source <id>`." Offer+`persistence.unbound_write database_only` or managed mode only as the user's+choice, with what each costs+([unbound sources](https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#unbound-sources-on-postgres)).+## Marker grammarText output without a terminal uses one block format, built by one modulediff --git a/skills/cron-scheduler/SKILL.md b/skills/cron-scheduler/SKILL.mdindex b54cdcd293..025d92bc91 100644--- a/skills/cron-scheduler/SKILL.md+++ b/skills/cron-scheduler/SKILL.md@@ -104,9 +104,11 @@ sources:no per-source lock, so a run that outlives the interval would overlap thenext tick. A run stopped at its deadline ends `resumable` and the next tickcontinues it. Sources drain one at a time, so `--parallel` does not apply.-- `owner_unavailable` for a source: another host owns it. Install a+- `owner_unavailable` for a source: read its `detail`. `unbound_source` on a+ classic Postgres brain is normal and does not stop classic sync; keep the+ sync line. Any other detail means another host owns the source: install aper-source line on that host (`gbrain sync --source <id> --no-pull- --hard-deadline 13m`, plus its refresh) instead of claiming the source here.+ --hard-deadline 13m`, plus its refresh) instead of claiming it here.- Failed files: run the `--retry-failed` command the failure prints(`gbrain sync --source <id> --no-pull --retry-failed …`) after fixing thefiles; never add `--skip-failed`.diff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.mdindex c6c2e515f5..9303499b44 100644--- a/skills/maintain/SKILL.md+++ b/skills/maintain/SKILL.md@@ -61,6 +61,9 @@ writer coordination refusal, inspect `gbrain sources writer status --brain <id>--json` on the selected host first and report the owner, epoch, enabled state andblocked recovery to the operator. Do not claim a checkout, activate managed mode,transfer an owner, replace identities, or remove ownership markers as a repair.+When the status reads `enabled: false` and the refusal says `unbound_source`,+the brain is in classic mode on purpose: report that writes go through the+checkout (file, commit, `gbrain sync`) and leave it classic.Deliberate administration requires a separately approved topology change and theaction-specific intent plus reviewed state precondition described in`docs/architecture/topologies.md`. Neither a TTY nor `--yes` nordiff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.mdindex b5e815f99f..cb1a976153 100644--- a/skills/setup/SKILL.md+++ b/skills/setup/SKILL.md@@ -92,6 +92,10 @@ harness subscription. This choice does not enable paid APIs or capture.If the user explicitly wants Postgres, follow [engines](https://github.com/garrytan/gbrain/blob/master/docs/ENGINES.md)or [postgres-adopt](../postgres-adopt/SKILL.md). `--prefer-postgres` is optional.+Tell the user once: on Postgres, a source with a checkout starts in classic+mode, where the checkout is the source of truth and agents save pages as+committed files followed by `gbrain sync`; direct saves need managed mode+([unbound sources](https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#unbound-sources-on-postgres)).Supabase uses a database connection string, not an anon key. Keep credentialsprivate and do not copy ambient secrets into file configuration.diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex e9bdf36044..e474260b88 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -40,6 +40,8 @@ export interface ActionInput { name: string; how: string }/** Stored/constructed form. Never carries `next` or `command`: both are computed at render time. */export interface Action {+ /** Escalation only: an action the agent must not take without asking renders `ask_user` whatever else it carries. */+ next?: 'ask_user';argv?: string[];mcp?: McpCall;consent: Effect[];@@ -56,7 +58,7 @@ export interface Action {}/** Wire form: what an agent reads. */-export interface RenderedAction extends Omit<Action, 'then' | 'docs'> {+export interface RenderedAction extends Omit<Action, 'then' | 'docs' | 'next'> {command?: string;next: Next;docs?: string;@@ -225,6 +227,7 @@ function warnInvalidRepoBase(value: string): void {/** The published decision table (first matching row wins). */export function deriveNext(a: Action, ctx: RenderContext): Next {+ if (a.next === 'ask_user') return 'ask_user';const callableMcp = a.mcp !== undefined && ctx.isCallable(a.mcp.tool);const mcpOnlyOnCli = ctx.transport === 'cli' && !a.argv?.length && a.mcp !== undefined && !callableMcp;if (!a.argv?.length && !callableMcp && !mcpOnlyOnCli) return 'report';diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex f6df2a343f..f3854b75c6 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -292,7 +292,7 @@ export const CODES = {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_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; `clone_in_progress`: a topology clone is recovering it; both clear by themselves. `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.",+ 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; `clone_in_progress`: a topology clone is recovering it; both clear by themselves. `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.' },diff --git a/src/core/persistence/unbound-source.ts b/src/core/persistence/unbound-source.tsindex cbbe7ff7f4..7e3791052c 100644--- a/src/core/persistence/unbound-source.ts+++ b/src/core/persistence/unbound-source.ts@@ -44,7 +44,10 @@ export function unboundSourceError(sourceId: string, path: string | null, scope:+ '(if an operator has locked writer administration, ask the operator to unlock it first)';// #6122: on a brain whose managed persistence is not activated, a claim alone fences classic sync of the source,// so the working path is the file plus classic sync; claiming is named with that consequence.- const edit = `edit the page's file in the checkout${path ? ` (${path})` : ''} and run gbrain sync --source ${sourceId}, which imports it`;+ // Classic sync imports commits, not the working tree, so the hint names the commit; a remote caller cannot reach the checkout.+ const edit = path+ ? `write the page as ${path}/<slug>.md (check generated frontmatter with gbrain frontmatter validate --stdin --path <slug>.md), commit it in that checkout, then run gbrain sync --source ${sourceId}`+ : `ask the user to write the page as <slug>.md in the source's checkout on the brain host, commit it, and run gbrain sync --source ${sourceId}`;const trap = `For a gbrain-owned checkout instead (a brain-wide change: ask the user first), ${bind}, then activate managed persistence (preview first: gbrain sources writer activate --confirm-quiesced --dry-run --json). `+ `Managed persistence is not activated on this brain, so a claim without activation blocks classic sync of ${sourceId} until it is activated or the claim is released with gbrain sources writer deactivate.`;const suggestion = classic ? scope === 'database_only_eligible'@@ -59,6 +62,23 @@ export function unboundSourceError(sourceId: string, path: string | null, scope:+ `${UNBOUND_WRITE_KEY}=database_only does not apply: this page came from a canonical file, and a database-only edit would be lost on the owner's next sync.`;const error = new OperationError('owner_unavailable', 'This source has no designated canonical owner.', suggestion, UNBOUND_SOURCE_DOCS);error.detail = 'unbound_source';+ // A configuration state, not a transient one: a retry gets the same refusal, and every way out is the user's choice.+ error.retryable = false;+ error.fix = {+ next: 'ask_user',+ consent: [],+ actor: path ? 'agent' : 'user',+ why: classic+ ? `The brain is in classic mode: the checkout of '${sourceId}' is the source of truth and gbrain only reads it, so a page is saved as a committed file followed by gbrain sync. Don't retry, claim the source or activate managed mode to get one write through.`+ : `Source '${sourceId}' has no canonical owner; binding it or allowing database-only pages is a brain-wide decision for the user.`,+ user_message: classic+ ? path+ ? `Your brain is in classic mode, so pages are saved as files in the checkout. I can write it as <slug>.md in ${path}, commit it and run gbrain sync --source ${sourceId}. Or I can explain the two other options: database-only pages, or managed mode.`+ : `Your brain is in classic mode, so I can't save pages directly. Save it as <slug>.md in the ${sourceId} folder, commit it, and run gbrain sync --source ${sourceId}. Or I can explain the two other options: database-only pages, or managed mode.`+ : `Source '${sourceId}' has no canonical owner, so I can't save this page. You can bind the source on the brain host, or allow database-only pages${scope === 'file_backed' ? ' (not for this page, which came from a file)' : ''}; I can explain what each changes.`,+ docs: UNBOUND_SOURCE_DOCS,+ requires_exclusive: false,+ };return error;}diff --git a/test/unbound-source-hint.test.ts b/test/unbound-source-hint.test.tsnew file mode 100644index 0000000000..b9cc4b1b12--- /dev/null+++ b/test/unbound-source-hint.test.ts@@ -0,0 +1,47 @@+/**+ * #6277: a classic Postgres brain refuses page writes to a filesystem source+ * with `owner_unavailable` / `detail: unbound_source`.+ *+ * Protects the agent contract of that refusal: classic sync imports commits,+ * so the hint must name the commit (an agent following "edit and sync" imports+ * nothing); a remote caller is told to hand the steps to the user; and the+ * envelope is not retryable and asks the user, because the refusal is a+ * configuration state and every way out is a brain-wide decision.+ */+import { describe, expect, test } from 'bun:test';+import { cliRenderContext, toAgentError } from '../src/core/agent-output.ts';+import { unboundSourceError } from '../src/core/persistence/unbound-source.ts';++const cli = (e: unknown) => toAgentError(e, { transport: 'cli', command: 'put', render: cliRenderContext({ routing: undefined }) });+const mcp = (e: unknown) => toAgentError(e, { transport: 'stdio', op: 'put_page', render: { transport: 'stdio', isCallable: () => true, preapproved: () => false } });++describe('unbound_source on a classic Postgres brain (#6277)', () => {+ test('trusted local: write the file, commit it, then classic sync; not retryable; ask the user', () => {+ const env = cli(unboundSourceError('notes', '/abs/notes', 'database_only_eligible', true));+ expect(env.code).toBe('owner_unavailable');+ expect(env.detail).toBe('unbound_source');+ expect(env.suggestion).toContain('/abs/notes/<slug>.md');+ expect(env.suggestion).toContain('commit it in that checkout, then run gbrain sync --source notes');+ expect(env.retryable).toBe(false);+ expect(env.fix?.next).toBe('ask_user');+ expect(env.fix?.user_message).toContain('commit it and run gbrain sync --source notes');+ });++ test('remote: the steps go to the user, with no host path', () => {+ const env = mcp(unboundSourceError('notes', null, 'file_backed', true));+ expect(env.suggestion).toContain('ask the user to write the page as <slug>.md');+ expect(env.suggestion).toContain('commit it, and run gbrain sync --source notes');+ expect(env.suggestion).not.toContain('/abs');+ expect(env.retryable).toBe(false);+ expect(env.fix?.next).toBe('ask_user');+ expect(env.fix?.user_message).toContain("Your brain is in classic mode, so I can't save pages directly.");+ });++ test('managed mode keeps its bind / database_only guidance and is not retryable either', () => {+ const env = cli(unboundSourceError('notes', '/abs/notes', 'database_only_eligible'));+ expect(env.suggestion).toContain('gbrain sources writer claim notes --path /abs/notes');+ expect(env.suggestion).not.toContain('commit it');+ expect(env.retryable).toBe(false);+ expect(env.fix?.next).toBe('ask_user');+ });+});