Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): name the owner exit for a recreated checkout and an ownership record other users can read (GST-465)
garrytan857384405708
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ba8bd42eb5..7c17a5f4e4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,7 +12,7 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**Page writes to a source whose directory is missing on the brain host no longer fail with a misleading `storage_error`. A source that is a folder inside a checkout now gets its folder created on the first write, and a source whose whole checkout is gone gets a refusal that says so.**+**Page writes to a source whose directory is missing on the brain host no longer fail with a misleading `storage_error`. A source that is a folder inside a checkout now gets its folder created on the first write, and a source whose whole checkout is gone gets a refusal that says so. A checkout restored or copied into place, or one whose private ownership records lost their mode, now refuses with the exact owner step that fixes it.**### What changed@@ -21,7 +21,10 @@ identifiers and attribution are available in the pre-removal Git revision| The source is a folder inside a checkout and the folder is missing (Git keeps no empty folder, so a fresh clone of a repository whose member folder has no files yet lacks it) | every `put_page`, `capture` and `add_timeline_entry` to it failed with `storage_error` ("The canonical file target cannot be accessed as a regular file"), so a token granted only that member's source could save nothing | the write creates the folder and the page, and the same token reads it back || The source's whole checkout is missing (a brain copied to another machine or into a container without its source directories) | the same `storage_error`, whose fix told the agent to repair file permissions | `recovery_required` with `detail: source_checkout_missing`, naming the source; the fix is the read-only `gbrain sources writer status --source <id> --json`, which shows the registered path. Remote callers are not shown the path. Nothing is written, as before |-A token's source grant decides where it writes exactly as before; this changes only how the file path inside the granted source is resolved.+| The checkout was restored, copied or recreated at its recorded path (new inode or birth time) | `recovery_required` whose `fix` only said to read the receipt | `detail: physical_root_directory_changed`, and the `fix` is the owner-run relocated-root self-transfer (`gbrain sources writer transfer prepare` then `accept`, both with `--self-transfer --confirm-relocated-root`) with `next: tell_user_to_run`. The re-stamp stays a deliberate step on the brain host |+| An ownership record of the checkout became readable by other users (a recursive `chmod` of a copied brain) | `recovery_required` ("The private physical-checkout identity cannot be verified"), and doctor's `foreign_ownership_marker` called the file foreign and told the operator to remove it | `detail: ownership_record_not_private` with `gbrain doctor --only foreign_ownership_marker` as the fix; doctor now reports this brain's own record with its mode and the exact `chmod 600 '<path>'`, never removal, and lists each record once |++A token's source grant decides where it writes exactly as before; this changes only how the file path inside the granted source is resolved and how these refusals name their exit.## [0.60.527.0] - 2026-10-31diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 527b70a180..e9a429b1b5 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -60,7 +60,8 @@ of making a duplicate.| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The exception is relationship `unreadable_state` (#7636): the database role gbrain connects as cannot see the writer state the guard reads (the `persistence_brain` or `git_canonical_brain` row, or the source or page row the write names) because row-level security hides it, or a `persistence_brain` / `git_canonical_brain` row is missing, so the guard refuses instead of letting the write through as if the brain were unmanaged or the row absent. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. For relationship `unreadable_state` the build is not the cause: run gbrain as a role that can see that state (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows, though a change to which sources are Git-canonical passes only the first two; see [writer-protocol fences](../ENGINES.md#opt-in-rls-source-scope-binding-gbrain_rls_scope_binding)), then retry with a **new** request ID; a missing row, which `gbrain init` never leaves, is reported like a defect. Never force-write, edit SQL or disable the guard. || `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`. || `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. | 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. |+| `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="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). || frontmatter slug conflict | `frontmatter_slug_conflict` (`invalid_params` on a gbrain older than v0.60.47.0) | A file's frontmatter `slug:` names a different page than its path. On a write nothing is written; during sync the file is held and the rest of the source imports. | Remove the `slug:` line or make it match the path, commit, then sync. See [`frontmatter_slug_conflict`](#frontmatter_slug_conflict). |@@ -740,6 +741,12 @@ Clearing it is the operator's decision, in this order:3. Claim again: `gbrain sources writer claim <source> --path <checkout> --dry-run`,then the printed apply command.+A marker of this brain that other users can read (mode `0644` after a+recursive `chmod`) is reported by the same check with its mode and the exact+`chmod 600 '<path>'` that restores it, and every write to that checkout+refuses [`ownership_record_not_private`](#ownership_record_not_private) until+then. Do not remove such a marker: it belongs to this brain.+## Secret scan refusals and redactionGBrain runs one secret scanner in several places. Depending on where adiff --git a/src/commands/doctor/checks/orphan-bindings.ts b/src/commands/doctor/checks/orphan-bindings.tsindex 6bfc53da0c..1a470087af 100644--- a/src/commands/doctor/checks/orphan-bindings.ts+++ b/src/commands/doctor/checks/orphan-bindings.ts@@ -40,7 +40,7 @@ export async function checkOrphanBindings(engine: BrainEngine): Promise<Check> {export async function checkForeignOwnershipMarkers(engine: BrainEngine): Promise<Check> {const name = 'foreign_ownership_marker';try {- const { readPhysicalRootReservation, readPhysicalRootStamp, physicalRootReservationPath, PHYSICAL_ROOT_MARKER } = await import('../../../core/persistence/physical-root-record.ts');+ const { readPhysicalRootReservation, readPhysicalRootStamp, physicalRootReservationPath, PHYSICAL_ROOT_MARKER, openOwnershipRecord } = await import('../../../core/persistence/physical-root-record.ts');const { existingLocalHostId } = await import('../../../core/persistence/identity.ts');const { existsSync } = await import('node:fs');const { join } = await import('node:path');@@ -49,14 +49,23 @@ export async function checkForeignOwnershipMarkers(engine: BrainEngine): Promiseconst roots = await engine.executeRaw<{ root: string; source_id: string | null }>(`SELECT DISTINCT local_path AS root,id AS source_id FROM sources WHERE local_path IS NOT NULL AND NOT COALESCE(archived,false)UNION SELECT DISTINCT h.local_path,NULL FROM persistence_host_bindings h WHERE h.host_id=$1::uuid`, [existingLocalHostId()]);- const markers: Array<{ path: string; source_id: string | null; kind: 'stamp' | 'reservation'; recorded_brain: string | null; worktree_known: boolean | null; problem: string }> = [];+ const markers: Array<{ path: string; source_id: string | null; kind: 'stamp' | 'reservation'; recorded_brain: string | null; worktree_known: boolean | null; problem: string; fix_command?: string }> = [];+ const seen = new Set<string>();for (const { root, source_id } of roots) {- if (!existsSync(root)) continue;+ if (!existsSync(root) || seen.has(root)) continue;+ seen.add(root);const candidates: Array<{ kind: 'stamp' | 'reservation'; path: string; read: () => { brainId: string; worktreeId: string } | null }> = [{ kind: 'stamp', path: join(root, PHYSICAL_ROOT_MARKER), read: () => readPhysicalRootStamp(root) },{ kind: 'reservation', path: physicalRootReservationPath(root), read: () => readPhysicalRootReservation(root) },];for (const candidate of candidates) {+ const open = openOwnershipRecord(candidate.path);+ if (open && brain && open.brainId === brain.brain_id && worktrees.has(open.worktreeId)) {+ const fix_command = `chmod 600 '${candidate.path.replaceAll("'", "'\\''")}'`;+ markers.push({ path: candidate.path, source_id, kind: candidate.kind, recorded_brain: open.brainId, worktree_known: true, fix_command,+ problem: `mode ${open.mode.toString(8).padStart(4, '0')}: other users can read it, so it no longer proves the owner; make it private again with ${fix_command}` });+ continue;+ }let value: { brainId: string; worktreeId: string } | null;try { value = candidate.read(); }catch { markers.push({ path: candidate.path, source_id, kind: candidate.kind, recorded_brain: null, worktree_known: null, problem: 'unreadable: not a private, well-formed ownership marker' }); continue; }@@ -70,11 +79,17 @@ export async function checkForeignOwnershipMarkers(engine: BrainEngine): Promise}const details = { count: markers.length, markers, docs: 'docs/guides/write-refusals.md#foreign-ownership-marker' };if (!markers.length) return { name, status: 'ok', message: 'Every ownership marker beside a source checkout belongs to this brain.', details };- return { name, status: 'warn', details,- message: `${markers.length} ownership marker(s) beside source checkouts do not belong to this brain: `- + markers.slice(0, 5).map(marker => `${marker.path} (${marker.problem})`).join('; ')- + `. A claim of that checkout refuses recovery_required while one remains. Confirm with the user that the recorded brain is retired `- + '(moved to this database or deleted), then remove exactly the named file on the brain host and claim again; never remove a marker of a brain that is still in use.' };+ const open = markers.filter(marker => marker.fix_command);+ const foreign = markers.filter(marker => !marker.fix_command);+ const parts: string[] = [];+ if (open.length) parts.push(`${open.length} ownership marker(s) beside source checkouts are readable by other users, so every write to that checkout refuses recovery_required `+ + `(ownership_record_not_private): ${open.slice(0, 5).map(marker => `${marker.path} (${marker.problem})`).join('; ')}. `+ + 'Run the named chmod on the brain host; never remove these markers, which belong to this brain.');+ if (foreign.length) parts.push(`${foreign.length} ownership marker(s) beside source checkouts do not belong to this brain: `+ + foreign.slice(0, 5).map(marker => `${marker.path} (${marker.problem})`).join('; ')+ + `. A claim of that checkout refuses recovery_required while one remains. Confirm with the user that the recorded brain is retired `+ + '(moved to this database or deleted), then remove exactly the named file on the brain host and claim again; never remove a marker of a brain that is still in use.');+ return { name, status: 'warn', details, message: parts.join(' ') };} catch (error) {return { name, status: 'warn', details: { count: 'unknown' },message: `Ownership markers could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex db7b8adf4f..da1c192da4 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -190,8 +190,8 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [id: 'foreign_ownership_marker', resolution: 'operator', registration: 'wave',hostOnly: 'Ownership markers are private files beside the source checkouts on the brain host.',count: d => Number(d.count ?? 0),- impact: 'An ownership marker beside a source checkout names another brain or an unknown worktree, so claiming that checkout refuses recovery_required',- instruction: 'Confirm with the user that the recorded brain is retired, then remove exactly the marker file doctor names on the brain host and claim again (docs/guides/write-refusals.md#foreign-ownership-marker); never remove a marker of a brain still in use.',+ impact: 'An ownership marker beside a source checkout names another brain or an unknown worktree, or other users can read it, so claiming or writing that checkout refuses recovery_required',+ instruction: 'A marker other users can read: run the chmod 600 doctor names on the brain host, never remove it. A marker of another brain: confirm with the user that the recorded brain is retired, then remove exactly the marker file doctor names on the brain host and claim again (docs/guides/write-refusals.md#foreign-ownership-marker); never remove a marker of a brain still in use.',run: async engine => (await import('./checks/orphan-bindings.ts')).checkForeignOwnershipMarkers(engine),},{diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 65fc082825..3f9af171bb 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -44,7 +44,7 @@ import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, pubimport { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { landedCommit, PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';-import { CANONICAL_FILE_MISSING, SOURCE_CHECKOUT_MISSING, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';+import { CANONICAL_FILE_MISSING, CHECKOUT_REFUSAL_ORIGINS, type CheckoutRefusalOrigin, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';import { SYNC_CURSOR_REPLACED, SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';import { withdrawalFailureDetail } from '../facts/withdrawal.ts';@@ -205,7 +205,7 @@ function requestError(error: unknown): PublicationFailure {// #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error) ?? (error.syncRefusal as PublicationFailure['detail'] | undefined)?? (error.detail === CANONICAL_FILE_MISSING ? { origin: CANONICAL_FILE_MISSING } : undefined)- ?? (error.detail === SOURCE_CHECKOUT_MISSING ? { origin: SOURCE_CHECKOUT_MISSING } : undefined)+ ?? ((CHECKOUT_REFUSAL_ORIGINS as readonly unknown[]).includes(error.detail) ? { origin: error.detail as CheckoutRefusalOrigin } : undefined)// #6693: a refusal on a page whose file awaits import or is held by sync; the replay after import selects on it.?? (error.code === 'source_changed' && (error.reason === PENDING_IMPORT || error.reason === SYNC_HELD) ? { origin: error.reason } : undefined);return { code: error.code, message: error.message, ...(detail ? { detail } : {}) };diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.tsindex 2e84dd90dc..7186b22c12 100644--- a/src/core/persistence/physical-root-record.ts+++ b/src/core/persistence/physical-root-record.ts@@ -51,6 +51,27 @@ const uuid = (value: unknown): value is string => typeof value === 'string' && /export function physicalRootError(message = 'The physical checkout identity changed or belongs to another owner.'): OperationError {return new OperationError('recovery_required', message, 'Use verified writer transfer or source recovery; do not remove ownership markers to claim this path.');}+/** GST-465: an ownership record whose mode lets other users read it (a recursive chmod of a copied brain) proves nothing about its owner. */+export function ownershipRecordNotPrivateError(): OperationError {+ const error = physicalRootError('A private ownership record of this checkout is readable by other users, so the checkout identity cannot be verified.');+ error.detail = 'ownership_record_not_private';+ error.suggestion = 'On the brain host, gbrain doctor --only foreign_ownership_marker names the record and the chmod 600 that makes it private again. Never remove an ownership record to get past this.';+ return error;+}+/**+ * Doctor only: an ownership record other users can read, with the mode and the brain and worktree it records, or null when+ * it is private, absent, not a regular file or not well formed (Windows: always null). Never authority for a write.+ */+export function openOwnershipRecord(path: string): { mode: number; brainId: string; worktreeId: string } | null {+ if (process.platform === 'win32') return null;+ try {+ const info = lstatSync(path);+ if (!info.isFile() || (info.mode & 0o077) === 0 || info.size > 16_384) return null;+ const value = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown; brainId?: unknown; worktreeId?: unknown } | null;+ if (!value || value.version !== 1 || !uuid(value.brainId) || !uuid(value.worktreeId)) return null;+ return { mode: info.mode & 0o777, brainId: value.brainId, worktreeId: value.worktreeId };+ } catch { return null; }+}export function physicalRootReservationPath(root: string): string {return join(dirname(root), `${RESERVATION_PREFIX}${sha256(root)}.json`);}@@ -60,12 +81,14 @@ function readPrivate(path: string): unknown | null {if (lstatSync(path).isSymbolicLink()) throw physicalRootError();fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));const info = fstatSync(fd);- if (!info.isFile() || info.size > 16_384 || process.platform !== 'win32' && (info.mode & 0o077) !== 0) throw physicalRootError();+ if (!info.isFile() || info.size > 16_384) throw physicalRootError();+ if (process.platform !== 'win32' && (info.mode & 0o077) !== 0) throw ownershipRecordNotPrivateError();const value = JSON.parse(readFileSync(fd, 'utf8'));if (!value || typeof value !== 'object') throw physicalRootError();return value;} catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ if (error instanceof OperationError && error.detail === 'ownership_record_not_private') throw error;throw physicalRootError('The private physical-checkout identity cannot be verified.');} finally { if (fd !== undefined) closeSync(fd); }}diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 44bc687c56..ed0d755117 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -60,10 +60,17 @@ export const CANONICAL_FILE_MISSING = 'canonical_file_missing';export interface CanonicalFileDetail { origin: typeof CANONICAL_FILE_MISSING; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }/** GST-465: the source's whole canonical checkout is missing on this host (`prepareFileTarget`, `sourceCheckoutMissingRefusal`). */export const SOURCE_CHECKOUT_MISSING = 'source_checkout_missing';-export interface SourceCheckoutDetail { origin: typeof SOURCE_CHECKOUT_MISSING; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }+/**+ * GST-465: refusals of the checkout itself whose detail outlives the receipt, so the caller gets the classified exit+ * (`storedCheckoutRefusal` in verb-errors.ts): the checkout is missing, was recreated at its recorded path+ * (`physicalRootDirectoryChangedError`), or holds an ownership record other users can read (`ownershipRecordNotPrivateError`).+ */+export const CHECKOUT_REFUSAL_ORIGINS = [SOURCE_CHECKOUT_MISSING, 'physical_root_directory_changed', 'ownership_record_not_private'] as const;+export type CheckoutRefusalOrigin = typeof CHECKOUT_REFUSAL_ORIGINS[number];+export interface CheckoutRefusalDetail { origin: CheckoutRefusalOrigin; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }/** #6693: a page write refused because its file holds a committed change sync has not imported (`pending_import`) or sync holds the file (`sync_held`). */export interface PendingImportDetail { origin: 'pending_import' | 'sync_held'; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail | SourceCheckoutDetail | PendingImportDetail }+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail | CheckoutRefusalDetail | PendingImportDetail }const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex f3f96df786..9449b5445b 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -25,8 +25,7 @@ import type { PgAccessReason } from '../pg-access-classify.ts';import { contentRefusalFromReceipt } from '../import-screen.ts';import { fenceIssuesFromDetail, fenceLocationFromDetail } from '../fence-repair/refusal.ts';import { withdrawnFromDetail } from '../facts/withdrawal.ts';-import { heldFileDiagnostic, sourceCheckoutMissingRefusal } from './verb-errors.ts';-import { SOURCE_CHECKOUT_MISSING } from './publication-failure.ts';+import { heldFileDiagnostic, storedCheckoutRefusal } from './verb-errors.ts';import { isMissingPageMessage } from './page-identity.ts';import { registerPersistenceConsumerConfig } from '../embedding-disabled.ts';@@ -411,10 +410,8 @@ export function writeResponse(row: WriteRequest, hints: { retryAfterMs?: numberconst pending = pendingImportRefusal(row, row.authority?.remote === true);Object.assign(error, { suggestion: pending.suggestion, fix: pending.fix, reason: pending.reason, detail: pending.detail, docs: pending.docs ?? error.docs });}- if (isTerminal(row) && (row.error_detail as { origin?: unknown } | null | undefined)?.origin === SOURCE_CHECKOUT_MISSING) {- const missing = sourceCheckoutMissingRefusal(row.source_id, row.slug || null);- Object.assign(error, { suggestion: missing.suggestion, fix: missing.fix, detail: missing.detail, docs: missing.docs });- }+ const checkout = isTerminal(row) ? storedCheckoutRefusal((row.error_detail as { origin?: unknown } | null | undefined)?.origin, row.source_id, row.slug || null) : undefined;+ if (checkout) Object.assign(error, { suggestion: checkout.suggestion, fix: checkout.fix, detail: checkout.detail, docs: checkout.docs });// #6317 (B1b): a waiter-only process names the owner that publishes for it, so the caller is told who holds the write instead of polling blind.if (!isTerminal(row) && hints.waiterOnlyOwner) {const owner = hints.waiterOnlyOwner;diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex f672def4ee..cefcc3051f 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -10,7 +10,8 @@ import { CHECKPOINT_MOVED_MESSAGE } from './sync-slug-mode.ts';import { PAGE_CHANGED_AFTER_READ_MESSAGE } from '../page-state/types.ts';import { readFix } from '../ops/op-fix.ts';import { ERROR_CATALOGUE } from '../error-catalogue.ts';-import { SOURCE_CHECKOUT_MISSING } from './publication-failure.ts';+import { SOURCE_CHECKOUT_MISSING, type CheckoutRefusalOrigin } from './publication-failure.ts';+import { ownershipRecordNotPrivateError, physicalRootDirectoryChangedError } from './physical-root-record.ts';/** GST-465: a page write to a source whose canonical checkout is missing on this host. The path is left to the read-only fix, which a remote caller cannot run. */export function sourceCheckoutMissingRefusal(sourceId: string, slug: string | null): OperationError {@@ -20,6 +21,33 @@ export function sourceCheckoutMissingRefusal(sourceId: string, slug: string | nufix: readFix(`Shows source ${sourceId}'s canonical binding and the checkout path this host registered for it, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });}+/**+ * GST-465: the classified exit of a page write refused because of the checkout itself, rebuilt from the origin its receipt+ * keeps. Re-stamping a recreated checkout and restoring a record's mode stay the owner's deliberate acts on the brain host:+ * the check exists to catch a swapped checkout, so the agent tells the user and never runs them itself.+ */+export function storedCheckoutRefusal(origin: unknown, sourceId: string, slug: string | null): OperationError | undefined {+ if (origin === SOURCE_CHECKOUT_MISSING) return sourceCheckoutMissingRefusal(sourceId, slug);+ if (origin === 'ownership_record_not_private') {+ const error = ownershipRecordNotPrivateError();+ error.fix = { argv: ['gbrain', 'doctor', '--only', 'foreign_ownership_marker'], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Read-only on the brain host: names each ownership record other users can read and the chmod 600 that makes it private again.' };+ error.docs = 'docs/guides/write-refusals.md#ownership_record_not_private';+ return error;+ }+ if (origin !== ('physical_root_directory_changed' satisfies CheckoutRefusalOrigin)) return undefined;+ const state = { name: 'admin_state', how: `admin_state from gbrain sources writer status ${sourceId} --json on the brain host, read again before each phase` };+ const intent = (phase: string) => ['--self-transfer', '--confirm-relocated-root', '--admin-intent', `writer_transfer_${phase}`, '--expected-state', '<admin_state>'];+ return Object.assign(physicalRootDirectoryChangedError(), {+ suggestion: 'Nothing was written. Only if the checkout was restored, copied or recreated at its recorded path on purpose, the brain host\'s owner re-stamps it with the relocated-root self-transfer in fix, then you submit again with a new request_id. Never remove the ownership records to get past this.',+ docs: 'docs/guides/write-refusals.md#recreated-root',+ fix: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', sourceId, ...intent('prepare')], inputs: [state], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Owner only, after confirming the move was deliberate: records the manifest of the directory now at the recorded path. The identity check exists to catch a swapped checkout.',+ then: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'accept', sourceId, '--path', '<checkout root>', '--expected-epoch', '<owner_epoch>', '--manifest', '<manifest digest printed by prepare>', ...intent('accept')],+ inputs: [state, { name: 'checkout root', how: 'the local_path writer status prints for the source' }, { name: 'owner_epoch', how: 'the owner_epoch prepare printed' }],+ consent: [], actor: 'user', requires_exclusive: false, why: 'Re-stamps the checkout identity at the same path; page writes publish again after it.' } } satisfies Action });+}+/** The refusal of a fact-batch completion request whose per-entity requests did not all commit (facts-prepare.ts). */export const FACTS_BATCH_INCOMPLETE_MESSAGE = 'Some extracted facts have not committed.';/** facts-prepare.ts: an entity request admitted at a revision another write moved (or a deleted or replaced entity page). */diff --git a/test/e2e/source-checkout-missing-write-postgres.test.ts b/test/e2e/source-checkout-missing-write-postgres.test.tsindex b780bbc7c4..a22598da2d 100644--- a/test/e2e/source-checkout-missing-write-postgres.test.ts+++ b/test/e2e/source-checkout-missing-write-postgres.test.ts@@ -1,11 +1,13 @@/** GST-465 on Postgres; the scenarios and their contract are in test/helpers/source-checkout-missing-scenarios.ts. */import { describe, test } from 'bun:test';import { hasDatabase } from './helpers.ts';-import { missingSourceCheckout, missingSourceSubdirectory } from '../helpers/source-checkout-missing-scenarios.ts';+import { missingSourceCheckout, missingSourceSubdirectory, ownershipRecordNotPrivate, recreatedCheckout } from '../helpers/source-checkout-missing-scenarios.ts';const d = hasDatabase() ? describe : describe.skip;d('GST-465: member-token page writes when the source directory is missing (Postgres)', () => {test('a missing source subdirectory is created and the same token reads the page back', () => missingSourceSubdirectory(process.env.DATABASE_URL), 240_000);test('a missing source checkout refuses with source_checkout_missing and writes nothing', () => missingSourceCheckout(process.env.DATABASE_URL), 240_000);+ test('a checkout recreated at its recorded path refuses physical_root_directory_changed and names the owner-run self-transfer', () => recreatedCheckout(process.env.DATABASE_URL), 240_000);+ test('an ownership record readable by others refuses ownership_record_not_private and doctor names the chmod', () => ownershipRecordNotPrivate(process.env.DATABASE_URL), 240_000);});diff --git a/test/helpers/source-checkout-missing-scenarios.ts b/test/helpers/source-checkout-missing-scenarios.tsindex 7d7886e0b5..2370d221d1 100644--- a/test/helpers/source-checkout-missing-scenarios.ts+++ b/test/helpers/source-checkout-missing-scenarios.ts@@ -11,10 +11,19 @@* that tells the agent to repair file permissions; a remote caller is not shown the host path; nothing is written.* Regression: both shapes refused every page write with storage_error ("The canonical file target cannot be accessed* as a regular file") because the file target was resolved against the source directory itself.+ *+ * The same write door, when the checkout is present but its private ownership records no longer verify:+ * - recreated at its recorded path (a backup restore or a container copy: new inode and birth time): the write refuses+ * recovery_required with detail physical_root_directory_changed, and its fix is the owner-run relocated-root+ * self-transfer (prepare, then accept), which the agent tells the user to run and never runs itself;+ * - an ownership record readable by other users (a recursive chmod): the write refuses recovery_required with detail+ * ownership_record_not_private and points at doctor, which names the file and the chmod 600 that restores it instead+ * of telling the operator to delete it. Restoring the mode makes the next write succeed.+ * Regression: both refused with no detail and a fix that only said to read the receipt.*/import { expect } from 'bun:test';import { execFileSync } from 'node:child_process';-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../../src/core/engine.ts';import type { AuthInfo } from '../../src/core/ops/contract.ts';@@ -24,7 +33,10 @@ import { mintLegacyToken } from '../../src/core/token-mint.ts';import { parseRescopeTokenArgs, rescopeLegacyToken } from '../../src/core/grants/legacy-token.ts';import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { PHYSICAL_ROOT_MARKER } from '../../src/core/persistence/physical-root-record.ts';+import { checkForeignOwnershipMarkers } from '../../src/commands/doctor/checks/orphan-bindings.ts';import { managedBrain } from './managed-brain.ts';+import { recreateRoot } from './recreate-root.ts';const page = (title: string, extra = '') => `---\ntitle: ${title}\ntype: note\n${extra}---\n\n${title} body.\n`;@@ -97,3 +109,43 @@ export function missingSourceCheckout(databaseUrl?: string) {expect(existsSync(memberDir)).toBe(false);}, { databaseUrl });}++export function recreatedCheckout(databaseUrl?: string) {+ return managedBrain(async ({ engine, root }) => {+ const call = caller(engine, await memberToken(engine, 'default'));+ expect((await call('put_page', { slug: 'notes/before-move', content: page('notes/before-move') })).body.error ?? null).toBeNull();+ recreateRoot(root, { keepStamp: true });+ const out = await call('put_page', { slug: 'notes/after-move', content: page('notes/after-move') });+ expect({ isError: out.isError, code: out.body.code, detail: out.body.detail }).toEqual({ isError: true, code: 'recovery_required', detail: 'physical_root_directory_changed' });+ expect(out.body.fix).toMatchObject({ next: 'tell_user_to_run', actor: 'user' });+ expect(out.body.fix.argv).toEqual(expect.arrayContaining(['transfer', 'prepare', 'default', '--self-transfer', '--confirm-relocated-root']));+ expect(out.body.fix.then.argv).toEqual(expect.arrayContaining(['transfer', 'accept', 'default', '--self-transfer', '--confirm-relocated-root']));+ expect(out.text).not.toContain(root);+ expect((await call('get_page', { slug: 'notes/after-move' })).body.error).toBe('page_not_found');+ }, { databaseUrl });+}++export function ownershipRecordNotPrivate(databaseUrl?: string) {+ if (process.platform === 'win32') return Promise.resolve();+ return managedBrain(async ({ engine, root }) => {+ const call = caller(engine, await memberToken(engine, 'default'));+ const stamp = join(root, PHYSICAL_ROOT_MARKER);+ expect((await call('put_page', { slug: 'notes/before-chmod', content: page('notes/before-chmod') })).body.error ?? null).toBeNull();+ chmodSync(stamp, 0o644);+ const out = await call('put_page', { slug: 'notes/after-chmod', content: page('notes/after-chmod') });+ expect({ isError: out.isError, code: out.body.code, detail: out.body.detail }).toEqual({ isError: true, code: 'recovery_required', detail: 'ownership_record_not_private' });+ expect(out.body.fix).toMatchObject({ next: 'tell_user_to_run', argv: ['gbrain', 'doctor', '--only', 'foreign_ownership_marker'] });+ expect(out.text).not.toContain(root);++ const check = await checkForeignOwnershipMarkers(engine);+ const markers = (check.details as { markers: Array<{ path: string; problem: string }> }).markers;+ expect(markers.map(marker => marker.path)).toEqual([stamp]);+ expect(markers[0].problem).toContain(`chmod 600 '${stamp}'`);+ expect(check.message).toContain(`chmod 600 '${stamp}'`);+ expect(check.message).not.toContain('remove exactly the named file');++ chmodSync(stamp, 0o600);+ expect((await call('put_page', { slug: 'notes/after-chmod', content: page('notes/after-chmod') })).body.error ?? null).toBeNull();+ expect((await call('get_page', { slug: 'notes/after-chmod' })).body.compiled_truth).toContain('notes/after-chmod body.');+ }, { databaseUrl });+}diff --git a/test/source-checkout-missing-write.test.ts b/test/source-checkout-missing-write.test.tsindex ffb5ec57e1..3117fa75e8 100644--- a/test/source-checkout-missing-write.test.ts+++ b/test/source-checkout-missing-write.test.ts@@ -1,8 +1,10 @@/** GST-465 on PGLite (keyless); the scenarios and their contract are in test/helpers/source-checkout-missing-scenarios.ts. */import { describe, test } from 'bun:test';-import { missingSourceCheckout, missingSourceSubdirectory } from './helpers/source-checkout-missing-scenarios.ts';+import { missingSourceCheckout, missingSourceSubdirectory, ownershipRecordNotPrivate, recreatedCheckout } from './helpers/source-checkout-missing-scenarios.ts';describe('GST-465: member-token page writes when the source directory is missing (PGLite)', () => {test('a missing source subdirectory is created and the same token reads the page back', () => missingSourceSubdirectory(), 120_000);test('a missing source checkout refuses with source_checkout_missing and writes nothing', () => missingSourceCheckout(), 120_000);+ test('a checkout recreated at its recorded path refuses physical_root_directory_changed and names the owner-run self-transfer', () => recreatedCheckout(), 120_000);+ test('an ownership record readable by others refuses ownership_record_not_private and doctor names the chmod', () => ownershipRecordNotPrivate(), 120_000);});