Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Read-only mirrors stay read-only for every writer, and durability refusals change nothing
garrytana50e760921ba
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex b5c05e6cfd..3072ffa0f0 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -9,7 +9,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/authority.ts` — durable write authority. `submissionAuthority` records the caller's grant ceiling on every write request (scopes, operations, slug prefixes, delegated namespace and, for a delegated job, its native `subagentId` when a positive safe integer); `authorizeWrite` re-checks it against the CURRENT principal at publication and replay. For a delegated OAuth client the current namespace is the stored `delegated_slug_prefixes` in `prefixes` mode, or only `wiki/agents/<retained subagentId>/*` for the native `job` form (prefixes NULL); anything else allows nothing, and it always intersects the original accepted prefixes, bound tools, scope and source, so a revoked, narrowed or switched grant or a foreign or invalid job id denies (`test/persistence-page-authority.test.ts`, Postgres: `test/e2e/minions-authority-parity.test.ts`). #5994: a context carrying `replayAuthority` (set only by `gbrain repair failed-writes`) gets that stored authority back from `submissionAuthority` (`replayedAuthority`): same source incarnation or refused, `databaseOnlyReason`/`takeHoldersUsed` dropped for admission to recompute, then `authorizeWrite` and page visibility against the live grant.- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still need physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists or is relative (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`). The report's `warnings[]` (dry run and real run) carries one `git_durability_not_enabled` entry per filesystem source the effect runner's policy (`gitDurabilityPolicy`) would leave non-durable, with `enable_command`, a read-only `git-durability --enable --dry-run` fix and the note that enabling re-queues skipped Git effects; `persistence-admin.ts` also prints them to stderr without `--json`, and activation proceeds (#5182, `test/writer-activate-durability-warnings-5182.test.ts`).-- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes (codes in `GIT_PUSH_CODES`; `retry-effects <source> --parked-pushes` does the same without a credential). `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.+- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs; a non-preview checks its approval before any side effect, #7634) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes (codes in `GIT_PUSH_CODES`; `retry-effects <source> --parked-pushes` does the same without a credential; a per-request refusal such as `page_not_found` is listed in `refused` and the run ends `partial`, #7110). `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.- `src/core/persistence/effect-git.ts` (`pushGitRoot`) + `git-push-holds.ts` — a Git effect reads the remote tip (`ls-remote`), scans `<tip>..HEAD` and pushes HEAD as a fast-forward leased on it (a missing branch: whole history first). A non-ancestor tip or a moved remote runs `gbrain git commit-push --push-only --keep-checkout --scan-secrets` as a child (off the event loop, never PATH `gbrain`): it merges in memory and pushes without moving the checkout or running pre-push hooks, so `sources refresh` stays the only importer. Holds: `publish_secret_found`, `publish_scan_unreadable`, or `integrate_conflict` (the user picks `--resolve`). `readGitPushHolds` counts each source's effects retrying or parked on a push code, with conflict state and one fix, for doctor `parked_effects` and `sync status` `git_push_holds` (`next` falls back to a held fix). A hold in an unbound worktree is `former_worktree` (fix: settle preview, #7378). Pinned by `test/pathological/h2-git-effect-moved-remote.test.ts`.- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, queued, running or recovering effects (the predicate activation uses; each exit says what clears it, and a failing links or facts-backstop effect settles after five attempts), held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `failedEffectHistory` lists terminally failed effects as history (`failed_effects` on the dry run and the applied report, never blockers), each with its code and the exit that retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects, `repair embedding-effects` for a failed embedding effect, none for `embedding_zero_norm` or an effect whose source was archived, replaced or removed (`test/pathological/a15-deactivate-exits.test.ts` runs every printed exit and checks it clears its entry); `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex cf429ec24a..beee4c4123 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -31,4 +31,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/url-clone.ts` — gbrain-owned `sources add --url` clones (#6946, GBRA-130 C-2). `isOwnedClone` (config `managed_clone` or a `local_path` under the default clone dir) and `defaultCloneDir`; `urlCloneReadOnly` is the one predicate (owned clone on a brain without managed persistence) the fence writer (`fence-write.ts`, `databaseOnlyReason: 'url_clone'`), write-through (`skipped: 'url_clone'`), timeline write-through, unfenced-facts adoption, the empty-fence guard and `sourceMirrorReadOnly` consult, so nothing gbrain writes lands in a checkout it updates with `git pull --ff-only`. `urlClonePullBlock` reads the tracked changes of a clone whose pull failed and returns `pull_blocked_local_changes` with an `ask_user` fix naming the preview `gbrain repair url-clone-fences --source <id>`; `formatUrlClonePullBlock` renders it for sync's stderr (`sync/preflight.ts`) and `cycle.ts` puts it in the sync phase detail as `pull_blocked`. Test: `test/pathological/c2-url-clone-fences.test.ts`. gbrain itself never writes into an owned clone on an unmanaged brain, but local commits someone else makes there are published by `gbrain sources git-reconcile` (`src/commands/sources-git-reconcile.ts`, autopilot each tick: secret scan, rewritten-upstream refusal, repository-root check); `sources.refresh_publish_diverged false` or `gbrain sources set-sync <id> off` keeps them local.- `src/core/url-source-origin.ts`, `src/commands/sources-record-origin.ts` and `src/commands/doctor/checks/url-source-origin.ts` — who added a URL source (`sources.config.added_by_remote_caller`). Both add paths write it (`true` for a remote caller, `false` for the local operator); only an explicit `true` reads as remote. URL sources added before that record existed carry none, and nothing stored tells a remote caller's add from the local operator's (same row, same default clone directory); a clone outside `$GBRAIN_HOME/clones/<id>` (or a `clones/<id>` under an earlier home) proves a local add. A URL clone counts when `isOwnedClone` accepts it, so an unmarked clone at the default directory is listed too. `urlSourcesWithoutOrigin` (read-only) feeds the wave check `url_source_origin` (host-only, `resolution: 'operator'`, `warn` with an `ask_user` fix whose argv is the preview). `recordSourceOrigin(engine, ids, { origin, apply, remote })` backs `gbrain sources record-origin <id>... --remote|--local [--apply] [--json]`: it throws `trusted_local_only` unless `remote === false`, previews unless `apply`, writes `true` (`--remote`) or `false` (`--local`) in one transaction that re-reads the row `FOR UPDATE` and refuses `source_changed` if its path or URL moved; on a managed brain that transaction runs inside `withTopologyLocks` after `lockTopologyRows`, the locks a reclone takes (a held lock refuses the id `source_busy`), and `runManagedSourceClone` takes the config it clones with from its own locked admission read, so a record and a reclone never interleave. `--remote --apply` also writes `LFS_OFF_CLONE_CONFIG` into the repository's shared config (`--git-common-dir`; `git config --file`, not run in the checkout) before the row, reads the effective values back (`lockDownGaps`) and throws when a worktree-scoped or included setting overrides one, and locks down an already-remote source whose checkout lacks it (no git-lfs refusal for it unless Git cannot place the checkout, `lfs_unknown`); each key's existing values are removed before its one value is written, in a `config.lock` copy renamed over the config in one step; a throw is reported for its id as `write_failed` and the batch continues. It never removes a `true`, and refuses `--remote` for a checkout with any tracked `filter=lfs` path or a committed `.gitattributes` declaring `filter=lfs` outside a comment line (`lfs_tracked`, worded per case; read with `hardenedGitSync` `ls-files -- ':(attr:filter=lfs)'` plus every committed `.gitattributes` blob from `ls-tree -z` records split at their first tab, then `cat-file`, so clone-local attributes cannot hide one, and read again under the locks), or one it cannot inspect (`lfs_unknown`, whose reason names the cause: checkout missing, not its own repository's top level by a realpath comparison, owned by another user (`safe.directory`), or a Git read failed), because a lock-down reclone would not match the stored writer manifest there. An unborn HEAD with an empty index (a clone of an empty repository) has no committed attributes and passes. Without git-lfs files the tracked bytes are the same, so no manifest is written. Pinned by `test/url-source-origin.test.ts` (PGLite and Postgres).-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`; a live source whose `local_path` is relative counts as owning every tree, one absolute only on another OS does not, and a `local_path` or `sync.repo_path` target not absolute on this host (`isHostAbsolutePath`) is `repo_not_found`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, inlineOnly?, logger?, expectedFileBytes?, deferCommit?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders an inline page via `serializePageToMarkdown`, and writes the `.md`. A page stored in segments is never rendered whole: its file is measured from its segments at the snapshot's revision (`unreadPageFile`; a page that moved since refuses `revision_conflict`), checked against `PUSH_SCAN_MAX_FILE_BYTES` before `source_path` is bound (a body already over the cap by `body_bytes` is refused without streaming), streamed through `stageStreamedContent` on the engine it was given (so a caller inside a transaction works) keeping the existing file's mode, and renamed over the target after the file-changed check; `frontmatterOverrides` on such a page return an error result, and `inlineOnly` (the derived writer) skips it as `segmented_page` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, content? (the bytes written; inline pages only), skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result (and a `relative_root` one, naming `sources set-path`) with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) unless the caller passes `deferCommit` (the derived write-through commits its batch itself, #8073; `deletePageThrough` takes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946: on a gbrain-owned `--url` clone of an unmanaged brain (`urlCloneReadOnly`), `writePageThrough` returns `skipped: 'url_clone'` and `deletePageThrough` returns `removed: false, skipped: 'url_clone'`; `timeline-write-through.ts` skips the same way.+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`; a live source whose `local_path` is relative counts as owning every tree, one absolute only on another OS does not, and a `local_path` or `sync.repo_path` target not absolute on this host (`isHostAbsolutePath`) is `repo_not_found`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, inlineOnly?, logger?, expectedFileBytes?, deferCommit?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders an inline page via `serializePageToMarkdown`, and writes the `.md`. A page stored in segments is never rendered whole: its file is measured from its segments at the snapshot's revision (`unreadPageFile`; a page that moved since refuses `revision_conflict`), checked against `PUSH_SCAN_MAX_FILE_BYTES` before `source_path` is bound (a body already over the cap by `body_bytes` is refused without streaming), streamed through `stageStreamedContent` on the engine it was given (so a caller inside a transaction works) keeping the existing file's mode, and renamed over the target after the file-changed check; `frontmatterOverrides` on such a page return an error result, and `inlineOnly` (the derived writer) skips it as `segmented_page` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, content? (the bytes written; inline pages only), skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result (and a `relative_root` one, naming `sources set-path`) with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) unless the caller passes `deferCommit` (the derived write-through commits its batch itself, #8073; `deletePageThrough` takes it too) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward. #6946/#7098: on a read-only checkout (`readOnlyCheckout` in `mirror-read-only.ts`: a `mirror-readonly` source, or a gbrain-owned `--url` clone of an unmanaged brain), `writePageThrough` returns `skipped: 'mirror_read_only' | 'url_clone'` and `deletePageThrough` returns `removed: false` with the same skip; `timeline-write-through.ts`, the fact fence writer, `forget` and the unfenced-fact pass skip the same way.diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 528c2b7022..e8891fa1f2 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -486,6 +486,13 @@ writes (for example a `forget`) complete as skipped. The flag is off by default.With `sync.write_through` off, sync keeps that canonical metadata in thedatabase for every source, mirror or not, and never rewrites a checkout file.+On a brain without managed persistence the flag holds the same way: page+write-through (`sync --full` re-exports, `brainstorm --save`), fact fences,+timeline entries, `forget`, the extract cycle's fence pass and owner trust+repairs leave the checkout untouched and keep the write in the database (a+trust repair is listed `needs_review` instead), reporting `mirror_read_only`+(#7098). The dream cycle's reverse-written pages are not gated yet.+A managed brain never pulls inside a cycle. Advance a managed checkout withone command on its owner host:@@ -667,8 +674,8 @@ writers, Git effects belong to the persistence outbox; generated legacy pushhelpers refuse to run rather than bypass that ownership boundary. See the[concurrent-write guide](concurrent-writes.md). On a managed root the ownercommits and pushes page writes (`gbrain sources writer git-durability <source>---enable`), files that are not pages are committed with plain git and ride the-owner's next push, the checkout is never pulled or rebased, and the durability+--enable`), files that are not pages are committed with+`gbrain git commit-push -m "<msg>" -- <paths>` and ride the owner's next push, the checkout is never pulled or rebased, and the durabilityblock below is regenerated in its managed form by that verb; see[files that are not pages](../architecture/topologies.md#files-that-are-not-pages).diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 986e666ced..47846a88e6 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -63,7 +63,7 @@ of making a duplicate.| `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. || <a id="owner_marker_missing"></a>`owner_marker_missing` | `owner_marker_missing` | The ownership marker `.gbrain-owner.json` is gone from the checkout root while the reservation beside the checkout still names this owner and identifies this exact directory: device, inode and birth time all equal (a cleanup or a restore that dropped dotfiles). A directory the reservation does not identify exactly, a birth time within the 1 µs tolerance included, keeps the generic `recovery_required` and its [recreated-root](#recreated-root) exit. No write publishes there, and a retry never brings the marker back, so the owner finishes each refused write `failed` (its outstanding-request slot is released); a sync stops `blocked_by_failures` on the refused file, without a hold. | Re-create the marker with the verified self-transfer on the brain host: `gbrain sources writer status --source <source> --json` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Then run the same `gbrain sync` again. Never create or copy the marker by hand. || `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |-| `physical_root_directory_changed` | `recovery_required` | The directory at the checkout's recorded path is not the one the owner stamped: its inode changed, or its birth time differs from the stamp by more than 1 µs, while the owner token, brain, worktree, root and device all still match. A checkout deleted and recreated at the same path (restore from backup, rebuilt container, Migration Assistant copy) looks like this. A birth time within 1 µs of the stamp is accepted (#6501: APFS reports a new directory's birth time tens of nanoseconds apart across processes); a stamp of `0` against a filesystem that now reports a birth time, or a damaged stamp, still refuses. | A refused page write carries `detail: physical_root_directory_changed` and this self-transfer as its `fix` (`next: tell_user_to_run`, both phases): an agent relays it and never runs it. If the checkout was recreated at its recorded path, do a deliberate relocated-root self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. `writer status --json` prints the commands filled in. Retry the original write with the **same** request ID. Never delete ownership marker files. |+| <a id="physical_root_directory_changed"></a>`physical_root_directory_changed` | `recovery_required` | The directory at the checkout's recorded path is not the one the owner stamped: its inode changed, or its birth time differs from the stamp by more than 1 µs, while the owner token, brain, worktree, root and device all still match. A checkout deleted and recreated at the same path (restore from backup, rebuilt container, Migration Assistant copy) looks like this. A birth time within 1 µs of the stamp is accepted (#6501: APFS reports a new directory's birth time tens of nanoseconds apart across processes); a stamp of `0` against a filesystem that now reports a birth time, or a damaged stamp, still refuses. | A refused page write carries `detail: physical_root_directory_changed` and this self-transfer as its `fix` (`next: tell_user_to_run`, both phases): an agent relays it and never runs it. If the checkout was recreated at its recorded path, do a deliberate relocated-root self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. `writer status --json` prints the commands filled in, and the refusal's `fix` is that prepare (with the accept as `fix.then`), a host-admin step (`next: tell_user_to_run`), on a write receipt too (#7671). Retry the original write with the **same** request ID. Never delete ownership marker files. || <a id="ownership_record_not_private"></a>`ownership_record_not_private` | `recovery_required` | A private ownership record of the checkout (`.gbrain-owner.json` inside it, or `.gbrain-owner-<hash>.json` beside it) is readable by other users, typically after a recursive `chmod` of a copied brain, so it no longer proves who owns the checkout. Nothing was written; the message names no path. | The refusal's `fix` is `gbrain doctor --only foreign_ownership_marker` on the brain host, which names each such record and the exact `chmod 600 '<path>'`. Run it, then submit the write again with a new request_id. Never remove the record. || <a id="recreated-root"></a>recreated or moved canonical root | `recovery_required` | The checkout at the recorded path is a different directory (new inode and birth time after a restore, a rebuilt container or a Migration Assistant copy) or the recorded path now resolves through a symlink; without this release every verb, self-transfer included, refused with no exit (#5914). | Same path, directory recreated: the self-transfer above with `--confirm-relocated-root` on **both** phases; it waives only the directory identity comparison and needs the reservation beside the root (`.gbrain-owner-<hash>.json`) and the stamp to agree on token, brain, worktree, root and coordination path. Recorded path now a symlink to the moved checkout: `gbrain sources set-path <source> <path>` on the owner host keeps the worktree and moves its records. `gbrain sources writer deactivate --dry-run` lists `physical_root` when its real run would refuse, and the dry runs of `gbrain sources remove` and `gbrain sources set-path` refuse with the same `recovery_required` their real runs would (#6849). Runbook: [recreated root](../architecture/topologies.md#recreated-root). Never delete ownership marker files. || <a id="embedding_budget_below_worst_case"></a>`embedding_budget_below_worst_case` | `embedding_budget_below_worst_case` | `gbrain migrate embeddings` (or the local `migrate_embeddings` operation) was given a `--max-cost-usd` cap below the migration's worst-case authorization: every planned provider request at its maximum input size, plus any debits a resumed run already holds. The run stopped before any provider request, re-chunk or vector invalidation, so nothing changed. The message and JSON carry `cap_usd`, `worst_case_usd`, `debited_usd` and `required_cap_usd`. | Re-run with the value the `suggestion` names, for example `gbrain migrate embeddings --to <provider:model> --dim <N> --max-cost-usd <required_cap_usd> --yes` (operation: `max_cost_usd`). Preview first with `--dry-run`, which prints the worst-case authorization beside the estimate. Requests settle to reported usage, so actual spend is usually far below the cap. See [embedding migration](embedding-migration.md). |diff --git a/scripts/persistence/model.ts b/scripts/persistence/model.tsindex 9cfcc6f37f..97096e3acd 100644--- a/scripts/persistence/model.ts+++ b/scripts/persistence/model.ts@@ -53,7 +53,7 @@ export const KNOWN_DEFERRALS: { class: ViolationClass; match: RegExp; todo: striexport type ViolationClass = 'lost_write' | 'duplicate_apply' | 'untrue_receipt' | 'wedge' | 'withdrawal_permanence'| 'source_isolation' | 'authorization' | 'caller_bound_replay' | 'projection_drift' | 'missing_attribution' | 'orphan_rows' | 'effects_not_terminal'- | 'untyped_error' | 'lock_order';+ | 'untyped_error' | 'lock_order' | 'read_failure';/** Violations that always block a ship (see the plan's bug-fix bound). */export const SAFETY_CLASSES: ReadonlySet<ViolationClass> = new Set(['lost_write', 'duplicate_apply', 'untrue_receipt', 'wedge','withdrawal_permanence', 'source_isolation', 'authorization', 'caller_bound_replay']);@@ -372,7 +372,11 @@ export class ReferenceModel {private async checkProjection(stage: string, live: { id: number; source_id: string; slug: string }[]): Promise<void> {for (const row of live) {const page = await this.readPage('local', row.source_id, row.slug);- const content = String(page?.content ?? '');+ if (!page) {+ this.violate({ class: 'read_failure', detail: `${stage}: get_page of live page ${row.source_id}/${row.slug} failed (${this.lastReadError ?? 'no page returned'}); its fences were not compared with the rows` });+ continue;+ }+ const content = String(page.content ?? '');const takes = parseTakesFence(content).takes;const dbTakes = await this.q<{ row_num: number; claim: string; active: boolean }>('SELECT row_num,claim,active FROM takes WHERE page_id=$1 ORDER BY row_num', [row.id]);diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.tsindex 2844245dbd..d3ee198ddc 100644--- a/src/commands/brainstorm.ts+++ b/src/commands/brainstorm.ts@@ -507,6 +507,13 @@ export function formatSaveOutcome(exitCode: 0,};}+ if (dbSaved && writeThrough.skipped === 'mirror_read_only') {+ return {+ stdout: `\n_Saved to DB page \`${ctx.slug}\` (the source is a read-only mirror, \`gbrain sources mirror-readonly\` — kept database-only)._`,+ stderr,+ exitCode: 0,+ };+ }if (dbSaved && writeThrough.skipped === 'url_clone') {return {stdout: `\n_Saved to DB page \`${ctx.slug}\` (the source is a clone gbrain pulls from upstream — kept database-only)._`,diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 90be2be51c..be38cdad07 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -2052,7 +2052,7 @@ Subcommands:brain needed. See docs/guides/github-source.md.federate <id> Make source appear in cross-source default search.unfederate <id> Isolate source from default search.- mirror-readonly <id> [--dry-run] Read-only mirror (#5409): managed writes never touch its checkout.+ mirror-readonly <id> [--dry-run] Read-only mirror (#5409): page and fact writes skip its checkout.mirror-writable <id> [--dry-run] Undo mirror-readonly. --dry-run previews either and writes nothing.record-origin <id>... --remote|--local [--apply] [--json]Record who added older URL sources (doctor url_source_origin); preview unless --apply.diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.tsindex 77ae6926c8..af0cf03c18 100644--- a/src/commands/sync/full.ts+++ b/src/commands/sync/full.ts@@ -542,7 +542,7 @@ async function reconcileFullSyncDeletes(try {const r = await writePageThrough(engine, slug, { sourceId: sid, expectedFileBytes: null });if (r.written) { reExported++; continue; }- if (r.skipped === 'disabled_by_config' || r.skipped === 'url_clone') continue;+ if (r.skipped === 'disabled_by_config' || r.skipped === 'mirror_read_only' || r.skipped === 'url_clone') continue;if (r.skipped === 'file_changed') throw new OperationError('file_database_drift', 'The checkout file exists; re-export only restores absent files.', `If the file holds the newer edit, run gbrain sync --source ${sid} to import it; otherwise ask the user which version to keep.`);if (r.error) throw new Error(r.error);if (r.skipped === 'over_push_scan_cap') {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6dcbc69d6c..4e4c695f9f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1588,6 +1588,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.529.0', id: 'stuck_recovery_strict_followup_7715', text: 'On a git-canonical (strict) source, `gbrain repair stuck-recovery --keep disk` now says the kept bytes are an uncommitted edit at the file\'s path and hands off to commit then sync (`gbrain git commit-push --path <checkout> -m "<message>" -- <path>`, or `git -C <checkout> restore -- <path>` to discard, then `gbrain sync --source <id> --no-pull`; verify with `git status --porcelain` then `gbrain sync status --source <id> --json`), with an ask-the-user `fix` in the item detail, instead of a database-side `sources reconcile`. Mixed sources keep the reconcile follow-up (#7715).' },{ since: '0.60.529.0', id: 'url_clone_fences_held_preview_7910', text: '`gbrain repair url-clone-fences` lists a held file (for example `visibility_noncanonical`) once, as an apply item, and no longer also counts it as a residual; its preview says the restored file equals HEAD, so sync does not screen it again and the page changes once an upstream fix is pulled and synced (it no longer claims sync holds the file) (#7910).' },{ since: '0.60.529.0', id: 'streamed_put_visibility_wording_7881', text: 'On a brain without managed persistence, `gbrain put --file` and `gbrain capture --file` of a page over the single-string ceiling that asks for `visibility: private` in a spelling page privacy does not read refuse `visibility_not_applied` with the page-write message a smaller put gives (nothing was written; write `visibility: private` on its own frontmatter line), not the import hold\'s "sync or import the file again" (#7881).' },+ { since: '0.60.529.0', id: 'git_durability_refusal_no_side_effects_7634', text: '`gbrain sources writer git-durability <source>` without `--dry-run` now checks `--admin-intent writer_git_durability` and `--expected-state` first: a missing, wrong or stale approval refuses (`writer_admin_intent_required` or `writer_admin_state_changed`) before the token file is read and before anything changes. It used to rewrite the durability block in `AGENTS.md`/`RESOLVER.md`, wire the `--pat-file` credential and retry parked pushes first. After an approved apply, `agents.commit` now names `gbrain git commit-push --path <root> -m "<msg>" -- <file>` instead of plain git.' },+ { since: '0.60.529.0', id: 'parked_push_hidden_page_7110', text: '`gbrain sources writer retry-effects <source> --parked-pushes` (and `git-durability --pat-file`) no longer stops the whole run when one parked request\'s remote writer can no longer see its page (it became private): that request is listed in `refused` with its `request_id`, code `page_not_found`, the page slug and a read-only receipt command, the other parked pushes are retried, and the run ends `partial` (exit 1). The refused request stays parked; nothing retries it under another authority.' },+ { since: '0.60.529.0', id: 'embedding_preflight_abort_7772', text: 'An embedding effect whose stop signal fires while its provider call is being admitted (for example a one-shot `gbrain put` exiting) is now retried (`queued`, `embedding_aborted`) instead of failing for good as `embedding_budget_refused`, which blocked writer quiescence and showed in doctor `stale_embedding_effects` until `gbrain repair embedding-effects --apply`. A real budget refusal still fails as `embedding_budget_refused`.' },+ { since: '0.60.529.0', id: 'mirror_read_only_legacy_writers_7098', text: 'On a brain without managed persistence, a source marked `gbrain sources mirror-readonly` is now left untouched by the legacy disk writers below (#7098): `sync --full` no longer re-exports never-committed database pages into its checkout, `brainstorm --save`, page write-through, timeline entries and fact fences keep the write in the database (write-through and timeline report `skipped: mirror_read_only`), `forget` expires a fenced fact in the database without rewriting the file, and the extract cycle neither fences its database-only facts into the file nor counts them in its legacy-row guard. An owner trust repair (`gbrain repair provenance`, `trust backfill`) lists such a page `needs_review` with detail `mirror_read_only` instead of rewriting its file. The dream cycle\'s reverse-written synthesis, patterns and cycle-summary pages are not gated yet. Before, only managed publication honored the flag, so these writers gave the mirror local changes that could stop its `git pull --ff-only`.' },+ { since: '0.60.529.0', id: 'copied_root_fix_names_self_transfer_7671', text: 'A managed write refused `recovery_required` because a source\'s checkout is a new directory at its recorded path (a copied or restored brain, detail `physical_root_directory_changed`) now carries the relocated-root self-transfer as its `fix` (#7671): `gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root` with its admin intent, then the accept as `fix.then`, a host-admin step (`next: tell_user_to_run`), on a put_page receipt too, where `fix` used to point at the write receipt. Nothing is re-stamped automatically; the write still refuses until the self-transfer runs.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex b43b217945..7d8e180bd7 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -105,7 +105,7 @@ import { embed, getEmbeddingDimensions, getEmbeddingModel, isAvailable } from '.import { isAborted } from '../abort-check.ts';import { parseMarkdown } from '../markdown.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';-import { urlCloneReadOnly } from '../url-clone.ts';+import { readOnlyCheckout } from '../persistence/mirror-read-only.ts';import { acquirePageLock } from '../page-lock.ts';import {lockReconcileRevision,@@ -876,10 +876,10 @@ export async function runExtractFacts(// the destructive reconciliation pass; the other pages reconcile.// #6610: rows the unbound-source policy keeps unfenced on database-only pages stay held out of reconciliation// but never gate the run; doctor fence_integrity names the opt-in that fences them.- // #6946: so do the database-only rows of a clone gbrain owns, which is never fenced.+ // #6946, #7098: so do the database-only rows of a clone gbrain owns or a read-only mirror, which is never fenced.const pending = await pendingLegacyRows(engine, sourceId);const legacySlugs = new Set(pending.keys());- const gating = await urlCloneReadOnly(engine, sourceId) ? [] : [...pending].filter(([slug]) => !unboundRefused.has(slug));+ const gating = await readOnlyCheckout(engine, sourceId) ? [] : [...pending].filter(([slug]) => !unboundRefused.has(slug));const legacyCount = gating.reduce((sum, [, n]) => sum + n, 0);result.legacyRowsPending = legacyCount;result.legacyPages = gating.map(([slug]) => slug).sort();diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex a342be10b0..64622cfc49 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -1120,7 +1120,7 @@ async function runPipelineBodyInner(// didn't (null-localPath echo, or the write_through flag flipped// mid-pipeline across the config-cache TTL). Route the group to the// legacy DB-only path — never drop facts.- if (result.databaseOnlyReason !== 'url_clone' && result.databaseOnlyReason !== 'file_database_drift') warnOnce(+ if (!result.databaseOnlyReason) warnOnce('facts:fence-write-unexpected-fallback',`[facts] writeFactsToFence returned legacyFallback for slug=${slug} despite localPath being set — routing to DB-only inserts.`,);diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex 57d68ad5a9..e4f700a3c0 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -62,7 +62,7 @@ import { recordTaintEdges } from '../trust/taint.ts';import { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts';import type { TaintInput, WriteTrust } from '../trust/tier.ts';import { gitChildEnv } from '../git-env.ts';-import { urlCloneReadOnly } from '../url-clone.ts';+import { readOnlyCheckout } from '../persistence/mirror-read-only.ts';import { bodyUnread } from '../page-body/page-shape.ts';import { bestEffortStoredBodyMirror, fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';@@ -119,10 +119,10 @@ export interface FenceWriteResult {inserted: number;/** DB ids assigned to the inserted rows, in input order. */ids: number[];- /** True when the path fell through to DB-only: local_path unset, `sync.write_through` off, or a gbrain-owned clone (`databaseOnlyReason`). */+ /** True when the path fell through to DB-only: local_path unset, `sync.write_through` off, or a read-only checkout (`databaseOnlyReason`). */legacyFallback?: true;- /** #6946: why a `legacyFallback` is expected — `url_clone`: the source is a clone gbrain owns and pulls (url-clone.ts), so its checkout is never written. */- databaseOnlyReason?: 'url_clone' | 'file_database_drift';+ /** Why a `legacyFallback` is expected: `mirror_read_only` (#7098) or `url_clone` (#6946, a clone gbrain owns and pulls), so the checkout is never written. */+ databaseOnlyReason?: 'mirror_read_only' | 'url_clone' | 'file_database_drift';/** A held file mirror's typed diagnostic and repair instructions; facts take the DB-only fallback. */warning?: string;/** True when fence parse-validate failed; rows were NOT inserted, .tmp quarantined. */@@ -308,8 +308,8 @@ export function stubEntityPage(* stamps the DB index via engine.insertFacts.** Returns `legacyFallback: true` when `target.localPath` is null (also- * under `sync.write_through` off and, with `databaseOnlyReason: 'url_clone'`,- * for a clone gbrain owns, #6946) —+ * under `sync.write_through` off and, with `databaseOnlyReason`, for a+ * read-only mirror (#7098) or a clone gbrain owns, #6946) —* the caller is responsible for falling through to the legacy* DB-only `engine.insertFact` path. We don't do the legacy fallback* here because the caller has the FactsBackstopCtx (visibility,@@ -355,7 +355,7 @@ export async function writeFactsToFence(// legacyFallback contract as a missing local_path — the caller's DB-only// path still records the facts.if (await isWriteThroughDisabled(engine)) return { inserted: 0, ids: [], legacyFallback: true };- if (await urlCloneReadOnly(engine, target.sourceId)) return { inserted: 0, ids: [], legacyFallback: true, databaseOnlyReason: 'url_clone' };+ const readOnly = await readOnlyCheckout(engine, target.sourceId); if (readOnly) return { inserted: 0, ids: [], legacyFallback: true, databaseOnlyReason: readOnly };// #4204: compute the SAME path writePageThrough computes for this// (source, slug) — the fence appends to the page's file, so the two writersdiff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex 015207fa2b..d75571e02e 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -17,6 +17,7 @@ import type { BrainEngine } from '../engine.ts';import { withPageLock } from '../page-lock.ts';import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';+import { readOnlyCheckout } from '../persistence/mirror-read-only.ts';import { parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';import { contentHash } from '../utils.ts';import { locateOutsideCode } from '../fence-scan.ts';@@ -262,7 +263,7 @@ export async function forgetFactInFence(row.entity_slug !== null;if (!canFence) return legacyExpire();- if (await isWriteThroughDisabled(engine)) return legacyExpire();+ if (await isWriteThroughDisabled(engine) || await readOnlyCheckout(engine, row.source_id)) return legacyExpire();// Look up source.local_path.const sources = await engine.executeRaw<SourceRow>(diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex e7a9b6711e..0446aea9ba 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -22,7 +22,8 @@* skipped) or the source has a `local_path` and the page's canonical file* exists on this host. Everything else is counted and left alone: a NULL* entity slug, a missing page or file, a source without a checkout here, or- * (unmanaged, #6946) a clone gbrain owns, whose checkout is never written.+ * (unmanaged, #6946, #7098) a clone gbrain owns or a read-only mirror, whose+ * checkout is never written.** Adoption oracle (#6278, `adoptableClaim`): the fence codec trims a claim,* folds CRLF/CR to LF, reads `~~x~~` as a struck row and `<br>` as a line@@ -82,6 +83,7 @@ import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStorimport { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';import { commitFactFenceFile, gitPathState } from './fence-write.ts';import { isOwnedClone } from '../url-clone.ts';+import { parseSourceConfig } from '../sources-load.ts';import { isSourceDbOnlySlug } from '../persistence/source-storage.ts';export interface UnfencedFactRow {@@ -115,6 +117,8 @@ export interface UnfencedFactsOutcome {skipped_archived: number;/** Unmanaged (#6946): rows of a clone gbrain owns (`sources add --url`), kept database-only so its checkout keeps fast-forwarding. */skipped_url_clone: number;+ /** Unmanaged (#7098): rows of a read-only mirror source (`gbrain sources mirror-readonly`), kept database-only for the same reason. */+ skipped_mirror_read_only: number;pages_touched: number;/** `<slug> (<reason>)` per page whose fence write failed; its rows stay unfenced. */failed_pages: string[];@@ -293,6 +297,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:'SELECT id, local_path, archived, config FROM sources',);const urlClones = new Set(managed ? [] : sources.filter(isOwnedClone).map(s => s.id));+ const mirrors = new Set(managed ? [] : sources.filter(s => parseSourceConfig(s.config).mirror_read_only === true).map(s => s.id));const localPathById = new Map(sources.map(s => [s.id, s.local_path] as const));const archived = new Set(sources.filter(s => s.archived).map(s => s.id));const rows = await engine.executeRaw<UnfencedFactRow>(@@ -309,7 +314,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:);const outcome: UnfencedFactsOutcome = {scanned: rows.length, fenced: 0, skipped_no_entity: 0, skipped_no_local_path: 0, skipped_no_page: 0,- skipped_archived: 0, skipped_url_clone: 0, pages_touched: 0, failed_pages: [], write_errors: 0, fenced_slugs: [], missing_files: [], unbound_refused: [], unadoptable_rows: [],+ skipped_archived: 0, skipped_url_clone: 0, skipped_mirror_read_only: 0, pages_touched: 0, failed_pages: [], write_errors: 0, fenced_slugs: [], missing_files: [], unbound_refused: [], unadoptable_rows: [],};const groups = new Map<string, UnfencedFactRow[]>();for (const row of rows) {@@ -317,6 +322,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:// A managed brain publishes through the source's maintenance authority,// which an archived source does not grant; it never blocks the others.if (managed && archived.has(row.source_id)) { outcome.skipped_archived += 1; continue; }+ if (mirrors.has(row.source_id)) { outcome.skipped_mirror_read_only += 1; continue; }if (urlClones.has(row.source_id)) { outcome.skipped_url_clone += 1; continue; }if (!localPathById.get(row.source_id) && !managed) { outcome.skipped_no_local_path += 1; continue; }if (!row.page_exists) { outcome.skipped_no_page += 1; continue; }diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex a8cb6fae13..d8085d5dc8 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -673,7 +673,8 @@ async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, errif (code === 'embedding_configuration') {await failEffect(engine, effect, 'embedding_configuration'); return;}- if ((code !== 'embedding_storage_unavailable' && isAIInvocationPolicyError(error)) || (error as { tag?: string } | null)?.tag === 'BUDGET_EXHAUSTED') {+ // #7772: the guard marks whatever the invocation preflight throws as a refusal, the stop signal's abort included; a stopped consumer retries below.+ if ((code !== 'embedding_storage_unavailable' && !signal?.aborted && isAIInvocationPolicyError(error)) || (error as { tag?: string } | null)?.tag === 'BUDGET_EXHAUSTED') {await failEffect(engine, effect, 'embedding_budget_refused'); return;}if (!signal?.aborted && normalizeAIError(error) instanceof AIConfigError) {diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.tsindex 6ad171bc28..7e8d333703 100644--- a/src/core/persistence/git-durability-administration.ts+++ b/src/core/persistence/git-durability-administration.ts@@ -16,7 +16,7 @@* sends agents around the owner, and leave it for the operator to commit.*/import { chmodSync, existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';-import { join } from 'node:path';+import { join, relative } from 'node:path';import { execFileBounded } from '../bounded-child-exec.ts';import { classifyGitCheckout } from '../git-checkout.ts';import { durableSsrfFlags, GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS } from '../git-remote.ts';@@ -34,6 +34,7 @@ import { gitDurabilityPolicy, planGitDurabilityCatchUp, requeueGitDurabilityCatcimport { refusalEnvelope, retryParkedEffects } from './effect-retry.ts';import { GIT_PUSH_CODES } from './git-push-holds.ts';import { patchManagedDurabilityBlock } from '../brain-repo-durability.ts';+import { findResolverFile } from '../resolver-filenames.ts';export const GIT_DURABILITY_PARAMS = ['source_id', 'enable', 'disable', 'pat_file', 'dry_run', 'admin_intent', 'expected_state'] as const;@@ -196,7 +197,18 @@ async function formerWorktreeHolds(engine: BrainEngine, sourceId: string, worktrexport type ParkedPushRefusal = { source_id: string; request_id: string; code: string; message: string; suggestion?: string; fix?: Action };export type ParkedPushRetry = { status: 'ok' | 'partial'; requests: number; queued: number; unchanged: number; refused: ParkedPushRefusal[] };-const REQUEST_REFUSALS = new Set(['permission_denied', 'source_changed', 'write_claim_lost']);+const REQUEST_REFUSALS = new Set(['permission_denied', 'source_changed', 'write_claim_lost', 'page_not_found']);++/**+ * #7110: the stored remote authority can no longer see the request's page (it became private), so the retry's+ * authority check refuses it as page_not_found. That is this request's refusal, not the run's; the trusted local+ * operator gets the slug and the receipt to read instead of the remote writer's non-disclosing message.+ */+function hiddenTargetRefusal(row: { request_id: string; slug: string }): Omit<ParkedPushRefusal, 'source_id' | 'request_id'> {+ return { code: 'page_not_found', message: `Page ${row.slug} is no longer visible to request ${row.request_id}'s original remote writer, so its parked Git effect was not retried under that writer.`,+ suggestion: 'The other parked requests were still retried. This one stays parked: no retry runs it under another authority. Read its receipt, then decide with the brain owner whether the page should be visible to that writer again.',+ fix: readFix(`Reads request ${row.request_id}'s receipt: its source, state and effect outcomes, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] }) };+}/*** #5808(a): after a credential change, one more attempt for every effect of this@@ -211,8 +223,8 @@ const REQUEST_REFUSALS = new Set(['permission_denied', 'source_changed', 'write_* a host or binding problem (`owner_unavailable`) still stops the whole run.*/export async function retryParkedPushes(engine: BrainEngine, worktreeId: string, dryRun: boolean, codes: readonly string[] = GIT_PUSH_CODES): Promise<ParkedPushRetry> {- const rows = await engine.executeRaw<{ source_id: string; id: string; request_id: string }>(`- SELECT DISTINCT e.source_id,r.id::text AS id,r.request_id::text AS request_id FROM persistence_effects e+ const rows = await engine.executeRaw<{ source_id: string; id: string; request_id: string; slug: string }>(`+ SELECT DISTINCT e.source_id,r.id::text AS id,r.request_id::text AS request_id,r.slug FROM persistence_effects eJOIN persistence_requests r ON r.id=e.request_idWHERE e.worktree_id=$1::uuid AND e.kind='git' AND e.state='failed' AND e.recovery IS NULL AND NOT (e.data ? 'settled') AND (${HELD_ON_CODES})ORDER BY e.source_id,request_id,id`, [worktreeId, [...codes]]);@@ -225,7 +237,7 @@ export async function retryParkedPushes(engine: BrainEngine, worktreeId: string,result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun, { internalId: row.id, parkedOnly: true, failedCodes: codes });} catch (error) {if (!(error instanceof OperationError) || !REQUEST_REFUSALS.has(error.code)) throw error;- refused.push({ ...target, ...refusalEnvelope(error) });+ refused.push({ ...target, ...(error.code === 'page_not_found' ? hiddenTargetRefusal(row) : refusalEnvelope(error)) });continue;}if (result?.action === 'owner_revoked') { refused.push({ ...target, ...(result.refusal as ReturnType<typeof refusalEnvelope>) }); continue; }@@ -278,6 +290,8 @@ async function ownedBinding(engine: BrainEngine, sourceId: string): Promise<Work/** The verb. `params` are the raw admin params; the caller has already checked the key set. */export async function runGitDurabilityAdministration(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {const input = parseGitDurabilityParams(params);+ // #7634: approval and the reviewed state are checked before the token is read or the checkout, credential store or parked pushes change.+ const expectedState = await requireWriterAdminIntent(engine, 'writer_git_durability', params);const binding = await ownedBinding(engine, input.sourceId);const root = binding.local_path;const token = input.patFile === undefined ? undefined : readPatFile(input.patFile);@@ -316,7 +330,8 @@ export async function runGitDurabilityAdministration(engine: BrainEngine, params// on this managed root it is replaced with the managed variant (a non-page file: the operator commits it).if (checkout) {const agents = patchManagedDurabilityBlock(root, input.sourceId, input.dryRun);- report.agents = { ...agents, ...(agents.status === 'fixed' && !input.dryRun ? { commit: 'The durability block is a non-page file: review it and commit it with plain git; it rides the owner\'s next push.' } : {}) };+ const file = relative(root, findResolverFile(root) ?? join(root, 'AGENTS.md'));+ report.agents = { ...agents, ...(agents.status === 'fixed' && !input.dryRun ? { commit: `The durability block is a non-page file: review it and commit it with gbrain git commit-push --path ${root} -m "<msg>" -- ${file}; it rides the owner's next push.` } : {}) };}if (input.dryRun) {const state = await writerAdminState(engine);@@ -327,7 +342,6 @@ export async function runGitDurabilityAdministration(engine: BrainEngine, paramsconsent: token ? ['credentials'] : [], actor: 'agent', requires_exclusive: false, why: 'Applies the previewed Git durability change on the owner host.',verify: { argv: ['gbrain', 'sources', 'writer', 'status', input.sourceId, '--json'] } } };}- const expectedState = await requireWriterAdminIntent(engine, 'writer_git_durability', params);const queued = await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('lock_timeout','2000ms',true),set_config('synchronous_commit','on',true)");await assertWriterAdminState(tx, expectedState);diff --git a/src/core/persistence/mirror-read-only.ts b/src/core/persistence/mirror-read-only.tsindex ac930fbe09..21565c97e0 100644--- a/src/core/persistence/mirror-read-only.ts+++ b/src/core/persistence/mirror-read-only.ts@@ -23,10 +23,20 @@ import { urlCloneReadOnly } from '../url-clone.ts';/** `lock`: inside a publication, hold the source row so a concurrent mode change waits for this write. */export async function sourceMirrorReadOnly(engine: SqlEngine, sourceId: string, lock = false): Promise<boolean> {- const [row] = await engine.executeRaw<{ read_only: boolean; local_path: string | null; config: unknown }>(- `SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only, local_path, config FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);- if (!row) return false;- return row.read_only === true || await urlCloneReadOnly(engine, sourceId, row);+ return await readOnlyCheckout(engine, sourceId, lock) !== null;+}++/**+ * Why the source's checkout is never written, or null: `mirror_read_only` (the flag) or `url_clone` (#6946). #7098: the+ * legacy disk writers (write-through, fact fences, timeline, forget, unfenced facts) skip on it as managed publication does.+ */+export async function readOnlyCheckout(engine: SqlEngine, sourceId: string, lock = false): Promise<'mirror_read_only' | 'url_clone' | null> {+ const [row] = await engine.executeRaw<{ local_path: string | null; config: unknown }>(+ `SELECT local_path, config FROM sources WHERE id = $1${lock ? ' FOR SHARE' : ''}`, [sourceId]);+ if (!row) return null;+ const config = typeof row.config === 'string' ? JSON.parse(row.config) as Record<string, unknown> : (row.config ?? {}) as Record<string, unknown>;+ if (String(config.mirror_read_only) === 'true') return 'mirror_read_only';+ return await urlCloneReadOnly(engine, sourceId, row) ? 'url_clone' : null;}/** Marks a page this publication stored database-only because its source is a read-only mirror and it has no recorded file. */diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex 610a82ed13..05daccec41 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -18,7 +18,7 @@ import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from 'import { acquireShared, deferToLease, exclusiveAcquired, foreignWaiterAhead, joinLease, noteWaiting, yieldLease } from './worktree-lease.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { assertPhysicalRoot, claimPhysicalRoot, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';-import { assertPhysicalRootReservation, readPhysicalRootStamp } from './physical-root-record.ts';+import { assertPhysicalRootReservation, readPhysicalRootStamp, relocatedRootTransferFix } from './physical-root-record.ts';import { nativeFilesystemPath } from './root-registry.ts';import { assertWriterAdminState } from './admin-intent.ts';import { readGraduationRow } from './graduation-schema.ts';@@ -234,6 +234,7 @@ async function lockWorktree(binding: WorktreeBinding, waitMs: number, signal: Ab+ `then gbrain sources writer transfer prepare ${binding.source_id} --self-transfer --confirm-relocated-root --admin-intent writer_transfer_prepare --expected-state <admin_state>, `+ `then gbrain sources writer transfer accept ${binding.source_id} --path ${binding.local_path} --expected-epoch ${binding.owner_epoch} --manifest <manifest digest printed by prepare> `+ `--self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <admin_state from a fresh status>. Retry the original write with the same request_id afterwards; never remove the ownership markers.`;+ error.fix = relocatedRootTransferFix(binding.source_id, { root: binding.local_path, epoch: String(binding.owner_epoch) });throw error;}if (!(error instanceof OperationError) || error.detail !== 'physical_root_device_changed') throw error;diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.tsindex 2fa65a99d7..2e1d321449 100644--- a/src/core/persistence/physical-root-record.ts+++ b/src/core/persistence/physical-root-record.ts@@ -3,6 +3,7 @@ import { execFileSync } from '../spawn.ts';import { appendFileSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { OperationError } from '../ops/contract.ts';+import type { Action } from '../agent-output.ts';import { gitChildEnv } from '../git-env.ts';import { flushDirectory } from '../fs-durable.ts';import { digest, sha256 } from './digest.ts';@@ -239,10 +240,29 @@ export function samePhysicalBirth(stored: string | null | undefined, live: biginif (value === 0n || live === 0n) return false;return (value > live ? value - live : live - value) <= PHYSICAL_BIRTH_TOLERANCE_NS;}+const DIRECTORY_CHANGED_MESSAGE = 'The checkout directory at the recorded root is not the one this owner stamped (its inode or birth time changed) while the owner token, brain, worktree, root and device still match. '+ + 'Inspect writer status and use the deliberate self-transfer that confirms a relocated root to re-stamp this same path.';+/** A stored refusal message (a write receipt keeps code and message only) that is the #5914 directory-changed refusal. */+export const isPhysicalRootDirectoryChangedMessage = (message: string | null | undefined): boolean => message === DIRECTORY_CHANGED_MESSAGE;+/**+ * #7671: the relocated-root self-transfer as the refusal's fix, a host-admin step: prepare, then accept. `root` and+ * `epoch` are filled when the caller holds the binding; otherwise they are inputs read from writer status.+ */+export function relocatedRootTransferFix(sourceId: string, binding?: { root: string; epoch: string }): Action {+ const intent = (phase: string) => ['--admin-intent', `writer_transfer_${phase}`, '--expected-state', '<admin_state>'];+ const adminState = { name: 'admin_state', how: `admin_state from gbrain sources writer status ${sourceId} --json on the owner host (read it again before the accept)` };+ const prepare = ['gbrain', 'sources', 'writer', 'transfer', 'prepare', sourceId, '--self-transfer', '--confirm-relocated-root'];+ return { argv: [...prepare, ...intent('prepare')], preview_argv: [...prepare, '--dry-run'], inputs: [adminState], consent: [], actor: 'host_admin', requires_exclusive: false,+ docs: 'docs/guides/write-refusals.md#physical_root_directory_changed',+ why: `Source ${sourceId}'s checkout is a new directory at its recorded path (a restored or copied brain). The self-transfer re-stamps this same path on this host when everything but the directory identity still matches; never remove the ownership markers instead.`,+ then: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'accept', sourceId, '--path', binding?.root ?? '<root>', '--expected-epoch', binding?.epoch ?? '<owner_epoch>',+ '--manifest', '<manifest digest printed by prepare>', '--self-transfer', '--confirm-relocated-root', ...intent('accept')],+ inputs: [adminState, ...(binding ? [] : [{ name: 'root', how: 'the binding root writer status prints' }, { name: 'owner_epoch', how: 'the owner_epoch prepare printed' }])],+ consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Accepts the self-transfer: ownership stays on this host and writes to the source resume; retry the refused write with the same request_id.' } };+}/** The #5914 exit for a directory recreated at its recorded path; filled with the source and root by lockWorktree (ownership.ts). */export function physicalRootDirectoryChangedError(): OperationError {- const error = physicalRootError('The checkout directory at the recorded root is not the one this owner stamped (its inode or birth time changed) while the owner token, brain, worktree, root and device still match. '- + 'Inspect writer status and use the deliberate self-transfer that confirms a relocated root to re-stamp this same path.');+ const error = physicalRootError(DIRECTORY_CHANGED_MESSAGE);error.detail = 'physical_root_directory_changed';error.suggestion = 'On the brain host, run gbrain sources writer status <source> and note admin_state, then gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root '+ '--admin-intent writer_transfer_prepare --expected-state <admin_state>, then gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <manifest digest printed by prepare> 'diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 7cca4eb57b..a7e57c3b6a 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -5,6 +5,7 @@ import { withAdoptedLocalEdit } from './local-edit-adoption.ts';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';+import { isPhysicalRootDirectoryChangedMessage, relocatedRootTransferFix } from './physical-root-record.ts';import { LANE_BUSY, PersistenceConsumer, type PersistenceConsumerLike, type PrepareMutation } from './consumer.ts';import { WaiterOnlyConsumer, type ElectedOwner } from './consumer-election.ts';import { RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat, type ConsumerHeartbeat } from './consumer-heartbeat.ts';@@ -425,6 +426,10 @@ export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: number? pendingWriteHint(receipt, row.operation): delivered?.suggestion ?? content?.suggestion ?? held?.suggestion ?? terminalReceiptHint(row, reason), delivered?.docs);if (delivered?.detail ?? held?.reason) error.detail = delivered?.detail ?? held?.reason;+ // #7671: a copied or restored checkout; the receipt kept only the message, so name the relocated-root self-transfer here.+ if (isTerminal(row) && reason === 'recovery_required' && isPhysicalRootDirectoryChangedMessage(row.error_message)) {+ Object.assign(error, { detail: 'physical_root_directory_changed', fix: relocatedRootTransferFix(row.source_id) });+ }// #6693: a write refused while its page's file awaited import says so, with the wait (remember) or the sync to run first.if (isTerminal(row) && reason === 'source_changed' && (row.error_detail as { origin?: unknown } | null | undefined)?.origin === PENDING_IMPORT) {const pending = pendingImportRefusal(row, row.authority?.remote === true);diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex b9faeb2e8c..218afeb6de 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -67,7 +67,7 @@ import {type PushLogOutcome,} from './brain-repo-durability.ts';import { extractTimelineFromContent } from './timeline-extract.ts';-import { urlCloneReadOnly } from './url-clone.ts';+import { readOnlyCheckout } from './persistence/mirror-read-only.ts';/** Raw op params for one manual timeline entry (date pre-validated by caller). */export interface TimelineEntryWriteInput {@@ -107,6 +107,7 @@ export interface TimelineWriteThroughOutcome {/** Why the FS-canonical path didn't apply (when handled=false). */skipped?:| 'disabled_by_config'+ | 'mirror_read_only'| 'url_clone'| 'no_repo_configured'| 'repo_not_found'@@ -313,9 +314,8 @@ export async function writeTimelineEntryThrough(if (await isWriteThroughDisabled(engine)) {return { handled: false, skipped: 'disabled_by_config' };}- if (await urlCloneReadOnly(engine, sourceId)) {- return { handled: false, skipped: 'url_clone' };- }+ const readOnly = await readOnlyCheckout(engine, sourceId);+ if (readOnly) return { handled: false, skipped: readOnly };const target = await resolvePageWriteTarget(engine, slug, sourceId);if (!target.ok) {return { handled: false, skipped: target.skipped };diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.tsindex f35804c09a..fbd1912d0c 100644--- a/src/core/trust/page-handlers.ts+++ b/src/core/trust/page-handlers.ts@@ -422,7 +422,7 @@ const DATABASE_ONLY_TARGETS = ['no_repo_configured', 'disabled_by_config', 'not_* The checkout file an owner repair mode on an unmanaged brain renders the page to: `target: null` when the page has* none on purpose (DATABASE_ONLY_TARGETS), the bytes the write must still find, or why the page cannot be repaired:* `file_database_drift` when the file holds an edit the database lacks (a hand edit sync has not imported), else the- * unresolvable target (a missing checkout, a path outside the source root) or `url_clone` (a clone gbrain pulls, whose+ * unresolvable target (a missing checkout, a path outside the source root), `mirror_read_only` or `url_clone` (a mirror or a clone gbrain pulls, whose* next pull would undo a database-only repair). Read-only.*/export async function ownerRepairFile(engine: BrainEngine, sourceId: string, slug: string):@@ -430,8 +430,9 @@ export async function ownerRepairFile(engine: BrainEngine, sourceId: string, sluconst { derivedFileTarget } = await import('../cycle/derived-write-through.ts');const resolved = await derivedFileTarget(engine, slug, sourceId);if (!resolved.ok) return DATABASE_ONLY_TARGETS.includes(resolved.skipped) ? { ok: true, target: null } : { ok: false, reason: resolved.skipped };- const { urlCloneReadOnly } = await import('../url-clone.ts');- if (await urlCloneReadOnly(engine, sourceId)) return { ok: false, reason: 'url_clone' };+ const { readOnlyCheckout } = await import('../persistence/mirror-read-only.ts');+ const readOnly = await readOnlyCheckout(engine, sourceId);+ if (readOnly) return { ok: false, reason: readOnly };const { replaceableFile } = await import('../facts/file-body-guard.ts');const file = await replaceableFile(engine, sourceId, slug, resolved.target.filePath);return file.ok ? { ok: true, target: { expectedFileBytes: file.expectedFileBytes, writeRoot: resolved.target.writeRoot } } : { ok: false, reason: 'file_database_drift' };diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex 8fbf9b6d1e..37a4bb28c8 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -40,7 +40,7 @@ import {type PushLogOutcome,} from './brain-repo-durability.ts';import { bindOrigin } from './persistence/origin-guard.ts';-import { urlCloneReadOnly } from './url-clone.ts';+import { readOnlyCheckout } from './persistence/mirror-read-only.ts';/** Minimal logger surface — structurally compatible with operations.ts `Logger`. */export interface WriteThroughLogger {@@ -102,8 +102,10 @@ export interface WriteThroughResult {* the edit is kept and nothing is written.* - over_push_scan_cap: the rendered file is over the pre-push secret-scan* cap (PUSH_SCAN_MAX_FILE_BYTES), so committing it would block every push.+ * - mirror_read_only / url_clone: the source is a read-only mirror (#5409,+ * #7098) or a clone gbrain owns and pulls (#6946); its checkout is never written.*/- skipped?: 'disabled_by_config' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page';+ skipped?: 'disabled_by_config' | 'mirror_read_only' | 'url_clone' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed' | 'over_push_scan_cap' | 'segmented_page';/** Caller-visible advisory when a permitted DB-only outcome is still risky. */warning?: string;/** Set when the render/write/rename itself threw (EACCES, ENOTDIR, disk full). */@@ -445,7 +447,8 @@ export async function resolvePageWriteTarget(* `sync.repo_path`. Never throws — failures are reported via the result's* `skipped` / `error` fields. put_page calls it before its transaction commits* and rejects non-deliberate skips so a file failure rolls back the DB write.- * A clone gbrain owns on an unmanaged brain is skipped (`url_clone`, #6946).+ * A read-only mirror source is skipped (`mirror_read_only`, #7098), and so is a+ * clone gbrain owns on an unmanaged brain (`url_clone`, #6946).*/export async function writePageThrough(engine: BrainEngine,@@ -462,9 +465,8 @@ export async function writePageThrough(if (await isWriteThroughDisabled(engine)) {return { written: false, skipped: 'disabled_by_config' };}- if (await urlCloneReadOnly(engine, sourceId)) {- return { written: false, skipped: 'url_clone' };- }+ const readOnly = await readOnlyCheckout(engine, sourceId);+ if (readOnly) return { written: false, skipped: readOnly };const target = await resolvePageWriteTarget(engine, slug, sourceId);if (!target.ok) {return { written: false, skipped: target.skipped };@@ -628,13 +630,13 @@ export interface DeleteThroughResult {* Non-error reasons nothing was removed. Shares the target-resolution skip* vocabulary (kept in lockstep via the Extract), plus:* - disabled_by_config: the operator opted the brain out of the disk sink.- * - url_clone: the source is a clone gbrain owns and pulls (#6946); its checkout is never written.+ * - mirror_read_only / url_clone: the source is a read-only mirror (#7098) or a clone gbrain owns and pulls (#6946); its checkout is never written.* - file_not_present: the page had no artifact on disk (DB-only page, or* already removed by hand) — a clean no-op, not a failure.* - file_changed: the caller passed `expectedFileBytes` and the file no* longer holds them (an edit landed after the caller read it) — kept.*/- skipped?: 'disabled_by_config' | 'url_clone' | 'file_not_present' | 'file_changed' | Extract<PageWriteTarget, { ok: false }>['skipped'];+ skipped?: 'disabled_by_config' | 'mirror_read_only' | 'url_clone' | 'file_not_present' | 'file_changed' | Extract<PageWriteTarget, { ok: false }>['skipped'];/** Set when the unlink itself threw (EACCES, EPERM, read-only mount). */error?: string;}@@ -679,9 +681,8 @@ export async function deletePageThrough(if (await isWriteThroughDisabled(engine)) {return { removed: false, skipped: 'disabled_by_config' };}- if (await urlCloneReadOnly(engine, sourceId)) {- return { removed: false, skipped: 'url_clone' };- }+ const readOnly = await readOnlyCheckout(engine, sourceId);+ if (readOnly) return { removed: false, skipped: readOnly };const target = opts.target ?? await resolvePageWriteTarget(engine, slug, sourceId);if (!target.ok) return { removed: false, skipped: target.skipped };const { filePath, writeRoot } = target;diff --git a/test/durability-block-managed-5808.test.ts b/test/durability-block-managed-5808.test.tsindex d919694fab..e95b197300 100644--- a/test/durability-block-managed-5808.test.ts+++ b/test/durability-block-managed-5808.test.ts@@ -105,7 +105,7 @@ describe('the managed durability block (#5808)', () => {const applied = await runPersistenceAdministration(engine, 'writer_git_durability', { source_id: sourceId, enable: true, ...await reviewedWriterIntent(engine, 'writer_git_durability') });expect(applied).toMatchObject({ applied: true, git_durability: { before: null, after: 'enabled' },- agents: { status: 'fixed', detail: expect.stringContaining('durability rules written'), commit: expect.stringContaining('plain git') } });+ agents: { status: 'fixed', detail: expect.stringContaining('durability rules written'), commit: expect.stringContaining(`gbrain git commit-push --path ${root} -m "<msg>" -- AGENTS.md`) } });const after = readFileSync(agents, 'utf8');for (const marker of CLASSIC) expect(block(after)).not.toContain(marker);expect(block(after)).toContain(`gbrain sources writer git-durability ${sourceId} --enable`);diff --git a/test/e2e/git-durability-refused-apply-7634.test.ts b/test/e2e/git-durability-refused-apply-7634.test.tsnew file mode 100644index 0000000000..da99dc06fb--- /dev/null+++ b/test/e2e/git-durability-refused-apply-7634.test.ts@@ -0,0 +1,113 @@+/**+ * #7634 on PostgreSQL: a refused `writer git-durability --enable --pat-file` apply (no approval, the wrong+ * intent, or a stale reviewed state) changes no file in the checkout, its .git config or the credential store,+ * and leaves the parked push and the binding as they were. The PGLite arm is in+ * test/persistence-admin-git-durability.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';+import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';+import { localHostId, registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { submissionAuthority } from '../../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite } from '../../src/core/persistence/journal.ts';+import { publishMutation } from '../../src/core/persistence/coordinator.ts';+import { serializePageToMarkdown } from '../../src/core/markdown.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { gitAsync } from '../helpers/git-publication.ts';+import { withEnv } from '../helpers/with-env.ts';+import { reviewedWriterIntent } from '../helpers/writer-admin-intent.ts';++const run = process.env.DATABASE_URL ? test : test.skip;+let engine: PostgresEngine;+let close: (() => Promise<void>) | undefined;+const roots: string[] = [];+const config = { engine: 'postgres' as const, embedding_disabled: true };+const page = (body: string) => ({ type: 'note', title: 'Example', compiled_truth: body, timeline: '', frontmatter: {} });+beforeAll(async () => {+ if (!process.env.DATABASE_URL) return;+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL));+}, 120_000);+afterAll(async () => {+ if (engine) await disposePersistenceConsumer(engine);+ await close?.();+ for (const root of roots) rmSync(root, { recursive: true, force: true });+});++function treeBytes(dir: string, files: Record<string, string> = {}): Record<string, string> {+ for (const name of readdirSync(dir).sort()) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) treeBytes(path, files);+ else files[path] = createHash('sha256').update(readFileSync(path)).digest('hex');+ }+ return files;+}++async function parkedSource(home: string) {+ const root = join(home, 'root'); mkdirSync(root);+ const remote = join(home, 'remote.git'); mkdirSync(remote);+ await gitAsync(remote, 'init', '-q', '--bare');+ await gitAsync(root, 'init', '-q', '-b', 'main');+ await gitAsync(root, 'config', 'user.name', 'Example Writer');+ await gitAsync(root, 'config', 'user.email', '[email protected]');+ writeFileSync(join(root, 'AGENTS.md'), '# Operator instructions\n');+ await gitAsync(root, 'add', 'AGENTS.md'); await gitAsync(root, 'commit', '-q', '-m', 'Instructions');+ await gitAsync(root, 'remote', 'add', 'origin', remote); await gitAsync(root, 'push', '-q', '-u', 'origin', 'main');+ const sourceId = `durability-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ const binding = await claimWorktree(engine, sourceId, root, localHostId());+ const slug = 'parked7634';+ await engine.putPage(slug, page('Before'), { sourceId });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const file = join(root, `${slug}.md`);+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ const ctx: OperationContext = { engine, config, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } };+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, binding.source_incarnation, slug);+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,+ sourceIncarnation: binding.source_incarnation, slug, pageId: snapshot.page.id, requestId: randomUUID(),+ callerIntent: { content: 'After' }, intent: { content: 'After' }, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ const row = (await claimNextWrite(engine, localHostId()))!;+ const result = await publishMutation(engine, row, { observedRevision: snapshot.revision, file: { path: file, root, content: 'After' },+ apply: async tx => { await tx.putPage(slug, page('After'), { sourceId }); return {}; } }, localHostId());+ expect(result.state).toBe('committed');+ await engine.executeRaw(`UPDATE persistence_effects SET state='failed',error_code='targets_parked',data=data || $2::text::jsonb+ WHERE request_id=$1::uuid AND kind='git'`, [row.id, JSON.stringify({ parked: [{ slug, error_code: 'git_push_unavailable' }], target_failures: 5 })]);+ return { sourceId, requestId: row.id };+}++const gitEffect = async (requestId: string) => (await engine.executeRaw<Record<string, unknown>>(+ "SELECT state,error_code,attempts,data,outcome FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [requestId]))[0];++describe('#7634 a refused git-durability apply has no side effects (PostgreSQL)', () => {+ for (const refusal of ['missing', 'wrong', 'stale'] as const) {+ run(`${refusal} approval`, async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-durability-7634-')); roots.push(home);+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1' }, async () => {+ await registerLocalWriter(engine, 'cli');+ try {+ const { sourceId, requestId } = await parkedSource(home);+ const token = join(home, 'synthetic-token');+ writeFileSync(token, 'synthetic-test-only-token\n', { mode: 0o600 });+ const reviewed = await reviewedWriterIntent(engine, 'writer_git_durability');+ if (refusal === 'stale') await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [`other-${randomUUID().slice(0, 8)}`]);+ const params = { source_id: sourceId, enable: true, pat_file: token,+ ...(refusal === 'missing' ? {} : refusal === 'wrong' ? { ...reviewed, admin_intent: 'writer_activate' } : reviewed) };+ const before = treeBytes(home);+ const effect = await gitEffect(requestId);+ const error = await runPersistenceAdministration(engine, 'writer_git_durability', params).catch(caught => caught);+ expect(error).toMatchObject({ code: refusal === 'stale' ? 'writer_admin_state_changed' : 'writer_admin_intent_required' });+ expect(treeBytes(home)).toEqual(before);+ expect(await gitEffect(requestId)).toEqual(effect);+ expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBeNull();+ } finally { await disposePersistenceConsumer(engine); }+ });+ }, 120_000);+ }+});diff --git a/test/mirror-readonly-write-through-7098.test.ts b/test/mirror-readonly-write-through-7098.test.tsnew file mode 100644index 0000000000..2953fdecbc--- /dev/null+++ b/test/mirror-readonly-write-through-7098.test.ts@@ -0,0 +1,161 @@+/**+ * #7098: `gbrain sources mirror-readonly <id>` (#5409) was honored by managed+ * publication but not by the legacy disk writers. On an unmanaged brain,+ * `sync --full` re-exported never-committed database pages into the mirror's+ * checkout, `brainstorm --save` wrote its page file there, and the fact fence,+ * timeline, unfenced-fact and forget writers rewrote its files, so the mirror+ * gained local changes and its `git pull --ff-only` could stop.+ *+ * Protects: every legacy writer treats a mirror-readonly source like a clone+ * gbrain owns (#6946): the database write lands, the checkout is untouched+ * (no modified or untracked file), and the outcome names `mirror_read_only`.+ * Seams: a plain git checkout registered as a source on an unmanaged brain,+ * imported with the real sync, then flagged with the real `mirror-readonly`+ * command. PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runMirrorMode } from '../src/commands/sources-mirror.ts';+import { formatSaveOutcome, persistSavedIdea } from '../src/commands/brainstorm.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { deletePageThrough, writePageThrough, _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';+import { writeTimelineEntryThrough } from '../src/core/timeline-write-through.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { forgetFactInFence } from '../src/core/facts/forget.ts';+import { fenceUnfencedFacts, planUnfencedFacts } from '../src/core/facts/unfenced-facts.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;+const SOURCE = 'source-a';+const ALICE = 'people/alice-example';+const ALICE_MD = '---\ntype: person\ntitle: Alice Example\n---\n\n# Alice Example\n\nAlice Example works at Acme Example.\n';+const git = (dir: string, args: string[]) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+const quiet = async <T>(run: () => Promise<T>): Promise<{ value: T; stderr: string }> => {+ const lines: string[] = [];+ const log = console.log, error = console.error, warn = console.warn, write = process.stderr.write.bind(process.stderr);+ console.log = () => {}; console.error = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); }; console.warn = console.error;+ (process.stderr as unknown as { write: (c: unknown) => boolean }).write = (c: unknown) => { lines.push(String(c)); return true; };+ try { return { value: await run(), stderr: lines.join('\n') }; }+ finally { console.log = log; console.error = error; console.warn = warn; process.stderr.write = write; }+};++for (const flavor of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const) describe(`mirror-readonly legacy disk writers (${flavor})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (flavor === 'postgres') {+ const fixture = await isolatedPersistencePostgres(databaseUrl!);+ engine = fixture.engine; closePostgres = fixture.close;+ } else {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ }+ }, 120_000);+ afterAll(async () => { if (closePostgres) await closePostgres(); else await engine?.disconnect(); });++ interface Mirror { root: string; alice: string; status(): string; sync(full?: boolean): Promise<string>; readOnly(): Promise<void> }+ async function withMirror(run: (m: Mirror) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-mirror-7098-'));+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ await resetPgliteState(engine as PGLiteEngine);+ const root = join(dir, 'mirror');+ mkdirSync(join(root, 'people'), { recursive: true });+ git(root, ['init', '-q', '-b', 'main']);+ git(root, ['config', 'user.email', '[email protected]']);+ git(root, ['config', 'user.name', 't']);+ writeFileSync(join(root, `${ALICE}.md`), ALICE_MD);+ git(root, ['add', '-A']);+ git(root, ['commit', '-q', '-m', 'initial']);+ await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', [SOURCE, root]);+ const m: Mirror = {+ root, alice: join(root, `${ALICE}.md`),+ status: () => git(root, ['status', '--porcelain', '--untracked-files=all']).trim(),+ async sync(full = false) {+ const { performSync } = await import('../src/commands/sync.ts');+ return (await quiet(() => performSync(engine, { sourceId: SOURCE, repoPath: root, noEmbed: true, noExtract: true, noPull: true, full }))).stderr;+ },+ readOnly: async () => { await quiet(() => runMirrorMode(engine, [SOURCE], true)); },+ };+ await m.sync();+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1', [SOURCE])).toEqual([{ slug: ALICE }]);+ await run(m);+ });+ } finally { rmSync(dir, { recursive: true, force: true }); }+ }++ test('writePageThrough and deletePageThrough skip a mirror-readonly checkout with mirror_read_only', () => withMirror(async m => {+ await m.readOnly();+ expect(await writePageThrough(engine, ALICE, { sourceId: SOURCE })).toEqual({ written: false, skipped: 'mirror_read_only' });+ await importFromContent(engine, 'notes/db-only', '---\ntype: note\ntitle: DB only\n---\n\nOnly in the database.\n', { noEmbed: true, sourceId: SOURCE });+ expect(await writePageThrough(engine, 'notes/db-only', { sourceId: SOURCE, expectedFileBytes: null })).toEqual({ written: false, skipped: 'mirror_read_only' });+ expect(await deletePageThrough(engine, ALICE, { sourceId: SOURCE })).toEqual({ removed: false, skipped: 'mirror_read_only' });+ expect(readFileSync(m.alice, 'utf8')).toBe(ALICE_MD);+ expect(m.status()).toBe('');+ }), 60_000);++ test('sync --full keeps a never-committed database page in the database and out of the mirror', () => withMirror(async m => {+ await importFromContent(engine, 'notes/db-only', '---\ntype: note\ntitle: DB only\n---\n\nOnly in the database.\n', { noEmbed: true, sourceId: SOURCE, sourcePath: 'notes/db-only.md' });+ await m.readOnly();+ const stderr = await m.sync(true);+ expect(existsSync(join(m.root, 'notes/db-only.md'))).toBe(false);+ expect(m.status()).toBe('');+ expect(stderr).not.toContain('re-export failure');+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [SOURCE])).toEqual([{ slug: 'notes/db-only' }, { slug: ALICE }]);+ }), 60_000);++ test('brainstorm --save stores the idea database-only and names the mirror', () => withMirror(async m => {+ await m.readOnly();+ const outcome = await persistSavedIdea(engine, { slug: 'ideas/acme-example', content: '---\ntype: idea\ntitle: Acme Example idea\n---\n\nAn idea.\n', sourceId: SOURCE, provenanceVia: 'brainstorm' });+ expect(outcome).toMatchObject({ dbSaved: true, writeThrough: { written: false, skipped: 'mirror_read_only' } });+ expect(existsSync(join(m.root, 'ideas/acme-example.md'))).toBe(false);+ expect(m.status()).toBe('');+ const message = formatSaveOutcome(outcome, { profileLabel: 'brainstorm', slug: 'ideas/acme-example' });+ expect(message.exitCode).toBe(0);+ expect(message.stdout).toContain('read-only mirror');+ expect(message.stdout).not.toContain('file NOT written');+ }), 60_000);++ test('a timeline entry and a fact land database-only and leave the page file alone', () => withMirror(async m => {+ await m.readOnly();+ const timeline = await writeTimelineEntryThrough(engine, ALICE, SOURCE, { date: '2026-10-01', summary: 'Joined Acme Example.' });+ expect(timeline).toMatchObject({ handled: false, skipped: 'mirror_read_only' });+ const fact = await writeSingleFact(engine, SOURCE, { fact: 'Alice Example leads the platform team at Acme Example.', provenance: 'test:7098', entity: ALICE, visibility: 'world', remote: false });+ const [row] = await engine.executeRaw<{ row_num: number | null }>('SELECT row_num FROM facts WHERE id=$1', [fact.id]);+ expect(row.row_num).toBeNull();+ expect(readFileSync(m.alice, 'utf8')).toBe(ALICE_MD);+ expect(m.status()).toBe('');+ }), 60_000);++ test('forget of a fenced fact expires it in the database without rewriting the mirror file', () => withMirror(async m => {+ const fact = await writeSingleFact(engine, SOURCE, { fact: 'Alice Example leads the platform team at Acme Example.', provenance: 'test:7098', entity: ALICE, visibility: 'world', remote: false });+ expect(readFileSync(m.alice, 'utf8')).toContain('Alice Example leads the platform team');+ git(m.root, ['commit', '-q', '-am', 'fence']);+ const fenced = readFileSync(m.alice, 'utf8');+ await m.readOnly();+ expect(await forgetFactInFence(engine, fact.id, { reason: 'test' })).toMatchObject({ ok: true, path: 'legacy_db' });+ expect((await engine.executeRaw<{ expired: boolean }>('SELECT expired_at IS NOT NULL AS expired FROM facts WHERE id=$1', [fact.id]))[0].expired).toBe(true);+ expect(readFileSync(m.alice, 'utf8')).toBe(fenced);+ expect(m.status()).toBe('');+ }), 60_000);++ test('unfenced fact rows of a mirror stay database-only, and the extract guard does not count them', () => withMirror(async m => {+ await m.readOnly();+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)+ VALUES ($1, $2, 'Alice Example ships the Acme Example search stack.', 'fact', 'world', 'medium', now(), 'test:7098', 1.0)`, [SOURCE, ALICE]);+ const outcome = await fenceUnfencedFacts(engine, await planUnfencedFacts(engine, { sourceId: SOURCE }));+ expect(outcome).toMatchObject({ fenced: 0, skipped_mirror_read_only: 1 });+ const result = await runExtractFacts(engine, { sourceId: SOURCE, slugs: [ALICE] });+ expect(result).toMatchObject({ guardTriggered: false, legacyRowsPending: 0, unfencedRowsFenced: 0 });+ expect(readFileSync(m.alice, 'utf8')).toBe(ALICE_MD);+ expect(m.status()).toBe('');+ }), 60_000);+});diff --git a/test/parked-push-retry-6678.test.ts b/test/parked-push-retry-6678.test.tsindex 3038b9c94c..f15df3ab2a 100644--- a/test/parked-push-retry-6678.test.ts+++ b/test/parked-push-retry-6678.test.ts@@ -247,6 +247,31 @@ describe('#6697 revoked writer: parked Git effect', () => {}), 120_000);});+describe('#7110 a remote writer that can no longer see its page', () => {+ test('bulk retry refuses only that request, names its request id, and still retries the healthy push', () => isolated(async home => {+ const root = await gitRoot(home);+ const { sourceId } = await claimedSource(root);+ await registerLocalWriter(engine, 'stdio');+ const hidden = await parked(root, sourceId, 'hidden7110', { remote: true });+ const current = (await engine.getPage('hidden7110', { sourceId }))!;+ await engine.putPage('hidden7110', { ...current, frontmatter: { ...current.frontmatter, visibility: 'private' } }, { sourceId });+ await registerLocalWriter(engine, 'cli', undefined, true);+ const healthy = await parked(root, sourceId, 'healthy7110');+ const before = await gitOutcome(hidden);+ const refusal = { source_id: sourceId, request_id: await publicId(hidden), code: 'page_not_found',+ message: expect.stringContaining('hidden7110'), fix: expect.objectContaining({ argv: ['gbrain', 'write-request', '--', await publicId(hidden)] }) };+ const preview = await runPersistenceAdministration(engine, 'writer_retry_effects', { source_id: sourceId, parked_pushes: true, dry_run: true });+ expect(preview).toMatchObject({ status: 'partial', requests: 2, queued: 1, unchanged: 0 });+ expect(preview.refused).toEqual([expect.objectContaining(refusal)]);+ expect(await gitOutcome(healthy)).toMatchObject({ state: 'failed' });+ const applied = await runPersistenceAdministration(engine, 'writer_retry_effects', { source_id: sourceId, parked_pushes: true });+ expect(applied).toMatchObject({ status: 'partial', requests: 2, queued: 1, unchanged: 0 });+ expect(applied.refused).toEqual(preview.refused);+ expect(await gitOutcome(hidden)).toEqual(before);+ expect(await gitOutcome(healthy)).toMatchObject({ state: 'queued', data: { retried: 1 } });+ }), 120_000);+});+describe('#6665 doctor parked_effects', () => {test('names the fix for a parked git_target_pending target', () => isolated(async home => {const root = await gitRoot(home);diff --git a/test/persistence-admin-git-durability.test.ts b/test/persistence-admin-git-durability.test.tsindex 6b74345306..5cf94d7b09 100644--- a/test/persistence-admin-git-durability.test.ts+++ b/test/persistence-admin-git-durability.test.ts@@ -12,8 +12,8 @@* `--pat-file` refuses a readable token file before writing anything.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import { randomUUID } from 'node:crypto';-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { createHash, randomUUID } from 'node:crypto';+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -102,6 +102,15 @@ async function gitOutcome(requestId: string) {"SELECT state,outcome,data FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [requestId]);return row;}+/** Every file under the private home: the checkout, its .git (config, index, refs) and the credential store. */+function treeBytes(dir: string, files: Record<string, string> = {}): Record<string, string> {+ for (const name of readdirSync(dir).sort()) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) treeBytes(path, files);+ else files[path] = createHash('sha256').update(readFileSync(path)).digest('hex');+ }+ return files;+}async function runEffects() {await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git'");await runPersistenceEffects(engine, config, { hostId: localHostId(), limit: 10 });@@ -227,6 +236,31 @@ describe('[R7ii] writer git-durability verb', () => {expect(again).toMatchObject({ catch_up: { planned: 0 }, why: expect.stringContaining('already as requested') });}), 120_000);+ for (const refusal of ['missing', 'wrong', 'stale'] as const) {+ test(`#7634 a refused apply (${refusal} approval) leaves the checkout, the credential store and the parked push unchanged`, () => isolated(async home => {+ const root = await gitRoot(home, { remote: true });+ writeFileSync(join(root, 'AGENTS.md'), '# Operator instructions\n');+ await gitAsync(root, 'add', 'AGENTS.md'); await gitAsync(root, 'commit', '-q', '-m', 'Instructions'); await gitAsync(root, 'push', '-q');+ const { sourceId } = await claimedSource(root);+ const id = await committedWrite(root, sourceId, 'parked7634');+ await engine.executeRaw(`UPDATE persistence_effects SET state='failed',error_code='targets_parked',data=data || $2::text::jsonb+ WHERE request_id=$1::uuid AND kind='git'`, [id, JSON.stringify({ parked: [{ slug: 'parked7634', error_code: 'git_push_unavailable' }], target_failures: 5 })]);+ const token = join(home, 'synthetic-token');+ writeFileSync(token, 'synthetic-test-only-token\n', { mode: 0o600 });+ const reviewed = await reviewedWriterIntent(engine, 'writer_git_durability');+ if (refusal === 'stale') await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [`other-${randomUUID().slice(0, 8)}`]);+ const params = { source_id: sourceId, enable: true, pat_file: token,+ ...(refusal === 'missing' ? {} : refusal === 'wrong' ? { ...reviewed, admin_intent: 'writer_activate' } : reviewed) };+ const before = treeBytes(home);+ const effect = await gitOutcome(id);+ const error = await runPersistenceAdministration(engine, 'writer_git_durability', params).catch(caught => caught);+ expect(error).toMatchObject({ code: refusal === 'stale' ? 'writer_admin_state_changed' : 'writer_admin_intent_required' });+ expect(treeBytes(home)).toEqual(before);+ expect(await gitOutcome(id)).toEqual(effect);+ expect((await getWorktreeBinding(engine, sourceId, localHostId()))!.git_durability).toBeNull();+ }), 120_000);+ }+test('--disable wins over a legacy hook: the next Git effect completes as skipped; --pat-file refuses a readable token file first', () => isolated(async home => {const root = await gitRoot(home);const hook = join(root, '.git', 'hooks', 'post-commit');diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.tsindex 8c0d6e95aa..38ca7a5cbe 100644--- a/test/persistence-crash-robot.test.ts+++ b/test/persistence-crash-robot.test.ts@@ -251,6 +251,37 @@ describe('injected session drops', () => {});}, 120_000);+ // #7651: a projection check whose page read failed compared an empty fence with the fact rows and reported+ // projection_drift (seed 5105, pooler_disconnect). A failed read of a live page is a read failure, never an empty page.+ test('a failed page read in the projection check is a read failure with its error, not projection drift', async () => {+ await robotBrain(async ({ world }) => {+ const source = world.remotes[0].sourceId;+ const model = new ReferenceModel(world);+ const put = descriptor('put', 'put_page', 'local', source, { slug: 'notes/alpha', content: pageBody('notes/alpha', 'mk-put0') });+ const fact = descriptor('fact', 'remember', 'local', source, { fact: 'Alpha fact mk-fact0', entity: 'notes/alpha' });+ world.descriptors = new Map([put, fact].map(d => [d.id, d]));+ for (const d of [put, fact]) {+ const seen = await executeOp(world, d);+ expect(seen.status).toBe('committed');+ model.beginStep(false);+ await model.observe(d, seen);+ }+ await model.checkGlobal('before the failed read');+ expect(model.violations).toEqual([]);++ const engine = world.engine;+ const read = engine.readPageSnapshot;+ engine.readPageSnapshot = (async (slug: string, ...rest: never[]) => {+ if (slug === 'notes/alpha') throw Object.assign(new Error('storage read failed mid-drop'), { code: 'storage_unavailable' });+ return read.call(engine, slug, ...rest);+ }) as typeof read;+ try { await model.checkGlobal('after ov6'); } finally { engine.readPageSnapshot = read; }+ expect(model.violations.map(v => v.class)).toEqual(['read_failure']);+ expect(model.violations[0].detail).toContain(`after ov6: get_page of live page ${source}/notes/alpha failed`);+ expect(model.violations[0].detail).toContain('storage read failed mid-drop');+ });+ }, 120_000);+test('a drop round counts once it terminated a session, including a round still in flight', async () => {const drops = new SessionDrops();expect(await drops.injectedBefore()).toBe(false);diff --git a/test/persistence-embedding-effects.test.ts b/test/persistence-embedding-effects.test.tsindex 60cad019d8..9aa0d259df 100644--- a/test/persistence-embedding-effects.test.ts+++ b/test/persistence-embedding-effects.test.ts@@ -262,6 +262,36 @@ for (const kind of testBackends()) {expect(await state(f.effectId)).toMatchObject({ state: 'failed', attempts: 1, error_code: 'embedding_budget_refused' });});+ check('#7772 a stop signal that fires in the invocation preflight retries as embedding_aborted, not budget-refused', async () => {+ const f = await fixture();+ const controller = new AbortController();+ let calls = 0;+ let failure: unknown;+ await run(async () => {+ controller.abort(new Error('consumer stopped'));+ try { return await invokeAI({ operation: 'embed', kind: 'embedding', model }, async () => { calls++; return vectors(); }, () => null); }+ catch (error) { failure = error; throw error; }+ }, controller.signal);+ expect(calls).toBe(0);+ expect(isAIInvocationPolicyError(failure)).toBe(true);+ expect(await state(f.effectId)).toMatchObject({ state: 'queued', attempts: 1, error_code: 'embedding_aborted' });+ await due(f.effectId);+ await run(async () => { calls++; return vectors(); });+ expect(calls).toBe(1);+ expect(await state(f.effectId)).toMatchObject({ state: 'committed', attempts: 2 });+ });++ check('#7772 a real admission refusal while the stop signal is live still fails as budget-refused', async () => {+ const f = await fixture();+ const controller = new AbortController();+ let calls = 0;+ await withAIInvocationGuard(async () => { throw new Error('budget refused'); }, () => run(async () =>+ invokeAI({ operation: 'embed', kind: 'embedding', model }, async () => { calls++; return vectors(); }, () => null), controller.signal));+ expect(controller.signal.aborted).toBe(false);+ expect(calls).toBe(0);+ expect(await state(f.effectId)).toMatchObject({ state: 'failed', attempts: 1, error_code: 'embedding_budget_refused' });+ });+check('rate-limit failures retain the existing provider-hint backoff', async () => {const f = await fixture();await run(async () => { throw Object.assign(new Error('Please try again in 120s'), { status: 429 }); });diff --git a/test/physical-root-copied-brain-fix-7671.test.ts b/test/physical-root-copied-brain-fix-7671.test.tsnew file mode 100644index 0000000000..913e935ec5--- /dev/null+++ b/test/physical-root-copied-brain-fix-7671.test.ts@@ -0,0 +1,98 @@+/**+ * #7671: on a brain copied as a directory (baked into an image, restored from+ * a file-level backup) every source root is a new directory at its recorded+ * path, so every managed write refuses `recovery_required` (detail+ * `physical_root_directory_changed`). The refusal named the relocated-root+ * self-transfer only in prose; `fix` pointed at the write receipt, so an agent+ * following `fix.next` read the receipt and never reached the exit.+ *+ * Protects: the refusal's `fix` is the relocated-root self-transfer for+ * that source (`transfer prepare <source> --self-transfer --confirm-relocated-root`,+ * a host-admin step, then the accept), both on the worktree lock (root and+ * epoch filled in) and on a put_page receipt rendered for the agent; the refusal+ * itself stays (nothing is re-stamped), and the named command restores writes.+ * Seams: the 6501 fixture: a managed source whose directory is replaced by a+ * copy at the same path (new inode and birth time, same device). PGLite always,+ * Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { renderCliError } from '../src/core/agent-output.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { PHYSICAL_ROOT_MARKER } from '../src/core/persistence/physical-root-record.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const readJson = (path: string) => JSON.parse(readFileSync(path, 'utf8'));+const PREPARE = (source: string) => ['gbrain', 'sources', 'writer', 'transfer', 'prepare', source, '--self-transfer', '--confirm-relocated-root'];++for (const kind of testBackends()) describe(`copied brain names the relocated-root self-transfer in fix (${kind})`, () => {+ const directory = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-copied-root-')));+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: directory }, () => disposePersistenceConsumer(engine));+ if (close) await close(); else await engine.disconnect();+ rmSync(directory, { recursive: true, force: true });+ });++ test('the worktree lock and a put_page receipt carry the filled self-transfer as fix; running it restores writes', async () => {+ const home = join(directory, randomUUID()), root = join(home, 'root'); mkdirSync(root, { recursive: true });+ const source = `copied-${randomUUID().slice(0, 8)}`;+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ await claimWorktree(engine, source, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const registration = await registerLocalWriter(engine, 'cli');+ const ctx: OperationContext = { engine, remote: false, sourceId: source, config: { engine: engine.kind, embedding_disabled: true } as never,+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ const put = (slug: string) => withVerifiedLocalRegistration(engine, registration, () =>+ operationsByName.put_page!.handler(ctx, { source_id: source, slug, request_id: randomUUID(),+ content: '---\ntype: note\ntitle: Example\n---\nA managed observation.\n' }));+ expect(await put('notes/before-copy')).toMatchObject({ state: 'committed' });+ const binding = (await getWorktreeBinding(engine, source))!;+ await disposePersistenceConsumer(engine);+ const previous = `${root}.previous`;+ renameSync(root, previous); mkdirSync(root); cpSync(previous, root, { recursive: true }); rmSync(previous, { recursive: true, force: true });+ expect(statSync(root, { bigint: true }).ino.toString()).not.toBe(readJson(join(root, PHYSICAL_ROOT_MARKER)).inode);++ const locked = await acquireWorktree(binding, 5000, undefined, engine).then(lock => lock?.release().then(() => null) ?? null,+ (error: unknown) => error as { code: string; detail?: string; fix?: { argv?: string[]; actor?: string; then?: { argv?: string[] } } });+ expect(locked).toMatchObject({ code: 'recovery_required', detail: 'physical_root_directory_changed' });+ expect(locked!.fix?.argv?.slice(0, 8)).toEqual(PREPARE(source));+ expect(locked!.fix?.actor).toBe('host_admin');+ expect(locked!.fix?.then?.argv).toEqual(expect.arrayContaining(['accept', source, '--path', root, '--expected-epoch', String(binding.owner_epoch), '--confirm-relocated-root']));++ const refused = await put('notes/while-copied').then(() => null, (error: unknown) => error);+ expect(refused).not.toBeNull();+ const envelope = JSON.parse(renderCliError(refused, { json: true, command: 'put', tty: false }).stdout ?? '') as { code: string; fix?: { argv?: string[]; command?: string; next?: string } };+ expect(envelope.code).toBe('recovery_required');+ expect(envelope.fix?.argv?.slice(0, 8)).toEqual(PREPARE(source));+ expect(envelope.fix?.command).toContain(`transfer prepare ${source} --self-transfer --confirm-relocated-root`);+ expect(envelope.fix?.next).toBe('tell_user_to_run');++ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) });+ const prepared = await administer('writer_transfer_prepare', { source_id: source, self_transfer: true, confirm_relocated_root: true }) as { owner_epoch: string; manifest: { digest: string } };+ expect(prepared.owner_epoch).toBe(String(binding.owner_epoch));+ await administer('writer_transfer_accept', { source_id: source, path: root, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest, self_transfer: true, confirm_relocated_root: true });+ expect(await put('notes/after-self-transfer')).toMatchObject({ state: 'committed' });+ });+ }, 90_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex e454634a7b..5502a7811e 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -128,8 +128,8 @@ test/frontmatter-reserved-keys-6454.test.tstest/g4-forget-fence-edit.test.tstest/gated-hold-strict-page-gst2535.test.tstest/get-chunks-paging.test.ts-test/git-canonical-conversion-evidence-d4.test.tstest/ghost-pages-git-canonical-7967.test.ts+test/git-canonical-conversion-evidence-d4.test.tstest/git-canonical-conversion-g8a.test.tstest/git-canonical-conversion-live-writer.test.tstest/git-canonical-conversion-no-checkout-7885.test.ts@@ -334,6 +334,7 @@ test/migration-0-53-host-move-7900.test.tstest/migration-persistence-foreground-committed-index.test.tstest/migration-persistence-request-id-index.test.tstest/migration-persistence-request-slug-index.test.ts+test/mirror-readonly-write-through-7098.test.tstest/notifier-passed-freshness-marker-7941.test.tstest/notifier-retry-unwatched-gst2515.test.tstest/on-commit-embedding.serial.test.ts@@ -496,6 +497,7 @@ test/persistence-write-interrupted.test.tstest/persistence-write-stall.test.tstest/persistence-writer-fences.test.tstest/physical-root-birth-tolerance-6501.test.ts+test/physical-root-copied-brain-fix-7671.test.tstest/privacy-label-ignored.test.tstest/provenance-drift-7891.test.tstest/provenance-stamps-7873.test.tsdiff --git a/test/provenance-drift-7891.test.ts b/test/provenance-drift-7891.test.tsindex 39d0f49c52..0b55e09816 100644--- a/test/provenance-drift-7891.test.ts+++ b/test/provenance-drift-7891.test.ts@@ -270,6 +270,22 @@ for (const kind of testBackends()) {expect(git(brainDir, 'rev-list', '--count', `${before.head}..HEAD`).trim()).toBe('2');}, 120_000);+ test.skipIf(!repo)('#7098: a page of a source marked mirror-readonly is listed needs_review, not repaired in the database alone', async () => {+ const slug = 'inbox/read-only-mirror';+ await seed(slug, STORED);+ await rewrite(slug, {}, 'oauth_client');+ const before = fs.readFileSync(fileOf(slug), 'utf8');+ await engine.executeRaw(`UPDATE sources SET config = COALESCE(config, '{}'::jsonb) || '{"mirror_read_only":true}'::jsonb WHERE id = 'default'`);+ try {+ const dry = await run(false);+ expect(dry.affected).toBe(0);+ expect(dry.listing.map((entry: Record<string, string>) => [entry.class, entry.detail])).toEqual([['needs_review', expect.stringContaining('mirror_read_only')]]);+ expect(fs.readFileSync(fileOf(slug), 'utf8')).toBe(before);+ } finally {+ await engine.executeRaw(`UPDATE sources SET config = config - 'mirror_read_only' WHERE id = 'default'`);+ }+ }, 120_000);+test('#7918: a classified page whose file would re-read higher gets its stored tier as the marker; the row keeps its tier', async () => {const slug = 'inbox/derived-unmarked';await seed(slug, {}, 'agent_written');