Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(GBRA-248 W0): review fixes: keyless re-init stays keyless without vectors; indexed, cancellable owner read inside existing budgets; stale owner rides owner_unavailable plus diagnostic.owner only when stale; stop stamp after DELETE with SKIP LOCKED
garrytan0d003bf14250
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 25ced4ee5f..415fcce7d7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,15 +14,15 @@ identifiers and attribution are available in the pre-removal Git revision**A brain moved or restored under a new host identity no longer leaves writes pending forever behind an `--accept-pending` exit 0, and a keyless re-init from a cold `GBRAIN_HOME` no longer switches an embedded brain to keyword-only (GBRA-248 W0).**-A managed source publishes only through the host that owns its checkout. When a brain moved to another machine, was restored from a backup, or ran in a container that restarted with a fresh `GBRAIN_HOME`, the new process got a new host identity, its writes queued for the old owner, and nothing said that owner was gone: the receipt read as an ordinary pending write and `--accept-pending` (or `GBRAIN_ACCEPT_PENDING=1`) exited 0, so hooks and cron treated writes that would never publish as saved. A pending receipt now carries the owner's liveness and last recorded activity, and names `owner_stale` when the owner runs no live consumer and has been quiet for more than 24 hours, or at once on PGLite when this process holds the database file under another identity. `--accept-pending` does not cover an `owner_stale` write: `gbrain put`, `gbrain call`, brainstorm saves and `gbrain trust accept --all` exit 10 and say why. A consumer's clean stop now stamps the worktrees its host owns, so a stopped owner is not mistaken for a gone one. The owner host never sees `owner_stale`, a repo-less (database-only) write never names an owner, and nothing claims or transfers ownership. New doctor check `owner_host_stale` lists the waiting writes with the owner and the read-only next step.+A managed source publishes only through the host that owns its checkout. When a brain moved to another machine, was restored from a backup, or ran in a container that restarted with a fresh `GBRAIN_HOME`, the new process got a new host identity, its writes queued for the old owner, and nothing said that owner was gone: the receipt read as an ordinary pending write and `--accept-pending` (or `GBRAIN_ACCEPT_PENDING=1`) exited 0, so hooks and cron treated writes that would never publish as saved. A pending receipt now names that owner (reason `owner_unavailable` with a new `diagnostic.owner` block, which older clients ignore) when it runs no live consumer and has been quiet for more than 24 hours, or at once on PGLite when this process holds the database file under another identity. `--accept-pending` does not cover such a write: `gbrain put`, `gbrain call`, brainstorm saves and `gbrain trust accept --all` exit 10 and say why. A consumer's clean stop now stamps the worktrees its host owns, so a stopped owner is not mistaken for a gone one. The owner host never sees the block, a repo-less (database-only) write never names an owner, and nothing claims or transfers ownership. New doctor check `owner_host_stale` lists the waiting writes with the owner and the read-only next step.-`gbrain init` with no provider key in reach falls back to keyless. Run from a cold home against a database that already had an embedding model and vectors, it wrote `embedding_disabled: true` into the new config file, and the brain stopped embedding. When that fallback was implicit and the database is not fresh, init now keeps the database's stored model and width in the config file instead and prints the key to set and `gbrain embed --stale`. A fresh keyless install, an explicit `--no-embedding` and a database that already disables embeddings behave as before. New doctor check `embedding_plane_disagreement` finds brains the old behavior left in that state and prints the `gbrain init --force --embedding-model …` enable for the same model.+`gbrain init` with no provider key in reach falls back to keyless. Run from a cold home against a database that already had an embedding model and vectors, it wrote `embedding_disabled: true` into the new config file, and the brain stopped embedding. When that fallback was implicit and the database holds vectors, init now keeps the database's stored model and width in the config file instead and prints the key to set and `gbrain embed --stale`. A fresh keyless install, a keyless brain with no vectors, an explicit `--no-embedding` and a database that already disables embeddings behave as before. New doctor check `embedding_plane_disagreement` finds brains the old behavior left in that state and prints the `gbrain init --force --embedding-model …` enable for the same model.### Itemized changes-- `src/core/persistence/owner-activity.ts` (new): owner liveness, last activity and the stale rule; `journal.ts` attaches it to receipt facts within the 500 ms budget; `health.ts`, `types.ts`, `params.ts`: the `owner_stale` reason and the optional `diagnostic.owner` receipt field.+- `src/core/persistence/owner-activity.ts` (new): owner liveness, last activity and the stale rule; `journal.ts` attaches it to receipt facts inside budgets the reads already have, cancelled past them; `health.ts`, `types.ts`, `params.ts`: the optional `diagnostic.owner` receipt field.- `src/core/persistence/service.ts`: a write left pending carries its owner facts into the receipt.-- `src/core/persistence/write-wait.ts`: `acceptPendingCovers`; `writeErrorExitCode` keeps exit 10 for `owner_stale`; `persistence-delegate.ts`, `brainstorm.ts`, `trust.ts` follow it.+- `src/core/persistence/write-wait.ts`: `acceptPendingCovers`; `writeErrorExitCode` keeps exit 10 when `diagnostic.owner` is present; `persistence-delegate.ts`, `brainstorm.ts`, `trust.ts` follow it.- `src/core/persistence/consumer-heartbeat.ts`: a clean stop stamps `persistence_worktrees.heartbeat_at` for the host's worktrees.- `src/commands/init-embedding-plane.ts` (new), `src/commands/init.ts`: the implicit-keyless marker and the kept database identity on both engines.- Doctor: `owner_host_stale` (`checks/owner-host-stale.ts`) and `embedding_plane_disagreement` (`checks/embedding-plane.ts`); `core/readiness.ts` exports `enableArgv`.diff --git a/docs/architecture/key-files/core-persistence-capacity.md b/docs/architecture/key-files/core-persistence-capacity.mdindex 357ac02301..c69d542002 100644--- a/docs/architecture/key-files/core-persistence-capacity.md+++ b/docs/architecture/key-files/core-persistence-capacity.md@@ -23,4 +23,4 @@ What a managed publish costs in statements and round trips, and how it is measur- `src/core/postgres-engine/pool-stats.ts` — #6317 (C1, G1): `driverPoolStats(sql)` reads the vendored postgres.js driver's `sql.pool` getter (`vendor/postgres`, patch regenerated) for real `{checked_out, max, waiters}`; `enginePoolStats(engine)` labels the source (`driver` or `tracked_subset` from `pool-gauge.ts`). Filled into the heartbeat row, `writer status` running claims and `getPoolDiagnostics()`.- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.- `src/core/persistence/effect-settle.ts` — `gbrain sources writer settle-effects <source> (--request-id|--parked-code) [--unsettle] [--dry-run|--apply --expect <plan_hash>]` (`writer_settle_effects`, an administration extension) (#7423, #7378): records `data.settled` (and appends to `data.settlements`) on a failed Git effect no retry can move, never touching its failure, parked targets, request or bytes. It settles only on an exact-target proof re-checked under row locks at apply: each target declared `db_only` in the current binding's gbrain.yml (`sourceDbOnlyDir`), or, for an effect `guardEffectSource` refuses `source_changed` because the source moved to a new worktree (same incarnation, this host owning the active binding), a later committed and pushed Git effect of the current worktree whose `expected_hash` equals the canonical file now and a blob at the already-fetched `@{upstream}` equal to it (no fetch). Withdrawal effects, claims, open recovery records, revoked writers, replaced sources and unknown targets refuse; an effect of the current binding that is not db_only refuses `retry_instead`. The plan hash is doctor --remediate's `computePlanHash` over the brain, source, selector, owner epoch and each proof (`preview_changed` otherwise). Readers that skip settled rows: doctor `parked_effects`, `rearmWithheldTargets`, `readParkedGroups`, `readGitPushHolds`, `retryParkedPushes`/`--parked-code`, `retryIndexLockParks`, `sync status`, `failedEffectHistory`; `retryParkedEffects` reports a settled effect as `action: settled`. `retryParkedPushes` also reaches a push that failed without parked targets (#7378, `failedCodes`). Tests: `test/persistence-effect-settle.test.ts` (scenarios in `test/helpers/effect-settle-scenarios.ts`) + the Postgres arm in `test/e2e/w5-persistence-postgres.test.ts`.-- `src/core/persistence/owner-activity.ts` — GBRA-248: `ownerActivity(engine, worktreeIds)` reads each worktree owner's liveness (a `persistence_consumers` row renewed within the lapse window) and last activity (the greatest of the worktree heartbeat, which a consumer's clean stop stamps, its newest consumer renewal and the newest committed publication). `stale` is true when the owner is not this host and not live, and either this process holds a PGLite file under another identity or the owner has been quiet past `OWNER_STALE_MS` (24 h; with no activity recorded, the oldest open request's age decides). The journal attaches it to receipt facts within the 500 ms budget (`boundedOwnerActivity`), `writeHealth` maps it to `owner_stale` with `diagnostic.owner`, and `acceptPendingCovers` in write-wait.ts keeps such a write at exit 10 under `--accept-pending`. Read-only; null activity authorizes nothing.+- `src/core/persistence/owner-activity.ts` — GBRA-248: `ownerActivity(engine, worktreeIds)` reads each worktree owner's liveness (a `persistence_consumers` row renewed within the lapse window) and last activity (the greatest of the worktree heartbeat, which a consumer's clean stop stamps, its newest consumer renewal and the newest committed receipt, read through the foreground-committed and sync-watermark indexes). `stale` is true when the owner is not this host and not live, and either this process holds a PGLite file under another identity or the owner has been quiet past `OWNER_STALE_MS` (24 h; with no activity recorded, the oldest open request's age decides). `startOwnerRead` runs it inside a budget the caller already has (the journal's 500 ms receipt read, the last 500 ms of `awaitWrite`'s wait) and cancels it past that; `writeHealth` maps a stale owner to `owner_unavailable` with a `diagnostic.owner` block, present only then, and `acceptPendingCovers` in write-wait.ts keeps such a write at exit 10 under `--accept-pending`. Read-only; null activity authorizes nothing.diff --git a/docs/guides/exit-codes.md b/docs/guides/exit-codes.mdindex 7405203d07..7c4691eb9a 100644--- a/docs/guides/exit-codes.md+++ b/docs/guides/exit-codes.md@@ -14,7 +14,7 @@ the exit code first, then reads the JSON document (`--json`) for the details:| 1 | failed | error envelope with `class` and `retryable` | follow `fix.next`; retry only when `retryable` is true || 2 | usage error or invalid input | error envelope (`invalid_params`, `unknown_flag`) | correct the command; `gbrain <command> --help` || 3 | `confirmation_required`: nothing ran | consent payload (`effects`, `user_message`, `fix`) | stop, relay `user_message` to the user, run `fix.command` only after they agree |-| 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0, except an `owner_stale` receipt ([owner_stale](troubleshooting.md#owner-host-stale)) |+| 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0, except a receipt whose `diagnostic.owner` names a stale owner ([stale owner](troubleshooting.md#owner-host-stale)) || 11 | partial, resumable budget stop | result with `remaining_*` and `resume_command` | run `resume_command` (it is safe to re-run) || 12 | `no_results`: `gbrain recall` (an entity, text, `--grep`, `--question` or `--query` lookup) or `gbrain entity` matched nothing. Opt-in: only with `GBRAIN_FAIL_ON_EMPTY=1`; otherwise a miss exits 0 | recall's list output: `status: "no_results"`; entity: `found: false` | treat it as a miss, not a failure; a script that filters stdout can branch on it || 13 | `pending_verify`: `gbrain bootstrap harness --token` wired a PGLite brain while no serve answered; nothing failed, nothing verified yet | the harness result with `status: "pending_verify"` and `fix` | tell the user to start `gbrain serve --http`, then run `fix.command` with the same token; `bootstrap harness --status` stays partial until it passes ([pending verify](bootstrap.md#pending-verify)) |diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex df515fdee6..cc99de20b7 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -61,7 +61,7 @@| [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | 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 | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok || [Doctor fails `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | `gbrain upgrade --restart-only` restarts every listed process onto the installed build and verifies one build runs; it refuses with the exact step for a process it cannot restart (the check also prints the manual restart) | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok || [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` |-| [A write stays pending with `owner_stale`, `--accept-pending` exits 10, or doctor warns `owner_host_stale`](#owner-host-stale) | run gbrain with the owner's `GBRAIN_HOME` (or bring the owner host back); the waiting writes are kept | brain host, after the user agrees | none | `gbrain doctor --only owner_host_stale --json` |+| [A pending write names a stale owner (`diagnostic.owner`), `--accept-pending` exits 10, or doctor warns `owner_host_stale`](#owner-host-stale) | run gbrain with the owner's `GBRAIN_HOME` (or bring the owner host back); the waiting writes are kept | brain host, after the user agrees | none | `gbrain doctor --only owner_host_stale --json` || [Doctor warns `embedding_plane_disagreement`: the config file disables embeddings over a database with vectors](#embedding-plane-disagreement) | with the provider key set, run the `gbrain init --force --embedding-model …` the check prints (same model and width) | user (key), then agent | `credentials`, `paid` | `gbrain doctor --only embedding_plane_disagreement --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` |@@ -189,7 +189,7 @@ A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation see<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.-<a id="owner-host-stale"></a>**A write stays pending with reason `owner_stale`, `--accept-pending` still exits 10, or doctor warns `owner_host_stale`?** A managed source publishes only through the host that owns its checkout, named by its `host.json` identity. When a brain is moved or restored onto another machine, or a container restarts with a new `GBRAIN_HOME`, the new process gets a new identity and its writes queue for the old owner, which may never return. The receipt names that case: `diagnostic.reason` is `owner_stale` and `diagnostic.owner` carries the owner host id and its last recorded activity (its newest consumer heartbeat, its newest publication, or the time its consumer last stopped cleanly). It applies when the owner runs no live consumer and has been quiet for more than 24 hours, or at once on PGLite when this process holds the database file under a different identity; the owner host itself never sees it. `--accept-pending` and `GBRAIN_ACCEPT_PENDING=1` cover a write that will commit on its own, so an `owner_stale` write exits 10 with them, and the CLI says so. Nothing is lost: the writes stay queued with their request ids. Run `gbrain sources writer status --json` (read-only) to see the binding owner. Bring the owner host back, or run this process with the owner's `GBRAIN_HOME` (the parent of its `.gbrain` directory) and restart it. For servers and containers, keep `GBRAIN_HOME` on a persistent volume that is stable across restarts, or use sources with no checkout root, whose writes any consumer publishes. Never edit, copy or delete a `host.json`, and nothing claims or transfers ownership automatically. Verify with `gbrain doctor --only owner_host_stale --json`; [`host_identity_mismatch`](#host-identity-mismatch) covers an owner whose checkout this filesystem holds.+<a id="owner-host-stale"></a>**A pending write names a stale owner in `diagnostic.owner`, `--accept-pending` still exits 10, or doctor warns `owner_host_stale`?** A managed source publishes only through the host that owns its checkout, named by its `host.json` identity. When a brain is moved or restored onto another machine, or a container restarts with a new `GBRAIN_HOME`, the new process gets a new identity and its writes queue for the old owner, which may never return. The receipt names that case: `diagnostic.reason` is `owner_unavailable` and a `diagnostic.owner` block, present only then, carries the owner host id and its last recorded activity (its newest consumer heartbeat, its newest publication, or the time its consumer last stopped cleanly). It applies when the owner runs no live consumer and has been quiet for more than 24 hours, or at once on PGLite when this process holds the database file under a different identity; the owner host itself never sees it. `--accept-pending` and `GBRAIN_ACCEPT_PENDING=1` cover a write that will commit on its own, so a write with a `diagnostic.owner` block exits 10 with them, and the CLI says so. Nothing is lost: the writes stay queued with their request ids. Run `gbrain sources writer status --json` (read-only) to see the binding owner. Bring the owner host back, or run this process with the owner's `GBRAIN_HOME` (the parent of its `.gbrain` directory) and restart it. For servers and containers, keep `GBRAIN_HOME` on a persistent volume that is stable across restarts, or use sources with no checkout root, whose writes any consumer publishes. Never edit, copy or delete a `host.json`, and nothing claims or transfers ownership automatically. Verify with `gbrain doctor --only owner_host_stale --json`; [`host_identity_mismatch`](#host-identity-mismatch) covers an owner whose checkout this filesystem holds.<a id="managed-sync-wedge-transcript"></a>**What the agent sees while a catch-up is wedged, step by step.** The brain is `default`, the owner is a `gbrain serve` with pid 4121, the sync CLI runs beside it, and the head write of a 16-member bulk group has been `preparing` with nothing in flight at the database. Output is abbreviated to the fields that decide the next step.@@ -408,7 +408,7 @@ records completion and leaves every page as it was.<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*-<a id="embedding-plane-disagreement"></a>**Doctor warns `embedding_plane_disagreement`, or a brain that had semantic search went keyword-only after a re-setup?** The config file says `embedding_disabled: true`, but the database does not disable embeddings and already holds vectors. A re-init from a new `GBRAIN_HOME` or a restarted container with no provider key in reach used to write that flag. Init now keeps the database's model and width in that case and prints the key to set; a fresh keyless install and an explicit `--no-embedding` still write the flag. The check prints the model and width the vectors use and the enable command for exactly that model (`gbrain init --force --embedding-model <model> --embedding-dimensions <N>`, with `--path` on PGLite; effects `credentials` and `paid`). Set the provider key, run it after the user agrees, then `gbrain embed --stale` embeds pages written meanwhile. Pages and vectors are kept. When the stored model is unrecorded, the check points at `gbrain migrate embeddings --status` first. Verify with `gbrain doctor --only embedding_plane_disagreement --json`.+<a id="embedding-plane-disagreement"></a>**Doctor warns `embedding_plane_disagreement`, or a brain that had semantic search went keyword-only after a re-setup?** The config file says `embedding_disabled: true`, but the database does not disable embeddings and already holds vectors. A re-init from a new `GBRAIN_HOME` or a restarted container with no provider key in reach used to write that flag. Init now keeps the database's model and width when it holds vectors and prints the key to set; a fresh keyless install, a keyless brain with no vectors and an explicit `--no-embedding` still write the flag. The check prints the model and width the vectors use and the enable command for exactly that model (`gbrain init --force --embedding-model <model> --embedding-dimensions <N>`, with `--path` on PGLite; effects `credentials` and `paid`). Set the provider key, run it after the user agrees, then `gbrain embed --stale` embeds pages written meanwhile. Pages and vectors are kept. When the stored model is unrecorded, the check points at `gbrain migrate embeddings --status` first. Verify with `gbrain doctor --only embedding_plane_disagreement --json`.<a id="embedding-identity-unqualified"></a>**`facts-absorb` dies with `embedding_configuration` ("records its embedding model without a provider") while `gbrain config get embedding_model` shows a valid `provider:model`, or doctor `embedding_identity_unqualified` warns?** The brain's database `config` row `embedding_model` holds a bare model name from an older install (for example `text-embedding-3-small`), and managed fact extraction reads only that row. `gbrain config set` cannot change it. The doctor check prints the preview with the configured model filled in: run `gbrain migrate embeddings --to <provider:model> --dry-run` (read-only), show the user the cost, and only after they approve run it without `--dry-run`, with `--yes --max-cost-usd <cap>`. It re-embeds active facts even when the model is unchanged, so it is a paid step. When no model is configured outside the database, the check asks for the provider-qualified id instead. **Say to your agent:** *"Why did facts extraction stop with an embedding configuration error?"*diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 191e96deb4..11a8e48034 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -140,7 +140,7 @@ a receipt can report has a row here.| `sync_cursor_replaced` | `sync_cursor_replaced` | A managed sync checkpoint found that another sync run of the same source (a rediscovery, a newer sync) replaced the cursor it belongs to, so it had nothing left to publish. The receipt is a conflict; no managed-sync failure is recorded for it, and the run that awaited it goes on with the cursor that now covers the source. | Nothing: let the current sync finish. `gbrain sync status --source <id> --json` shows that cursor. A same-run index lag keeps reporting `revision_conflict`. || <a id="revision-backfill"></a>`revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. `gbrain doctor` reports the backfill as `revision_backfill` with the pending count and any failed rows by page. | Resume the backfill on the brain host with `gbrain apply-migrations --force-schema` (it prints its progress; `--yes` alone does not resume it once the schema is current). Rows that used all three attempts are no longer retried: run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). || `idempotency_conflict` | `idempotency_conflict` | The `request_id` was already used for a different target, content or protocol. | Use a new `request_id` for a different write; reuse an ID only to replay the same write. |-| <a id="write_pending"></a>`write_pending` | `write_pending` (CLI exit 10) | The write was accepted but has not committed yet. It keeps its request ID and may still commit. The CLI exits 10, not 1; a lost acknowledgment with no receipt is `submission_status: "unknown"` and exits 1. See [CLI exit status for writes](../protocol/MEMORY_VERBS_v1.md#cli-exit-status-for-writes). | Poll `gbrain call get_write_request '{"request_id":"<id>"}'`, or repeat the same command with the same `--request-id` and a longer `--wait <seconds>`. Scripts that only need the write admitted pass `--accept-pending` (or `GBRAIN_ACCEPT_PENDING=1`) to exit 0, except for a receipt whose `diagnostic.reason` is `owner_stale`, which still exits 10 ([owner_stale](troubleshooting.md#owner-host-stale)). |+| <a id="write_pending"></a>`write_pending` | `write_pending` (CLI exit 10) | The write was accepted but has not committed yet. It keeps its request ID and may still commit. The CLI exits 10, not 1; a lost acknowledgment with no receipt is `submission_status: "unknown"` and exits 1. See [CLI exit status for writes](../protocol/MEMORY_VERBS_v1.md#cli-exit-status-for-writes). | Poll `gbrain call get_write_request '{"request_id":"<id>"}'`, or repeat the same command with the same `--request-id` and a longer `--wait <seconds>`. Scripts that only need the write admitted pass `--accept-pending` (or `GBRAIN_ACCEPT_PENDING=1`) to exit 0, except for a receipt whose `diagnostic.owner` names a stale owner, which still exits 10 ([stale owner](troubleshooting.md#owner-host-stale)). || <a id="invalid_write_wait"></a>`invalid_write_wait` | `invalid_write_wait` | `GBRAIN_WRITE_WAIT_MS` or `persistence.write_wait_ms` is not a whole number of milliseconds from 0 to 600000. Nothing was written. | `unset GBRAIN_WRITE_WAIT_MS` (or set it to e.g. `30000`), or `gbrain config set persistence.write_wait_ms 30000`. || <a id="edit_page"></a>`edit_no_match`, `edit_ambiguous_match`, `edit_protected_span`, `edit_invalid` | same | An `edit_page` edit matched nothing, matched more than once, touched a protected takes/facts section, or was malformed. `detail` names `edit_index` (and `match_count`). Nothing was admitted. | Re-read `get_page include_content:true`, fix the named edit and resend with a **new** request ID. See [partial page edits](../protocol/MEMORY_VERBS_v1.md#partial-page-edits-edit_page). || <a id="file_database_drift"></a>`file_database_drift` | `file_database_drift` (also the `detail` of a `source_changed` refusal) | A page's checkout file and its database copy differ, so the writer left both as they were instead of replacing one with the other (#6982). The page is held, the run reports it (`details.file_holds`, a `FACTS_FENCE_FAILED` or connector hold) and the rest of the batch continues. Nothing was overwritten. | If the file holds the newer edit, `gbrain sync --source <id>` imports it; if the database copy is newer, re-save the page with write-through on (`gbrain get <slug>`, then `gbrain put <slug>`). When both changed, ask the user which version to keep. |diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 3b8b645b36..c6d5ec078b 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -817,7 +817,7 @@ lock".| Exit | Meaning || --- | --- || 0 | Committed (or pending with `--accept-pending`). |-| 10 | Accepted, still pending; the receipt names the request. Also with `--accept-pending` when the receipt's `diagnostic.reason` is `owner_stale`: the owner host runs no consumer and has been quiet past the stale window, so the write will not commit on its own ([owner_stale](../guides/troubleshooting.md#owner-host-stale)). |+| 10 | Accepted, still pending; the receipt names the request. Also with `--accept-pending` when the receipt carries `diagnostic.owner` (reason `owner_unavailable`): the owner host runs no consumer and has been quiet past the stale window, so the write will not commit on its own ([stale owner](../guides/troubleshooting.md#owner-host-stale)). || 1 | Not committed: a terminal failure (`conflict`, `failed`, `cancelled`), a refusal before admission (for example "the persistence owner is closing", even with `--accept-pending`), or a lost response whose submission state is unknown (`submission_status: "unknown"`, no receipt). |The verdict keys on an admitted, non-terminal receipt, never on an error codediff --git a/llms-full.txt b/llms-full.txtindex 2e30f73868..408b63b4eb 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9061,7 +9061,7 @@ lock".| Exit | Meaning || --- | --- || 0 | Committed (or pending with `--accept-pending`). |-| 10 | Accepted, still pending; the receipt names the request. Also with `--accept-pending` when the receipt's `diagnostic.reason` is `owner_stale`: the owner host runs no consumer and has been quiet past the stale window, so the write will not commit on its own ([owner_stale](../guides/troubleshooting.md#owner-host-stale)). |+| 10 | Accepted, still pending; the receipt names the request. Also with `--accept-pending` when the receipt carries `diagnostic.owner` (reason `owner_unavailable`): the owner host runs no consumer and has been quiet past the stale window, so the write will not commit on its own ([stale owner](../guides/troubleshooting.md#owner-host-stale)). || 1 | Not committed: a terminal failure (`conflict`, `failed`, `cancelled`), a refusal before admission (for example "the persistence owner is closing", even with `--accept-pending`), or a lost response whose submission state is unknown (`submission_status: "unknown"`, no receipt). |The verdict keys on an admitted, non-terminal receipt, never on an error code@@ -9952,7 +9952,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | 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 | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok || [Doctor fails `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | `gbrain upgrade --restart-only` restarts every listed process onto the installed build and verifies one build runs; it refuses with the exact step for a process it cannot restart (the check also prints the manual restart) | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok || [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` |-| [A write stays pending with `owner_stale`, `--accept-pending` exits 10, or doctor warns `owner_host_stale`](#owner-host-stale) | run gbrain with the owner's `GBRAIN_HOME` (or bring the owner host back); the waiting writes are kept | brain host, after the user agrees | none | `gbrain doctor --only owner_host_stale --json` |+| [A pending write names a stale owner (`diagnostic.owner`), `--accept-pending` exits 10, or doctor warns `owner_host_stale`](#owner-host-stale) | run gbrain with the owner's `GBRAIN_HOME` (or bring the owner host back); the waiting writes are kept | brain host, after the user agrees | none | `gbrain doctor --only owner_host_stale --json` || [Doctor warns `embedding_plane_disagreement`: the config file disables embeddings over a database with vectors](#embedding-plane-disagreement) | with the provider key set, run the `gbrain init --force --embedding-model …` the check prints (same model and width) | user (key), then agent | `credentials`, `paid` | `gbrain doctor --only embedding_plane_disagreement --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` |@@ -10080,7 +10080,7 @@ A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation see<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.-<a id="owner-host-stale"></a>**A write stays pending with reason `owner_stale`, `--accept-pending` still exits 10, or doctor warns `owner_host_stale`?** A managed source publishes only through the host that owns its checkout, named by its `host.json` identity. When a brain is moved or restored onto another machine, or a container restarts with a new `GBRAIN_HOME`, the new process gets a new identity and its writes queue for the old owner, which may never return. The receipt names that case: `diagnostic.reason` is `owner_stale` and `diagnostic.owner` carries the owner host id and its last recorded activity (its newest consumer heartbeat, its newest publication, or the time its consumer last stopped cleanly). It applies when the owner runs no live consumer and has been quiet for more than 24 hours, or at once on PGLite when this process holds the database file under a different identity; the owner host itself never sees it. `--accept-pending` and `GBRAIN_ACCEPT_PENDING=1` cover a write that will commit on its own, so an `owner_stale` write exits 10 with them, and the CLI says so. Nothing is lost: the writes stay queued with their request ids. Run `gbrain sources writer status --json` (read-only) to see the binding owner. Bring the owner host back, or run this process with the owner's `GBRAIN_HOME` (the parent of its `.gbrain` directory) and restart it. For servers and containers, keep `GBRAIN_HOME` on a persistent volume that is stable across restarts, or use sources with no checkout root, whose writes any consumer publishes. Never edit, copy or delete a `host.json`, and nothing claims or transfers ownership automatically. Verify with `gbrain doctor --only owner_host_stale --json`; [`host_identity_mismatch`](#host-identity-mismatch) covers an owner whose checkout this filesystem holds.+<a id="owner-host-stale"></a>**A pending write names a stale owner in `diagnostic.owner`, `--accept-pending` still exits 10, or doctor warns `owner_host_stale`?** A managed source publishes only through the host that owns its checkout, named by its `host.json` identity. When a brain is moved or restored onto another machine, or a container restarts with a new `GBRAIN_HOME`, the new process gets a new identity and its writes queue for the old owner, which may never return. The receipt names that case: `diagnostic.reason` is `owner_unavailable` and a `diagnostic.owner` block, present only then, carries the owner host id and its last recorded activity (its newest consumer heartbeat, its newest publication, or the time its consumer last stopped cleanly). It applies when the owner runs no live consumer and has been quiet for more than 24 hours, or at once on PGLite when this process holds the database file under a different identity; the owner host itself never sees it. `--accept-pending` and `GBRAIN_ACCEPT_PENDING=1` cover a write that will commit on its own, so a write with a `diagnostic.owner` block exits 10 with them, and the CLI says so. Nothing is lost: the writes stay queued with their request ids. Run `gbrain sources writer status --json` (read-only) to see the binding owner. Bring the owner host back, or run this process with the owner's `GBRAIN_HOME` (the parent of its `.gbrain` directory) and restart it. For servers and containers, keep `GBRAIN_HOME` on a persistent volume that is stable across restarts, or use sources with no checkout root, whose writes any consumer publishes. Never edit, copy or delete a `host.json`, and nothing claims or transfers ownership automatically. Verify with `gbrain doctor --only owner_host_stale --json`; [`host_identity_mismatch`](#host-identity-mismatch) covers an owner whose checkout this filesystem holds.<a id="managed-sync-wedge-transcript"></a>**What the agent sees while a catch-up is wedged, step by step.** The brain is `default`, the owner is a `gbrain serve` with pid 4121, the sync CLI runs beside it, and the head write of a 16-member bulk group has been `preparing` with nothing in flight at the database. Output is abbreviated to the fields that decide the next step.@@ -10299,7 +10299,7 @@ records completion and leaves every page as it was.<a id="maintenance-write-drift"></a>**Writes to the same pages keep refusing `source_changed` with `file_database_drift`, or doctor `maintenance_write_drift` warns?** Each of those pages has a canonical file that differs from its database copy, usually from an edit outside a coordinated write, so every coordinated write to it refuses and leaves a conflict receipt. Maintenance now checks the file first: `synthesize_concepts` skips a drifted concept before any model call (the phase warns and names the commands below) and other maintenance writes refuse before admission, so the pile stops growing. To list the pages, run `gbrain sources reconcile <id> --brain host --audit --conflicts` (read-only; receipts per slug, whether the file still differs, its drift class and producer; MCP `list_write_conflicts` gives remote readers the database-derived part). Then preview `gbrain repair file-drift --source <id> --all-drifted --prefer file` (add `--class <name>` when the preview reports mixed classes, narrow it with `--only '<path glob>'` / `--skip '<path glob>'` over the canonical file paths, or pick pages with `--slug`), show the user the per-page `exceptions`, and after they agree run the printed `--apply --expect <hash>` command exactly as printed. For derived pages under one directory, such as regenerated concepts: (6) preview `gbrain repair file-drift --source default --all-drifted --only 'concepts/**' --prefer database`, show the user the count and the exceptions, and after they agree run the apply command it prints, which applies exactly the previewed pages. To keep resolving such a directory with the database copy from now on, the user can declare it under `storage:` `keep_db:` in the source's gbrain.yml; the owner host's serve, jobs or autopilot consumer then reconciles drifted pages there at most 10 every 10 minutes, and doctor echoes the policy with its matched count and receipt cost ([keep_db](repair.md#file-drift-keep-db)). `--keep` is refused here: use `--prefer database` or `--prefer file`. See [file drift](repair.md#file-drift). **Say to your agent:** *"Which pages keep refusing source_changed? Preview resolving them and show me before you apply."*-<a id="embedding-plane-disagreement"></a>**Doctor warns `embedding_plane_disagreement`, or a brain that had semantic search went keyword-only after a re-setup?** The config file says `embedding_disabled: true`, but the database does not disable embeddings and already holds vectors. A re-init from a new `GBRAIN_HOME` or a restarted container with no provider key in reach used to write that flag. Init now keeps the database's model and width in that case and prints the key to set; a fresh keyless install and an explicit `--no-embedding` still write the flag. The check prints the model and width the vectors use and the enable command for exactly that model (`gbrain init --force --embedding-model <model> --embedding-dimensions <N>`, with `--path` on PGLite; effects `credentials` and `paid`). Set the provider key, run it after the user agrees, then `gbrain embed --stale` embeds pages written meanwhile. Pages and vectors are kept. When the stored model is unrecorded, the check points at `gbrain migrate embeddings --status` first. Verify with `gbrain doctor --only embedding_plane_disagreement --json`.+<a id="embedding-plane-disagreement"></a>**Doctor warns `embedding_plane_disagreement`, or a brain that had semantic search went keyword-only after a re-setup?** The config file says `embedding_disabled: true`, but the database does not disable embeddings and already holds vectors. A re-init from a new `GBRAIN_HOME` or a restarted container with no provider key in reach used to write that flag. Init now keeps the database's model and width when it holds vectors and prints the key to set; a fresh keyless install, a keyless brain with no vectors and an explicit `--no-embedding` still write the flag. The check prints the model and width the vectors use and the enable command for exactly that model (`gbrain init --force --embedding-model <model> --embedding-dimensions <N>`, with `--path` on PGLite; effects `credentials` and `paid`). Set the provider key, run it after the user agrees, then `gbrain embed --stale` embeds pages written meanwhile. Pages and vectors are kept. When the stored model is unrecorded, the check points at `gbrain migrate embeddings --status` first. Verify with `gbrain doctor --only embedding_plane_disagreement --json`.<a id="embedding-identity-unqualified"></a>**`facts-absorb` dies with `embedding_configuration` ("records its embedding model without a provider") while `gbrain config get embedding_model` shows a valid `provider:model`, or doctor `embedding_identity_unqualified` warns?** The brain's database `config` row `embedding_model` holds a bare model name from an older install (for example `text-embedding-3-small`), and managed fact extraction reads only that row. `gbrain config set` cannot change it. The doctor check prints the preview with the configured model filled in: run `gbrain migrate embeddings --to <provider:model> --dry-run` (read-only), show the user the cost, and only after they approve run it without `--dry-run`, with `--yes --max-cost-usd <cap>`. It re-embeds active facts even when the model is unchanged, so it is a paid step. When no model is configured outside the database, the check asks for the provider-qualified id instead. **Say to your agent:** *"Why did facts extraction stop with an embedding configuration error?"*@@ -10806,7 +10806,7 @@ the exit code first, then reads the JSON document (`--json`) for the details:| 1 | failed | error envelope with `class` and `retryable` | follow `fix.next`; retry only when `retryable` is true || 2 | usage error or invalid input | error envelope (`invalid_params`, `unknown_flag`) | correct the command; `gbrain <command> --help` || 3 | `confirmation_required`: nothing ran | consent payload (`effects`, `user_message`, `fix`) | stop, relay `user_message` to the user, run `fix.command` only after they agree |-| 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0, except an `owner_stale` receipt ([owner_stale](troubleshooting.md#owner-host-stale)) |+| 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0, except a receipt whose `diagnostic.owner` names a stale owner ([stale owner](troubleshooting.md#owner-host-stale)) || 11 | partial, resumable budget stop | result with `remaining_*` and `resume_command` | run `resume_command` (it is safe to re-run) || 12 | `no_results`: `gbrain recall` (an entity, text, `--grep`, `--question` or `--query` lookup) or `gbrain entity` matched nothing. Opt-in: only with `GBRAIN_FAIL_ON_EMPTY=1`; otherwise a miss exits 0 | recall's list output: `status: "no_results"`; entity: `found: false` | treat it as a miss, not a failure; a script that filters stdout can branch on it || 13 | `pending_verify`: `gbrain bootstrap harness --token` wired a PGLite brain while no serve answered; nothing failed, nothing verified yet | the harness result with `status: "pending_verify"` and `fix` | tell the user to start `gbrain serve --http`, then run `fix.command` with the same token; `bootstrap harness --status` stays partial until it passes ([pending verify](bootstrap.md#pending-verify)) |diff --git a/src/commands/doctor/checks/owner-host-stale.ts b/src/commands/doctor/checks/owner-host-stale.tsindex b8e3a5ff83..c045e0ef1d 100644--- a/src/commands/doctor/checks/owner-host-stale.ts+++ b/src/commands/doctor/checks/owner-host-stale.ts@@ -24,7 +24,7 @@ export async function ownerHostStaleCheck(engine: BrainEngine, now = Date.now())(SELECT array_agg(b.source_id ORDER BY b.source_id) FROM persistence_source_bindings b WHERE b.worktree_id=r.worktree_id) AS source_idsFROM persistence_requests r WHERE r.worktree_id IS NOT NULL AND r.state IN ('queued','running','recovering')GROUP BY r.worktree_id`);- const owners = await ownerActivity(engine, open.map(row => row.worktree_id), now);+ const owners = await ownerActivity(engine, open.map(row => row.worktree_id), { now });const stale = open.flatMap(row => {const owner = owners.get(row.worktree_id);return owner?.stale ? [{ worktree_id: row.worktree_id, source_ids: row.source_ids ?? [], owner_host_id: owner.owner_host_id, last_active: owner.last_active,diff --git a/src/commands/init-embedding-plane.ts b/src/commands/init-embedding-plane.tsindex 3a1c9396fc..cbe2834c78 100644--- a/src/commands/init-embedding-plane.ts+++ b/src/commands/init-embedding-plane.ts@@ -3,18 +3,16 @@* key was in reach (a cold GBRAIN_HOME, a container restarted without its* key) must not write embedding_disabled over a content database that already* carries an embedding identity. It keeps the database's model and width in- * the file plane instead and says which key to set. A fresh database, an- * explicit --no-embedding and a database already keyless by choice behave as- * before.+ * the file plane instead and says which key to set. Only stored vectors make+ * the identity worth keeping: a database with none (a fresh one, or a keyless+ * brain whose config row holds only the new-install default) still gets+ * embedding_disabled, as does an explicit --no-embedding.*/import type { BrainEngine } from '../core/engine.ts';import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from '../core/stored-embedding-identity.ts';import { resolveRecipe } from '../core/ai/model-resolver.ts';import type { ResolvedAIOptions } from './init.ts';-/** The embedding identity src/schema.sql seeds into every new config table; it names no choice anyone made. */-const SCHEMA_SEED_IDENTITY = { model: 'text-embedding-3-large', dimensions: 1536 };-/** What the file plane keeps: the database's identity, or nothing (no embedding_disabled) when it holds vectors whose identity cannot be confirmed. */export interface KeptEmbedding { model?: string; dimensions?: number }@@ -26,9 +24,8 @@ export async function keptEmbeddingIdentity(engine: BrainEngine, aiOpts: Resolveconst [row] = await engine.executeRaw<{ present: boolean }>(`SELECT EXISTS (SELECT 1 FROM ${table} WHERE embedding IS NOT NULL) AS present`);if (row?.present) { embedded = true; break; }}+ if (!embedded) return null;const stored = await readStoredEmbeddingIdentity(engine).catch(() => null);- const seeded = !stored?.model || (stored.model === SCHEMA_SEED_IDENTITY.model && stored.dimensions === SCHEMA_SEED_IDENTITY.dimensions);- if (!embedded && seeded) return null;const configured = Number(await engine.getConfig('embedding_dimensions').catch(() => null) ?? NaN);const agrees = stored?.model && (!Number.isFinite(configured) || configured === stored.dimensions);return agrees ? { model: stored!.model!, dimensions: stored!.dimensions } : {};diff --git a/src/commands/persistence-delegate.ts b/src/commands/persistence-delegate.tsindex 6834bbaf10..c812a41769 100644--- a/src/commands/persistence-delegate.ts+++ b/src/commands/persistence-delegate.ts@@ -45,7 +45,7 @@ export async function reportPersistenceCliError(error: unknown, json = false,if (pending) {console.error(`Poll: ${poll}`);if (!acceptPending) console.error(`Exit ${PENDING_WRITE_EXIT_CODE}: accepted, not yet committed. Wait longer with --wait <seconds>, or pass --accept-pending to exit 0 (${WRITE_EXIT_DOCS}).`);- else if (!acceptPendingCovers(pending)) console.error(`Exit ${PENDING_WRITE_EXIT_CODE}: accepted, but queued for an owner host that runs no consumer and has been quiet past the stale window (owner_stale); --accept-pending does not cover it. Run gbrain doctor --only owner_host_stale --json (${WRITE_EXIT_DOCS}).`);+ else if (!acceptPendingCovers(pending)) console.error(`Exit ${PENDING_WRITE_EXIT_CODE}: accepted, but queued for an owner host that runs no consumer and has been quiet past the stale window (the receipt's diagnostic.owner); --accept-pending does not cover it. Run gbrain doctor --only owner_host_stale --json (${WRITE_EXIT_DOCS}).`);}setCliExitVerdict(writeErrorExitCode(error, acceptPending));return true;diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.tsindex 2954f919f1..69e214be9f 100644--- a/src/core/persistence/consumer-heartbeat.ts+++ b/src/core/persistence/consumer-heartbeat.ts@@ -283,12 +283,14 @@ export function startConsumerHeartbeat(engine: DirectEngine, hostId: string, optclearInterval(cadence);await inFlight;const cancel = new AbortController();- // GBRA-248: the worktrees this host owns keep the time it stopped, so owner-activity.ts can tell a stopped owner from one long gone.- const stamp = new AbortController();- try { await bounded(execute('UPDATE persistence_worktrees SET heartbeat_at=now() WHERE owner_host_id=$1::uuid', [hostId], stamp.signal), stamp, 1_000); }- catch { /* best effort: owner activity falls back to publications and the last renewal */ }try { await bounded(execute('DELETE FROM persistence_consumers WHERE host_id=$1::uuid AND pid=$2::integer AND nonce=$3', [hostId, self.pid, self.nonce], cancel.signal), cancel, 1_000); }catch { /* the row lapses on its own; the next renewal on this host purges it */ }+ // GBRA-248: the worktrees this host owns keep the time it stopped, so owner-activity.ts can tell a stopped owner from one long gone.+ // Rows another transaction holds (a transfer) are skipped, in id order, so the stamp neither waits nor deadlocks.+ const stamp = new AbortController();+ try { await bounded(execute(`UPDATE persistence_worktrees SET heartbeat_at=now() WHERE id IN+ (SELECT id FROM persistence_worktrees WHERE owner_host_id=$1::uuid ORDER BY id FOR UPDATE SKIP LOCKED)`, [hostId], stamp.signal), stamp, 1_000); }+ catch { /* best effort: owner activity falls back to receipts and the last renewal */ }},};}diff --git a/src/core/persistence/health.ts b/src/core/persistence/health.tsindex 390c9a7858..1025e23ff7 100644--- a/src/core/persistence/health.ts+++ b/src/core/persistence/health.ts@@ -21,13 +21,13 @@ export function writeHealth(row: { state: WriteRequestState; created_at: Date |const raw = row.blocked_reason;const unexpected = raw === 'unexpected_file_bytes' || raw === 'unexpected_staging_bytes';let reason: WriteDiagnostic['reason'] = unexpected || facts.inspect_owner || facts.recovery_required || row.state === 'recovering'- ? 'recovery_required' : facts.owner_unavailable ? 'owner_unavailable' : facts.owner?.stale ? 'owner_stale' : facts.earlier_write ? 'waiting_on_earlier_write'+ ? 'recovery_required' : facts.owner_unavailable || facts.owner?.stale ? 'owner_unavailable' : facts.earlier_write ? 'waiting_on_earlier_write': raw ? (WRITE_HEALTH_REASONS as readonly string[]).includes(raw) ? raw as WriteDiagnostic['reason'] : 'cause_unknown' : 'pending';const aged = age >= 120_000;const unknown = reason === 'pending' || reason === 'cause_unknown';if (aged && unknown) reason = 'cause_unknown';- const inspect = aged || unexpected || facts.inspect_owner || ['writer_pool_capacity', 'owner_unavailable', 'writer_lock_unavailable', 'owner_stale'].includes(reason);- const owner = facts.owner && !facts.owner.live ? { host_id: facts.owner.owner_host_id, live: false, last_active: facts.owner.last_active } : undefined;+ const inspect = aged || unexpected || facts.inspect_owner || ['writer_pool_capacity', 'owner_unavailable', 'writer_lock_unavailable'].includes(reason);+ const owner = facts.owner?.stale ? { host_id: facts.owner.owner_host_id, live: false, last_active: facts.owner.last_active } : undefined;return { retry_after_ms: inspect ? INSPECT_OWNER_RETRY_MS : !unknown || age >= 30_000 ? 5000 : 1000,diagnostic: { age_ms: age, assessment: unknown ? aged ? 'stalled' : 'pending' : 'blocked', reason,next_action: inspect ? 'inspect_owner' : 'poll', ...(facts.observed_at ? { observed_at: facts.observed_at } : {}), ...(owner ? { owner } : {}) } };@@ -35,7 +35,7 @@ export function writeHealth(row: { state: WriteRequestState; created_at: Date |export function pendingWriteHint(receipt: WriteReceipt, operation?: string): string {const identity = `Use the same operation with the same arguments and request_id ${receipt.request_id}. Do not submit a new request_id for this write.`;- const owner = receipt.diagnostic?.reason === 'owner_stale' && receipt.diagnostic.owner+ const owner = receipt.diagnostic?.owner? ` The owner host ${receipt.diagnostic.owner.host_id} runs no consumer and was last active ${receipt.diagnostic.owner.last_active ?? 'at no recorded time'}; it may be asleep or gone, and this write publishes only when that host runs gbrain again or its ownership moves through an explicit operator step.` : '';if (receipt.diagnostic?.next_action === 'inspect_owner') return `${identity}${owner} Ask the operator to inspect gbrain sources writer status --probe --json on the selected brain's existing owner. Do not claim, transfer, activate, or remove locks. Poll no faster than ${receipt.retry_after_ms ?? 30_000} ms; if receipt helpers are unavailable, replay the same verb only after inspection.`;const target = receipt.target?.slug ? ` Its fact goes to page ${receipt.target.slug}${receipt.target.entity_slug && receipt.target.entity_slug !== receipt.target.slug ? ` (entity ${receipt.target.entity_slug})` : ''}; get_write_request reports when it is saved there.` : '';diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex e8f3935477..f6708f124e 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -15,7 +15,7 @@ import { pipelined } from '../page-state/transactions.ts';import { backgroundPaused, backgroundWorktreeInactive, declaredBackground, readBackgroundPauseShare, resolveAdmissionOrigin, type AdmissionOrigin } from './admission-origin.ts';import { EFFECT_BYTES_SQL, RECEIPT_RESERVATION_FLOOR, receiptReservation, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';-import { ownerActivity, type OwnerActivity } from './owner-activity.ts';+import { OWNER_READ_BUDGET_MS, startOwnerRead } from './owner-activity.ts';import { assertBackgroundOwner } from './owner-verification.ts';import { writerStamp } from './writer-versions.ts';import { intentCarriesContent, intentCarriesPurgedContent, PURGE_PRESENCE_COLUMNS } from './purged-intent.ts';@@ -1247,12 +1247,15 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]) head ON true`, [roots], { signal: engine.kind === 'postgres' ? abort.signal : undefined }).catch(() => null).finally(() => { if (healthQueries.get(engine) === query) healthQueries.delete(engine); });healthQueries.set(engine, query);+ // GBRA-248: owner facts read beside the head facts, inside the same 500 ms budget.+ const ownerReadStarted = performance.now();+ const settleOwners = startOwnerRead(engine, pending.flatMap(row => row.worktree_id ? [row.worktree_id] : []));let timer: ReturnType<typeof setTimeout> | undefined;const facts = await Promise.race([query, new Promise<null>(resolve => {timer = setTimeout(() => { abort.abort(); resolve(null); }, 500);})]).finally(() => { if (timer) clearTimeout(timer); });+ const owners = await settleOwners(facts ? OWNER_READ_BUDGET_MS - (performance.now() - ownerReadStarted) : 0);if (!facts) return result;- const owners = await boundedOwnerActivity(engine, pending.flatMap(row => row.worktree_id ? [row.worktree_id] : []));const byRoot = new Map(facts.map(fact => [fact.root, fact]));for (const row of pending) {const fact = byRoot.get(row.worktree_id ?? `db:${row.source_incarnation}`);@@ -1268,11 +1271,3 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]}return result;}-/** GBRA-248: the owners of these worktrees, within the receipt read's 500 ms budget; a slow or failed read adds no owner facts. */-export async function boundedOwnerActivity(engine: BrainEngine, worktreeIds: readonly string[]): Promise<Map<string, OwnerActivity>> {- if (!worktreeIds.length) return new Map();- let timer: ReturnType<typeof setTimeout> | undefined;- return Promise.race([ownerActivity(engine, worktreeIds).catch(() => new Map<string, OwnerActivity>()),- new Promise<Map<string, OwnerActivity>>(resolve => { timer = setTimeout(() => resolve(new Map()), 500); })])- .finally(() => { if (timer) clearTimeout(timer); });-}diff --git a/src/core/persistence/owner-activity.ts b/src/core/persistence/owner-activity.tsindex cc651a9066..d17f2e9c22 100644--- a/src/core/persistence/owner-activity.ts+++ b/src/core/persistence/owner-activity.ts@@ -7,7 +7,14 @@** last_active is the greatest of: the owner's newest consumer heartbeat* (Postgres only; deleted on a clean stop), the owner's newest committed- * publication on the worktree (durable; survives a clean stop and compaction)+ * receipt on the worktree (durable; survives a clean stop and compaction; read+ * through the foreground-committed and sync-watermark partial indexes, whose+ * predicates the two subqueries repeat verbatim. The foreground subquery+ * bounds worktree_id as a range and orders by (worktree_id, sequence): with+ * plain equality the correlated plan walked the sequence key through every+ * receipt, 68 ms against 0.05 ms at 300k receipts on a worktree with none;+ * the sync subquery reads the newest receipt of each source's current+ * incarnation instead of every sync receipt of the worktree)* and the worktree heartbeat (stamped at claim and on a consumer's clean stop).* null means no evidence at all: it reads as stale only once a write has* waited on the worktree past the stale window, and never as permission. The owner is never stale to itself:@@ -31,7 +38,8 @@ export interface OwnerActivity {stale: boolean;}-export async function ownerActivity(engine: BrainEngine, worktreeIds: readonly string[], now = Date.now()): Promise<Map<string, OwnerActivity>> {+export async function ownerActivity(engine: BrainEngine, worktreeIds: readonly string[], opts: { now?: number; signal?: AbortSignal } = {}): Promise<Map<string, OwnerActivity>> {+ const now = opts.now ?? Date.now();const result = new Map<string, OwnerActivity>();const ids = [...new Set(worktreeIds)].filter(Boolean);if (!ids.length) return result;@@ -41,11 +49,15 @@ export async function ownerActivity(engine: BrainEngine, worktreeIds: readonly sAND c.renewed_at > now() - ($2::double precision * interval '1 millisecond')) AS live,GREATEST(w.heartbeat_at,(SELECT max(c.renewed_at) FROM persistence_consumers c WHERE c.host_id=w.owner_host_id),- (SELECT COALESCE(r.published_at, r.completed_at) FROM persistence_requests r- WHERE r.worktree_id=w.id AND r.state='committed' ORDER BY r.sequence DESC LIMIT 1)) AS last_active,+ (SELECT COALESCE(r.published_at, r.completed_at) FROM persistence_requests r WHERE r.worktree_id>=w.id AND r.worktree_id<=w.id+ AND r.state='committed' AND NOT COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%' ORDER BY r.worktree_id DESC, r.sequence DESC LIMIT 1),+ (SELECT max(x.completed_at) FROM sources s CROSS JOIN LATERAL (SELECT r.completed_at FROM persistence_requests r+ WHERE r.worktree_id=w.id AND r.source_incarnation=s.incarnation AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%'+ ORDER BY r.completed_at DESC LIMIT 1) x)) AS last_active,(SELECT min(r.created_at) FROM persistence_requests r WHERE r.worktree_id=w.id AND r.state IN ('queued','running','recovering')) AS oldest_openFROM persistence_worktrees w- WHERE w.id::text = ANY($1::text[]) AND w.owner_host_id IS NOT NULL`, [ids, CONSUMER_LAPSED_MS]);+ WHERE w.id::text = ANY($1::text[]) AND w.owner_host_id IS NOT NULL`, [ids, CONSUMER_LAPSED_MS],+ { signal: engine.kind === 'postgres' ? opts.signal : undefined });const local = existingLocalHostId();for (const row of rows) {const lastActive = row.last_active === null ? null : new Date(row.last_active).toISOString();@@ -58,3 +70,24 @@ export async function ownerActivity(engine: BrainEngine, worktreeIds: readonly s}return result;}++/** How long a receipt read waits for owner facts, counted from when the read started. */+export const OWNER_READ_BUDGET_MS = 500;++/**+ * Starts the owner read now and returns `settle(ms)`, which waits at most that+ * much longer for it. A read still running then is cancelled (Postgres) and adds+ * no owner facts, as does a failed one, so callers fold it into a budget they+ * already have instead of adding one.+ */+export function startOwnerRead(engine: BrainEngine, worktreeIds: readonly string[]): (budgetMs: number) => Promise<Map<string, OwnerActivity>> {+ const abort = new AbortController();+ const read = worktreeIds.length ? ownerActivity(engine, worktreeIds, { signal: abort.signal }).catch(() => null) : Promise.resolve(null);+ return async budgetMs => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const owners = await Promise.race([read, new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), Math.max(0, budgetMs)); })])+ .finally(() => { if (timer) clearTimeout(timer); });+ if (!owners) abort.abort();+ return owners ?? new Map();+ };+}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex aba8905e9a..118a082a4b 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -10,8 +10,8 @@ import { claimOwnerKind, isOneShotCommand } from './claim-phase.ts';import { noteDirectPoolLease } from '../direct-pool-profile.ts';import { preparePageMutation } from './page-prepare.ts';import { prepareSemanticPageMutation } from './semantic-pages.ts';-import { boundedOwnerActivity, getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';-import type { OwnerActivity } from './owner-activity.ts';+import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';+import { OWNER_READ_BUDGET_MS, startOwnerRead, type OwnerActivity } from './owner-activity.ts';import { isTerminal, type WriteRequest } from './model.ts';import { isWriteErrorCode, type WriteReceipt } from './types.ts';import { registerPgliteReopen } from '../pglite-lifecycle.ts';@@ -251,10 +251,13 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:let deadline = started + waitMs;const firstPoll = recentlySettled.get(engine)?.has(id) ? 0 : Math.min(WRITE_POLL_START_MS, waitMs / 2);let delay = firstPoll, failure: { error: unknown; attempts: number } | undefined;+ // GBRA-248: owner facts for a write that may be left pending, read during the wait's last OWNER_READ_BUDGET_MS so they never extend it.+ let settleOwner: ((budgetMs: number) => Promise<Map<string, OwnerActivity>>) | undefined;try {while (!service.stopping && !opts.signal?.aborted) {if (handed) { row = handed; handed = undefined; if (isTerminal(row)) return { kind: 'terminal', row }; }const remaining = deadline - performance.now();+ if (!settleOwner && row.worktree_id && remaining <= OWNER_READ_BUDGET_MS) settleOwner = startOwnerRead(engine, [row.worktree_id]);if (remaining <= 0) {if (opts.whileHeldMs && opts.whileHeldMs > waitMs && deadline === started + waitMs&& (consumer.holds(id) || row.state === 'queued' && !row.blocked_reason)) { deadline = started + opts.whileHeldMs; continue; }@@ -315,9 +318,12 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:}const cause = BLOCKED_WRITE_REASONS.find(reason => reason === row.blocked_reason);if (cause) return { kind: 'blocked', row, request_id: row.request_id, cause, command: `gbrain sources writer status ${row.source_id} --json` };- // GBRA-248: a write left pending names its owner when that host runs no consumer, so the receipt (and --accept-pending) can tell a stale owner from a slow commit.- const owner = row.worktree_id ? (await boundedOwnerActivity(engine, [row.worktree_id])).get(row.worktree_id) : undefined;- if (owner) observedOwners.set(row, owner);+ // GBRA-248: a write left pending names a stale owner, so the receipt (and --accept-pending) can tell it from a slow commit.+ if (row.worktree_id) {+ const owners = await (settleOwner ?? startOwnerRead(engine, [row.worktree_id]))(Math.min(OWNER_READ_BUDGET_MS, deadline - performance.now()));+ const owner = owners.get(row.worktree_id);+ if (owner) observedOwners.set(row, owner);+ }return { kind: 'pending', row };}/** At most four progress reads per engine; concurrent waiters on one request share a read. */diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex be3c3f4f75..08231e52ef 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -27,7 +27,7 @@ export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];export const WRITE_HEALTH_REASONS = ['pending', 'waiting_on_earlier_write', 'database_contention', 'writer_busy','revision_changed_repreparing', 'recovery_required', 'writer_pool_capacity', 'owner_unavailable',- 'writer_lock_unavailable', 'consumer_stopping', 'cause_unknown', 'owner_stale'] as const;+ 'writer_lock_unavailable', 'consumer_stopping', 'cause_unknown'] as const;export const WRITE_HEALTH_ASSESSMENTS = ['pending', 'blocked', 'stalled'] as const;export const WRITE_HEALTH_ACTIONS = ['poll', 'inspect_owner'] as const;export interface WriteDiagnostic {@@ -36,7 +36,7 @@ export interface WriteDiagnostic {assessment: typeof WRITE_HEALTH_ASSESSMENTS[number];reason: typeof WRITE_HEALTH_REASONS[number];next_action: typeof WRITE_HEALTH_ACTIONS[number];- /** GBRA-248: the worktree owner when it runs no consumer: its host id and last recorded activity (null when none). */+ /** GBRA-248: present only when the worktree owner is stale (reason owner_unavailable): no live consumer and quiet past the stale window. Older readers ignore it. */owner?: { host_id: string; live: boolean; last_active: string | null };}diff --git a/src/core/persistence/write-wait.ts b/src/core/persistence/write-wait.tsindex 11fac114a9..da7006dfcb 100644--- a/src/core/persistence/write-wait.ts+++ b/src/core/persistence/write-wait.ts@@ -118,7 +118,7 @@ export function pendingReceiptOf(error: unknown): WriteReceipt | null {* the stale window (a moved or restored brain, a replaced container home).*/export function acceptPendingCovers(receipt: WriteReceipt | null | undefined): boolean {- return receipt?.diagnostic?.reason !== 'owner_stale';+ return !receipt?.diagnostic?.owner;}/**diff --git a/test/init-cold-home-embedding.test.ts b/test/init-cold-home-embedding.test.tsindex 83a5e058a1..b3b09f358a 100644--- a/test/init-cold-home-embedding.test.ts+++ b/test/init-cold-home-embedding.test.ts@@ -100,6 +100,20 @@ describe('cold-home re-init over an embedded PGLite brain', () => {expect(fileConfig(explicit).embedding_disabled).toBe(true);expect(fileConfig(explicit).embedding_model).toBeUndefined();}, 240_000);++ test('a keyless brain re-initialized from a cold home stays keyless', async () => {+ for (const firstFlags of [[], ['--no-embedding']]) {+ const owner = coldHome();+ const path = join(owner, 'keyless.pglite');+ const first = await runCli(['init', '--pglite', '--path', path, ...firstFlags], owner);+ expect({ code: first.exitCode, stderr: first.stderr }).toMatchObject({ code: 0 });+ const home = coldHome();+ const again = await runCli(['init', '--pglite', '--path', path], home);+ expect({ code: again.exitCode, stderr: again.stderr }).toMatchObject({ code: 0 });+ expect({ flags: firstFlags, disabled: fileConfig(home).embedding_disabled }).toEqual({ flags: firstFlags, disabled: true });+ expect(again.stdout).not.toContain('kept this database');+ }+ }, 300_000);});describe('cold-home re-init over an embedded Postgres brain', () => {diff --git a/test/owner-stale-moved-brain.test.ts b/test/owner-stale-moved-brain.test.tsindex 80ac975ca6..e6030e6ee2 100644--- a/test/owner-stale-moved-brain.test.ts+++ b/test/owner-stale-moved-brain.test.ts@@ -2,7 +2,7 @@* GBRA-248 W0a against the real CLI: a PGLite brain moved or restored under a* new host identity (its host.json did not come along, as with a fresh* container GBRAIN_HOME) queues writes for the old owner, which will never- * publish them. The receipt names owner_stale with the owner's last activity,+ * publish them. The receipt names the stale owner (reason owner_unavailable, a diagnostic.owner block) with its last activity,* --accept-pending (flag and env) still exits 10, and doctor's* owner_host_stale warns. Before the move the same brain's opt-in exits 0.*/@@ -50,7 +50,7 @@ beforeAll(async () => {afterAll(() => { rmSync(dir, { recursive: true, force: true }); });describe('a moved PGLite brain and the pending-write contract', () => {- test('on its owner a paused write is covered by --accept-pending; after the move it is owner_stale and exits 10', async () => {+ test('on its owner a paused write is covered by --accept-pending; after the move its owner is stale and it exits 10', async () => {const seeded = await cli(['put', 'notes/seed', '--json'], page('Seed body.'));expect({ code: seeded.code, stderr: seeded.stderr }).toMatchObject({ code: 0 });@@ -65,7 +65,7 @@ describe('a moved PGLite brain and the pending-write contract', () => {try {const held = await cli(['put', 'notes/held', '--request-id', heldId, '--wait', '1', '--accept-pending', '--json'], page('Held body.'));expect({ code: held.code, stderr: held.stderr }).toMatchObject({ code: 0 });- expect(JSON.parse(held.stdout).write_request.diagnostic?.reason).not.toBe('owner_stale');+ expect(JSON.parse(held.stdout).write_request.diagnostic?.owner).toBeUndefined();} finally { await lock.release(); }});const drained = await cli(['put', 'notes/held', '--request-id', heldId, '--wait', '30', '--json'], page('Held body.'));@@ -78,9 +78,9 @@ describe('a moved PGLite brain and the pending-write contract', () => {const pending = await cli(['put', 'notes/moved', '--request-id', id, '--wait', '1', '--accept-pending', '--json'], page('Moved body.'));expect({ code: pending.code, stderr: pending.stderr }).toMatchObject({ code: PENDING_WRITE_EXIT_CODE });const receipt = JSON.parse(pending.stdout).write_request;- expect(receipt).toMatchObject({ request_id: id, diagnostic: { reason: 'owner_stale', next_action: 'inspect_owner', owner: { live: false } } });+ expect(receipt).toMatchObject({ request_id: id, diagnostic: { reason: 'owner_unavailable', next_action: 'inspect_owner', owner: { live: false } } });expect(Number.isFinite(Date.parse(receipt.diagnostic.owner.last_active))).toBe(true);- expect(pending.stderr).toContain('owner_stale');+ expect(pending.stderr).toContain('quiet past the stale window');expect(pending.stderr).toContain('gbrain doctor --only owner_host_stale --json');const viaEnv = await cli(['put', 'notes/moved', '--request-id', id, '--wait', '0', '--json'], page('Moved body.'), { GBRAIN_ACCEPT_PENDING: '1' });diff --git a/test/persistence-owner-activity.test.ts b/test/persistence-owner-activity.test.tsindex eb3ed3c98c..63522d541d 100644--- a/test/persistence-owner-activity.test.ts+++ b/test/persistence-owner-activity.test.ts@@ -1,6 +1,6 @@/*** GBRA-248 W0a: owner activity on both engines. A worktree whose owner host- * runs no consumer and has been quiet past 24 h reads owner_stale in the+ * runs no consumer and has been quiet past 24 h reads stale (owner_unavailable plus diagnostic.owner) in the* receipt, which --accept-pending does not cover; a PGLite file held under* another host identity is stale at once; the owner is never stale to itself;* a live consumer keeps its owner fresh and its clean stop leaves a durable@@ -50,15 +50,15 @@ async function worktree(engine: BrainEngine, owner: string, heartbeatHoursAgo: nVALUES($1::uuid, CASE WHEN $2::double precision IS NULL THEN NULL ELSE now()-($2::double precision*interval '1 hour') END) RETURNING id::text`, [owner, heartbeatHoursAgo]);return row!.id;}-async function request(engine: BrainEngine, worktreeId: string | null, state: 'queued' | 'committed', hoursAgo: number): Promise<string> {+async function request(engine: BrainEngine, worktreeId: string | null, state: 'queued' | 'committed', hoursAgo: number, intent = '{"content":"x"}'): Promise<string> {return engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");const [row] = await tx.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation,state,intent,worktree_id,created_at,updated_at,completed_at,published_at)- VALUES('local_cli','owner-activity',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),$3,$4,'{}'::jsonb,0,0,$5,'{"content":"x"}'::jsonb,$6::uuid,+ VALUES('local_cli','owner-activity',$1::uuid,'put_page',$2,(SELECT incarnation FROM sources WHERE id=$2),$3,$4,'{}'::jsonb,0,0,$5,$8::jsonb,$6::uuid,now()-($7::double precision*interval '1 hour'),now()-($7::double precision*interval '1 hour'),CASE WHEN $5='committed' THEN now()-($7::double precision*interval '1 hour') END,CASE WHEN $5='committed' THEN now()-($7::double precision*interval '1 hour') END)- RETURNING id::text`, [randomUUID(), SOURCE, `notes/${randomUUID()}`, randomUUID(), state, worktreeId, hoursAgo]);+ RETURNING id::text`, [randomUUID(), SOURCE, `notes/${randomUUID()}`, randomUUID(), state, worktreeId, hoursAgo, intent]);return row!.id;});}@@ -73,7 +73,9 @@ describe('owner activity', () => {const unknownYoung = await worktree(engine, randomUUID(), null); await request(engine, unknownYoung, 'queued', 1);const unknownOld = await worktree(engine, randomUUID(), null); await request(engine, unknownOld, 'queued', 48);const published = await worktree(engine, randomUUID(), 48); await request(engine, published, 'committed', 1); await request(engine, published, 'queued', 2);- const owners = await ownerActivity(engine, [gone, recent, own, unknownYoung, unknownOld, published]);+ const synced = await worktree(engine, randomUUID(), 48);+ await request(engine, synced, 'committed', 1, '{"kind":"managed_sync_import"}'); await request(engine, synced, 'queued', 2);+ const owners = await ownerActivity(engine, [gone, recent, own, unknownYoung, unknownOld, published, synced]);expect(owners.get(gone)).toMatchObject({ live: false, stale: true, foreign_file_holder: pglite });expect(Date.now() - Date.parse(owners.get(gone)!.last_active!)).toBeGreaterThan(OWNER_STALE_MS);expect(owners.get(recent)).toMatchObject({ live: false, stale: pglite });@@ -82,19 +84,23 @@ describe('owner activity', () => {expect(owners.get(unknownOld)).toMatchObject({ last_active: null, stale: true });expect(owners.get(published)!.stale).toBe(pglite);expect(Date.now() - Date.parse(owners.get(published)!.last_active!)).toBeLessThan(2 * 3_600_000);+ expect(owners.get(synced)!.stale).toBe(pglite);+ expect(Date.now() - Date.parse(owners.get(synced)!.last_active!)).toBeLessThan(2 * 3_600_000);}}));- test('the receipt names owner_stale and --accept-pending does not cover it; a repo-less write never names an owner', async () => inHome(async () => {+ test('the receipt names a stale owner and --accept-pending does not cover it; the owner host receipt and a repo-less write name none', async () => inHome(async () => {for (const engine of engines) {const owner = randomUUID();const gone = await worktree(engine, owner, 48);const id = await request(engine, gone, 'queued', 48);const dbOnly = await request(engine, null, 'queued', 48);- const rows = [(await getWriteRequestById(engine, id))!, (await getWriteRequestById(engine, dbOnly))!];+ const own = await worktree(engine, self, 48);+ const recentId = await request(engine, own, 'queued', 48);+ const rows = [(await getWriteRequestById(engine, id))!, (await getWriteRequestById(engine, dbOnly))!, (await getWriteRequestById(engine, recentId))!];const facts = await writeHealthFacts(engine, rows);const stale = receiptFor(rows[0]!, facts.get(id));- expect(stale.diagnostic).toMatchObject({ reason: 'owner_stale', next_action: 'inspect_owner', owner: { host_id: owner, live: false } });+ expect(stale.diagnostic).toMatchObject({ reason: 'owner_unavailable', next_action: 'inspect_owner', owner: { host_id: owner, live: false } });const wire = publicWriteReceipt(stale as never);expect(isWriteReceipt(wire)).toBe(true);expect(wire.diagnostic?.owner?.host_id).toBe(owner);@@ -103,9 +109,11 @@ describe('owner activity', () => {expect(writeErrorExitCode(pending(wire), true)).toBe(PENDING_WRITE_EXIT_CODE);expect(writeErrorExitCode(pending(wire), false)).toBe(PENDING_WRITE_EXIT_CODE);const repoLess = publicWriteReceipt(receiptFor(rows[1]!, facts.get(dbOnly)) as never);- expect(repoLess.diagnostic?.reason).not.toBe('owner_stale');expect(repoLess.diagnostic?.owner).toBeUndefined();expect(writeErrorExitCode(pending(repoLess), true)).toBe(0);+ const quiet = publicWriteReceipt(receiptFor(rows[2]!, facts.get(recentId)) as never);+ expect(quiet.diagnostic?.owner).toBeUndefined();+ expect(writeErrorExitCode(pending(quiet), true)).toBe(0);}}));