Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): tolerate 1 µs of persisted birth-stamp drift; name the relocated-root exit (#6501)
garrytan8cacfc8ccca3
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a20918744e..1a73617e3c 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2268,7 +2268,7 @@ More: [docs/guides/company-brain-ingestion.md#agent-and-ci-use](../../docs/guide| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| An earlier write left state that must be inspected and recovered before new writes. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |+| An earlier write left state that must be inspected and recovered before new writes. | Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it). Both are explained in docs/guides/write-refusals.md. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |### redirect_uri_mismatchdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 6c7b014160..f74f767096 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -40,6 +40,7 @@ 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 receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. | 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. 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 --retry-failed`. || `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. || <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. 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). |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 089e7a919a..93fc686e47 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -440,6 +440,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Fix wave 15 G2 (GBRA-79, #6454); `since` is a placeholder equal to the branch's VERSION until the integrator sets the merge-slot stamp.{ since: '0.60.175.0', text: 'A coordinated write to a page whose stored frontmatter carries one of the parser\'s reserved top-level keys (`type`, `title`, `tags`, `slug`, kept by imports before mid-2026) is no longer refused `source_changed` when the file matches the database in every other way: the file/database comparison (publication, `sources reconcile`, file repairs) strips those four keys on both sides, as the parser does (#6454). A real body, title or tag drift still refuses. Writes refused this way whose receipt is retained replay with `gbrain repair failed-writes --source <id>`; doctor `stale_frontmatter_keys` counts the rows and names the explicit-only `gbrain repair frontmatter-keys` sweep, which removes the inert keys in coordinated batches and advances each swept page\'s `knowledge_revision` once (a client holding an older revision gets one `revision_conflict`).' },{ since: '0.60.175.0', text: 'A published page file now always carries the page\'s own `type`, `title` and tags from the database columns. A legacy row whose stored frontmatter also held a `type` or `title` that disagreed with the columns used to render the stored value (and stored `tags` rendered when the page had none); the next write of such a page now renders the columns and drops the stale keys, so the file\'s header can change once. Nested keys of the same names (`metadata.title`) and the `slug:` stamp for slugs the path cannot derive are unchanged.' },+ // Fix wave 15 G2 (GBRA-79, #6501); `since` is a placeholder equal to the branch's VERSION until the integrator sets the merge-slot stamp.+ { since: '0.60.175.0', text: 'A managed checkout\'s persisted directory birth stamp now matches the live directory when the two are within 1 µs, instead of only when they are byte-identical (#6501: on APFS a freshly created root reports a birth time tens of nanoseconds apart between the process that stamped it and later processes, which left every write to that root refused `recovery_required`). The owner token, brain, worktree, root, inode and device still have to match exactly; a damaged or zero stamp still refuses; the in-process file target check, the staging identity and the transfer prepare/accept comparison stay exact. When the inode or birth time moved beyond that while everything else matches (a checkout restored or recreated at its recorded path), the refusal now carries detail `physical_root_directory_changed` and names the exit: `gbrain sources writer transfer prepare/accept <source> --self-transfer --confirm-relocated-root` (`writer status --json` prints it filled in). The tolerance covers the reported drift; it was not reproduced on APFS here, so #6501 stays open until a reporter confirms on this build.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex ca91d28e6a..5533b33298 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -347,7 +347,7 @@ export const CODES = {receipt_fence_required: { class: 'host_only', summary: "Ingestion into a managed or bound source needs the worktree owner's fence.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },receipt_identity_mismatch: { class: 'caller', summary: "The receipt ID is already bound to different approved ingestion metadata.", docs: 'docs/guides/company-brain-ingestion.md#agent-and-ci-use' },pat_file_unreadable: { class: 'caller', summary: "The --pat-file token file is missing, empty, holds more than one token, or is readable by other users, so it was not read.", why: "The token is read from a private file so it never appears on a command line or in a process list; a file other users can read would leak it, so the verb refuses before any credential is written.", suggestion: 'Write exactly one token on one line to a file, chmod 600 it, and pass its path with --pat-file.' },- recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes." },+ recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes.", why: "Details name the exit when there is one: physical_root_device_changed (the checkout's filesystem device number changed; re-stamped by itself when ownership verifies) and physical_root_directory_changed (the directory at the recorded path was recreated, or its birth time drifted beyond 1 µs; the relocated-root self-transfer, `transfer prepare/accept <source> --self-transfer --confirm-relocated-root`, re-stamps it). Both are explained in docs/guides/write-refusals.md." },redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },ref_not_in_answer: { class: 'caller', summary: "The rated page is not one of the pages the answer used.", docs: 'docs/guides/retrieval-feedback.md#ref_not_in_answer' },refresh_dirty: { class: 'caller', summary: "The worktree has uncommitted changes." },diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex 194311f9a1..410b0e0776 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -192,6 +192,15 @@ async function lockWorktree(binding: WorktreeBinding, waitMs: number, signal: Abtry { assertPhysicalRoot(binding.local_path, identity); return lock; }catch (error) {try {+ if (error instanceof OperationError && error.detail === 'physical_root_directory_changed') {+ // #6501: a directory recreated (or drifted beyond tolerance) at its recorded path; fill the #5914 exit for this source.+ error.suggestion = `The directory at ${binding.local_path} is not the one this owner stamped (inode or birth time changed; owner token, brain, worktree, root and device match). `+ + `If this checkout was restored or recreated at its recorded path, on the brain host run gbrain sources writer status ${binding.source_id} and note admin_state, `+ + `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.`;+ throw error;+ }if (!(error instanceof OperationError) || error.detail !== 'physical_root_device_changed') throw error;if (engine && await restampPhysicalRoot(engine, binding, localHostId())) { assertPhysicalRoot(binding.local_path, identity); return lock; }const why = !engine ? 'this caller cannot verify database ownership'diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.tsindex 1ae52d0f72..02d90061e1 100644--- a/src/core/persistence/physical-root-record.ts+++ b/src/core/persistence/physical-root-record.ts@@ -144,18 +144,65 @@ export function assertNoPhysicalRootOverlap(root: string): void {export function writePhysicalRootStamp(directory: string, reservation: PhysicalRootReservation): void {const info = statSync(directory, { bigint: true });if (!info.isDirectory()) throw physicalRootError();- const stamp: PhysicalRootStamp = { version: 1, token: reservation.token, brainId: reservation.brainId, worktreeId: reservation.worktreeId,- root: reservation.root, device: info.dev.toString(), inode: info.ino.toString(), birth: info.birthtimeNs.toString() };- createPrivate(join(directory, PHYSICAL_ROOT_MARKER), stamp);+ const stampFor = (live: { dev: bigint; ino: bigint; birthtimeNs: bigint }): PhysicalRootStamp => ({ version: 1, token: reservation.token, brainId: reservation.brainId,+ worktreeId: reservation.worktreeId, root: reservation.root, device: live.dev.toString(), inode: live.ino.toString(), birth: live.birthtimeNs.toString() });+ const marker = join(directory, PHYSICAL_ROOT_MARKER);+ createPrivate(marker, stampFor(info));+ // #6501 belt-and-braces: the stamp records what the directory reports after the marker landed in it.+ const after = statSync(directory, { bigint: true });+ if (after.dev !== info.dev || after.ino !== info.ino || after.birthtimeNs !== info.birthtimeNs) replacePrivate(marker, stampFor(after));assertPhysicalRootStamp(directory, reservation);excludeOwnershipMarkers([directory, reservation.root, dirname(reservation.root)]);}+/**+ * #6501: how far a persisted directory birth stamp may sit from the live+ * `birthtimeNs` and still name the same directory. APFS reports a freshly+ * created directory's birth time tens of nanoseconds apart between the+ * process that created it and later processes (one Apple-Silicon timebase+ * tick), which left every write to such a root refused forever. 1 µs is 20x+ * the reported drift and far below anything a removed-and-recreated directory+ * can land in; everything else about the stamp (owner token, brain, worktree,+ * root, inode, device) still has to agree exactly.+ */+export const PHYSICAL_BIRTH_TOLERANCE_NS = 1_000n;+/**+ * Whether a persisted birth stamp names the live directory. Equal strings+ * always match (so `'0'` against a filesystem that reports no birth time+ * keeps working); a malformed stamp, or a zero on either side against a+ * non-zero on the other, fails closed; otherwise the two may differ by at+ * most PHYSICAL_BIRTH_TOLERANCE_NS. Persisted-stamp comparisons only: the+ * in-process path-race check, the staging identity and the prepared-record+ * digest compare exactly, because they guard a running operation.+ */+export function samePhysicalBirth(stored: string | null | undefined, live: bigint): boolean {+ if (typeof stored !== 'string' || !/^\d{1,30}$/.test(stored)) return false;+ const value = BigInt(stored);+ if (value === live) return true;+ if (value === 0n || live === 0n) return false;+ return (value > live ? value - live : live - value) <= PHYSICAL_BIRTH_TOLERANCE_NS;+}+/** 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.');+ 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> '+ + '--self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept --expected-state <admin_state from a fresh status>. Never remove the ownership markers to claim this path.';+ return error;+}/** directory may be a verified staging directory; its stamp always names the final root. */export function assertPhysicalRootStamp(directory: string, reservation: PhysicalRootReservation): void {const value = readPrivate(join(directory, PHYSICAL_ROOT_MARKER)) as PhysicalRootStamp | null;const info = statSync(directory, { bigint: true });if (!value || value.version !== 1 || value.token !== reservation.token || value.brainId !== reservation.brainId || value.worktreeId !== reservation.worktreeId- || value.root !== reservation.root || value.inode !== info.ino.toString() || value.birth !== info.birthtimeNs.toString()) throw physicalRootError();+ || value.root !== reservation.root) throw physicalRootError();+ if (value.inode !== info.ino.toString() || !samePhysicalBirth(value.birth, info.birthtimeNs)) {+ // #6501 door parity with the device change below: a well-formed stamp whose directory identity alone moved names the #5914 exit;+ // a malformed birth stamp is a damaged record, not a recreated directory, and keeps the generic refusal.+ if (value.device === info.dev.toString() && typeof value.birth === 'string' && /^\d+$/.test(value.birth)) throw physicalRootDirectoryChangedError();+ throw physicalRootError();+ }if (value.device !== info.dev.toString()) {if (typeof value.device === 'string' && /^\d+$/.test(value.device)) {const error = physicalRootError('The filesystem device identifier changed while the other checkout identity fields still match. Inspect writer status and use deliberate self-transfer to re-stamp this same root.');@@ -174,7 +221,7 @@ export function assertPhysicalRootStamp(directory: string, reservation: Physicalexport function physicalRootDeviceChange(stamp: PhysicalRootStamp, reservation: Pick<PhysicalRootReservation, 'token' | 'brainId' | 'worktreeId' | 'root'>,info: { dev: bigint; ino: bigint; birthtimeNs: bigint }): { from: string; to: string } | null {if (stamp.token !== reservation.token || stamp.brainId !== reservation.brainId || stamp.worktreeId !== reservation.worktreeId- || stamp.root !== reservation.root || stamp.inode !== info.ino.toString() || stamp.birth !== info.birthtimeNs.toString()+ || stamp.root !== reservation.root || stamp.inode !== info.ino.toString() || !samePhysicalBirth(stamp.birth, info.birthtimeNs)|| info.birthtimeNs === 0n || stamp.device === info.dev.toString()) return null;return { from: stamp.device, to: info.dev.toString() };}diff --git a/src/core/persistence/physical-root.ts b/src/core/persistence/physical-root.tsindex 799a9bdf52..fb45aa773b 100644--- a/src/core/persistence/physical-root.ts+++ b/src/core/persistence/physical-root.ts@@ -6,7 +6,7 @@ import type { SqlEngine } from './model.ts';import { persistenceHome } from './identity.ts';import { canonicalFilesystemPath } from './root-registry.ts';import { adoptTransferredRootStamp, assertNoPhysicalRootOverlap, assertPhysicalRoot, assertPhysicalRootStamp, PHYSICAL_ROOT_MARKER, physicalRootDeviceChange, physicalRootError,- readPhysicalRootReservation, readPhysicalRootStamp, reservePhysicalRootRecord, restampPhysicalRootDevice, writePhysicalRootStamp, type PhysicalRootReservation } from './physical-root-record.ts';+ readPhysicalRootReservation, readPhysicalRootStamp, reservePhysicalRootRecord, restampPhysicalRootDevice, samePhysicalBirth, writePhysicalRootStamp, type PhysicalRootReservation } from './physical-root-record.ts';export { assertPhysicalRoot, isPhysicalRootMetadata, readPhysicalRootReservation } from './physical-root-record.ts';export interface PhysicalRootClaim { hostId: string; worktreeId?: string; coordinationPath?: string; }@@ -46,7 +46,7 @@ export async function claimPhysicalRoot(tx: SqlEngine, path: string, opts: Physi}else {const info = statSync(reservation.root, { bigint: true });- if (reservation.initialDevice !== info.dev.toString() || reservation.initialInode !== info.ino.toString() || reservation.initialBirth !== info.birthtimeNs.toString()) throw physicalRootError();+ if (reservation.initialDevice !== info.dev.toString() || reservation.initialInode !== info.ino.toString() || !samePhysicalBirth(reservation.initialBirth, info.birthtimeNs)) throw physicalRootError();writePhysicalRootStamp(reservation.root, reservation);}return reservation;diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex a873ab248a..afcbeda654 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -82,6 +82,9 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {return { reason: 'source_changed', message: 'A canonical source input or binding changed; the write was refused.',suggestion: 'Inspect the source on its existing owner. For file/database drift, preview gbrain sources reconcile <source> <slug> --brain <brain> --preview. Do not change ownership or permissions to bypass this guard.' };}+ // #6501: a checkout recreated (or drifted beyond the birth tolerance) at its recorded path; the #5914 relocated-root self-transfer is the exit.+ if (code === 'recovery_required' && message?.startsWith('The checkout directory at the recorded root is not the one this owner stamped')) return { reason: 'physical_root_directory_changed', message,+ suggestion: 'On the brain host, gbrain sources writer status <source> --json shows the filled commands: gbrain sources writer transfer prepare <source> --self-transfer --confirm-relocated-root, then transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --confirm-relocated-root (each with its admin intent). Retry the original write with the same request_id afterwards; never remove the ownership markers.' };if (code === 'owner_unavailable' && message === UNBOUND_PUBLICATION_MESSAGE) return { reason: 'unbound_source', message,suggestion: 'Read the page again and submit the write with a new request_id; a bound source publishes it to its canonical file.' };if (code === 'owner_unavailable') return { reason: code, message: 'The accepted source owner is unavailable or changed.',diff --git a/test/persistence-physical-root-device.test.ts b/test/persistence-physical-root-device.test.tsindex 2a49009a34..bb4da18326 100644--- a/test/persistence-physical-root-device.test.ts+++ b/test/persistence-physical-root-device.test.ts@@ -35,7 +35,9 @@ test('device-only change is recognized only with a non-zero matching birth timeexpect(physicalRootDeviceChange(stamp, reservation, info(7n, 11n, 13n))).toBeNull();expect(physicalRootDeviceChange({ ...stamp, birth: '0' }, reservation, info(8n, 11n, 0n))).toBeNull();expect(physicalRootDeviceChange(stamp, reservation, info(8n, 12n, 13n))).toBeNull();- expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, 14n))).toBeNull();+ // #6501: a birth time within 1 µs of the stamp is the same directory (14 vs 13 ns); beyond it is not.+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, 14n))).toEqual({ from: '7', to: '8' });+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, 13n + 1001n))).toBeNull();expect(physicalRootDeviceChange(stamp, { ...reservation, token: randomUUID() }, info(8n, 11n, 13n))).toBeNull();expect(physicalRootDeviceChange({ ...stamp, root: '/other' }, reservation, info(8n, 11n, 13n))).toBeNull();});diff --git a/test/physical-root-birth-tolerance-6501.test.ts b/test/physical-root-birth-tolerance-6501.test.tsnew file mode 100644index 0000000000..b2deab078f--- /dev/null+++ b/test/physical-root-birth-tolerance-6501.test.ts@@ -0,0 +1,244 @@+/**+ * #6501: APFS reports a freshly created directory's birth time tens of+ * nanoseconds apart between the process that stamped it and later processes,+ * and the persisted physical-root stamp compared it exactly, so every write+ * to such a root was refused `recovery_required` with no exit named.+ *+ * Fix: persisted birth stamps compare through `samePhysicalBirth` (1 µs+ * tolerance, every other identity field exact, malformed and zero fail+ * closed), and a directory whose inode or birth moved beyond that while the+ * owner token, brain, worktree, root and device still match refuses with the+ * new detail `physical_root_directory_changed`, whose suggestion names the+ * #5914 `transfer prepare/accept --self-transfer --confirm-relocated-root`+ * exit. [R39]: the in-process path-race check, the staging identity and the+ * prepared-record digest CAS stay exact.+ *+ * Honest claim: the drift itself is not reproducible on Linux (ext4/tmpfs+ * report stable values); these tests perturb the persisted stamp.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import * as fs from 'node:fs';+import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, 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 type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.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 { assertPhysicalRoot } from '../src/core/persistence/physical-root.ts';+import { inspectPhysicalRootRecovery, repairPhysicalRoot } from '../src/core/persistence/physical-root-recovery.ts';+import { PHYSICAL_BIRTH_TOLERANCE_NS, PHYSICAL_ROOT_MARKER, physicalRootDeviceChange, physicalRootReservationPath, samePhysicalBirth, writePhysicalRootStamp } 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 writeJson = (path: string, value: unknown) => writeFileSync(path, JSON.stringify(value), { mode: 0o600 });+const ROOT = join(import.meta.dir, '..');++describe('samePhysicalBirth (#6501)', () => {+ const live = 1_791_731_240_233_986_720n;+ test('tolerates up to 1 µs of drift on a well-formed stamp, refuses beyond it', () => {+ expect(PHYSICAL_BIRTH_TOLERANCE_NS).toBe(1000n);+ expect(samePhysicalBirth(live.toString(), live)).toBe(true);+ expect(samePhysicalBirth((live - 50n).toString(), live)).toBe(true);+ expect(samePhysicalBirth((live + 47n).toString(), live)).toBe(true);+ expect(samePhysicalBirth((live - 1000n).toString(), live)).toBe(true);+ expect(samePhysicalBirth((live + 1000n).toString(), live)).toBe(true);+ expect(samePhysicalBirth((live - 1001n).toString(), live)).toBe(false);+ expect(samePhysicalBirth((live + 1001n).toString(), live)).toBe(false);+ expect(samePhysicalBirth((live - 5_000_000_000n).toString(), live)).toBe(false);+ });+ test('malformed and zero stamps fail closed; an exact zero against a zero filesystem still matches', () => {+ expect(samePhysicalBirth('abc', live)).toBe(false);+ expect(samePhysicalBirth('', live)).toBe(false);+ expect(samePhysicalBirth('-50', live)).toBe(false);+ expect(samePhysicalBirth('1.5', live)).toBe(false);+ expect(samePhysicalBirth(null, live)).toBe(false);+ expect(samePhysicalBirth(undefined, live)).toBe(false);+ expect(samePhysicalBirth('0', live)).toBe(false);+ expect(samePhysicalBirth('0', 5n)).toBe(false);+ expect(samePhysicalBirth('5', 0n)).toBe(false);+ expect(samePhysicalBirth('0', 0n)).toBe(true);+ });+ test('the device door keeps its parity: a 50 ns birth drift still recognizes a device-only change, 1 µs + 1 ns does not', () => {+ const stamp = { version: 1 as const, token: randomUUID(), brainId: randomUUID(), worktreeId: randomUUID(), root: '/example/root', device: '7', inode: '11', birth: live.toString() };+ const reservation = { token: stamp.token, brainId: stamp.brainId, worktreeId: stamp.worktreeId, root: stamp.root };+ const info = (dev: bigint, ino: bigint, birth: bigint) => ({ dev, ino, birthtimeNs: birth });+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, live + 50n))).toEqual({ from: '7', to: '8' });+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, live - 1000n))).toEqual({ from: '7', to: '8' });+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, live - 1001n))).toBeNull();+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 12n, live + 50n))).toBeNull();+ expect(physicalRootDeviceChange({ ...stamp, birth: '0' }, reservation, info(8n, 11n, 0n))).toBeNull();+ });+ test('writePhysicalRootStamp re-stats after the marker lands: the stamp carries the post-create birth time', () => {+ const dir = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-restat-')));+ const original = fs.statSync;+ let bigintStats = 0;+ // The creating process reads one value before the marker exists and another after (the reported APFS shape).+ const spy = spyOn(fs, 'statSync').mockImplementation(((path: fs.PathLike, opts?: { bigint?: boolean }) => {+ const info = original(path, opts as never) as fs.BigIntStats;+ if (path === dir && opts?.bigint && ++bigintStats === 1) return new Proxy(info, { get: (target, key) => key === 'birthtimeNs' ? target.birthtimeNs - 50n : Reflect.get(target, key) });+ return info;+ }) as typeof fs.statSync);+ try {+ const reservation = { version: 1 as const, token: randomUUID(), brainId: randomUUID(), worktreeId: randomUUID(), hostId: randomUUID(), root: dir,+ coordinationPath: join(tmpdir(), 'unused.lock'), initialDevice: null, initialInode: null, initialBirth: null };+ writePhysicalRootStamp(dir, reservation);+ expect(bigintStats).toBeGreaterThanOrEqual(2);+ expect(readJson(join(dir, PHYSICAL_ROOT_MARKER)).birth).toBe(original(dir, { bigint: true }).birthtimeNs.toString());+ } finally { spy.mockRestore(); rmSync(dir, { recursive: true, force: true }); }+ });++ test('[R39] the in-process path-race check and the staging identity still compare birth exactly', () => {+ const nativeTarget = readFileSync(join(ROOT, 'src/core/persistence/native-file-target.ts'), 'utf8');+ expect(nativeTarget).toContain('current.birthtimeNs !== rootInfo.birthtimeNs');+ expect(nativeTarget).not.toContain('samePhysicalBirth');+ const topology = readFileSync(join(ROOT, 'src/core/persistence/topology-recovery.ts'), 'utf8');+ expect(topology).toContain('current.birthNs!==expected.birthNs');+ expect(topology).not.toContain('samePhysicalBirth');+ const recovery = readFileSync(join(ROOT, 'src/core/persistence/physical-root-recovery.ts'), 'utf8');+ expect(recovery).not.toContain('samePhysicalBirth');+ });+});++for (const kind of testBackends()) describe(`physical root birth drift (${kind})`, () => {+ const directory = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-root-birth-')));+ 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 });+ });++ type Fixture = { root: string; source: string; ctx: OperationContext; registration: Awaited<ReturnType<typeof registerLocalWriter>>; marker: string };+ async function fixture(run: (f: Fixture) => Promise<void>) {+ const home = join(directory, randomUUID()), root = join(home, 'root'); mkdirSync(root, { recursive: true });+ const source = `birth-${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 disposePersistenceConsumer(engine);+ 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() {} } };+ await run({ root, source, ctx, registration, marker: join(root, PHYSICAL_ROOT_MARKER) });+ });+ }+ const put = (f: Fixture, slug: string) => withVerifiedLocalRegistration(engine, f.registration, () =>+ operationsByName.put_page!.handler(f.ctx, { source_id: f.source, slug, request_id: randomUUID(),+ content: '---\ntype: note\ntitle: Example\n---\nA managed observation on a drifted root.\n' }))+ // The journal keeps code and message: the message names the relocated-root exit; writer status carries the filled commands.+ .then(r => (r as { state: string }).state, (e: { code?: string; message?: string }) =>+ `${e.code}${e.message?.includes('self-transfer that confirms a relocated root') ? '/relocated-root-exit' : ''}`);+ /** The reporter's table: the stamp written by the creating process sits `delta` ns from what later processes read. */+ const drift = (f: Fixture, delta: bigint) => {+ const stamp = readJson(f.marker);+ writeJson(f.marker, { ...stamp, birth: (BigInt(stamp.birth) + delta).toString() });+ return stamp;+ };+ const refusal = (binding: NonNullable<Awaited<ReturnType<typeof getWorktreeBinding>>>) =>+ acquireWorktree(binding, 0, undefined, engine).then(lock => lock?.release().then(() => null) ?? null, (error: unknown) => error as { code: string; detail?: string; suggestion?: string });++ test('a stamp −50 ns and +47 ns from the live birth time commits writes and rewrites nothing', () => fixture(async f => {+ expect(await put(f, 'notes/before-drift')).toBe('committed');+ for (const delta of [-50n, 47n, -1000n, 1000n]) {+ const stamped = drift(f, delta);+ expect(await put(f, `notes/drift-${delta}`)).toBe('committed');+ expect(readJson(f.marker)).toEqual({ ...stamped, birth: (BigInt(stamped.birth) + delta).toString() });+ writeJson(f.marker, stamped);+ }+ }), 60_000);++ test('a stamp 1 µs + 1 ns or 5 s away refuses with physical_root_directory_changed and the filled relocated-root exit, marker untouched', () => fixture(async f => {+ expect(await put(f, 'notes/before-drift')).toBe('committed');+ const binding = (await getWorktreeBinding(engine, f.source))!;+ for (const delta of [-1001n, 1001n, -5_000_000_000n]) {+ const stamped = drift(f, delta);+ expect(await put(f, `notes/drift-${delta}`)).toBe('recovery_required/relocated-root-exit');+ const refused = await refusal(binding);+ expect(refused).toMatchObject({ code: 'recovery_required', detail: 'physical_root_directory_changed' });+ expect(refused!.suggestion).toContain(`gbrain sources writer transfer prepare ${f.source} --self-transfer --confirm-relocated-root`);+ expect(refused!.suggestion).toContain(`gbrain sources writer transfer accept ${f.source} --path ${f.root} --expected-epoch ${binding.owner_epoch}`);+ expect(refused!.suggestion).toContain('--self-transfer --confirm-relocated-root --admin-intent writer_transfer_accept');+ expect(readJson(f.marker)).toEqual({ ...stamped, birth: (BigInt(stamped.birth) + delta).toString() });+ writeJson(f.marker, stamped);+ }+ expect(await put(f, 'notes/after-restore')).toBe('committed');+ }), 60_000);++ test('negatives: equal birth with a token, brain, worktree, device or inode mismatch, a malformed or zero birth, still refuse', () => fixture(async f => {+ expect(await put(f, 'notes/before')).toBe('committed');+ const binding = (await getWorktreeBinding(engine, f.source))!;+ const stamped = readJson(f.marker);+ const cases: Array<[Record<string, string>, string | undefined]> = [+ [{ token: randomUUID() }, undefined], [{ brainId: randomUUID() }, undefined], [{ worktreeId: randomUUID() }, undefined],+ [{ root: `${f.root}-other` }, undefined],+ [{ inode: (BigInt(stamped.inode) + 1n).toString() }, 'physical_root_directory_changed'],+ [{ inode: (BigInt(stamped.inode) + 1n).toString(), device: (BigInt(stamped.device) + 1n).toString() }, undefined],+ [{ birth: 'abc' }, undefined], [{ birth: '' }, undefined],+ [{ birth: '0' }, 'physical_root_directory_changed'],+ ];+ for (const [change, detail] of cases) {+ writeJson(f.marker, { ...stamped, ...change });+ const refused = await refusal(binding);+ expect(refused).toMatchObject({ code: 'recovery_required' });+ expect(refused!.detail).toBe(detail);+ expect(await put(f, `notes/${Object.keys(change).join('-')}`)).toBe(`recovery_required${detail ? '/relocated-root-exit' : ''}`);+ expect(readJson(f.marker)).toEqual({ ...stamped, ...change });+ expect(readJson(physicalRootReservationPath(f.root))).toMatchObject({ initialBirth: stamped.birth });+ }+ writeJson(f.marker, stamped);+ expect(await put(f, 'notes/after')).toBe('committed');+ }), 60_000);++ test('a directory recreated at the recorded path refuses with the new detail, and the named relocated-root self-transfer restores writes', () => fixture(async f => {+ expect(await put(f, 'notes/before-recreate')).toBe('committed');+ const binding = (await getWorktreeBinding(engine, f.source))!;+ await disposePersistenceConsumer(engine);+ // A restore from backup: new directory at the same path with the same bytes (new inode, new birth time, same device).+ const previous = `${f.root}.previous`;+ renameSync(f.root, previous); mkdirSync(f.root); cpSync(previous, f.root, { recursive: true }); rmSync(previous, { recursive: true, force: true });+ expect(statSync(f.root, { bigint: true }).ino.toString()).not.toBe(readJson(f.marker).inode);+ const refused = await refusal(binding);+ expect(refused).toMatchObject({ code: 'recovery_required', detail: 'physical_root_directory_changed' });+ expect(refused!.suggestion).toContain('--self-transfer --confirm-relocated-root');+ expect(() => assertPhysicalRoot(f.root, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path }))+ .toThrow(expect.objectContaining({ code: 'recovery_required', detail: 'physical_root_directory_changed' }));+ expect(await put(f, 'notes/while-recreated')).toBe('recovery_required/relocated-root-exit');+ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) });+ // Without --confirm-relocated-root the self-transfer still refuses: the waiver is deliberate.+ await expect(administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true })).rejects.toMatchObject({ code: 'recovery_required' });+ const prepared = await administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true, confirm_relocated_root: true }) as { owner_epoch: string; manifest: { digest: string } };+ await administer('writer_transfer_accept', { source_id: f.source, path: f.root, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest, self_transfer: true, confirm_relocated_root: true });+ expect(readJson(f.marker).inode).toBe(statSync(f.root, { bigint: true }).ino.toString());+ expect(await put(f, 'notes/after-relocation')).toBe('committed');+ }), 60_000);++ test('[R39] the prepared-record digest CAS stays exact: a 50 ns drift between prepare and accept refuses the repair', () => fixture(async f => {+ expect(await put(f, 'notes/before')).toBe('committed');+ const binding = (await getWorktreeBinding(engine, f.source))!;+ await disposePersistenceConsumer(engine);+ const reservation = readJson(physicalRootReservationPath(f.root));+ const identity = { brainId: reservation.brainId, worktreeId: binding.worktree_id, hostId: reservation.hostId, coordinationPath: binding.coordination_path! };+ const recovery = inspectPhysicalRootRecovery(f.root, identity);+ const marker = readJson(f.marker);+ expect(() => repairPhysicalRoot(f.root, recovery, identity, true)).not.toThrow();+ const drifted = { ...recovery, stamp: { ...recovery.stamp, birth: (BigInt(recovery.stamp.birth) - 50n).toString() } };+ expect(() => repairPhysicalRoot(f.root, drifted, identity)).toThrow(expect.objectContaining({ code: 'recovery_required' }));+ expect(readJson(f.marker)).toEqual(marker);+ }), 60_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex e9ec45dda4..d1c35735ae 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -105,6 +105,7 @@ test/persistence-sync-fence-holds.test.tstest/persistence-sync-holds.test.tstest/persistence-write-stall.test.tstest/persistence-writer-fences.test.ts+test/physical-root-birth-tolerance-6501.test.tstest/purge-fact.test.tstest/purge-global-marker.test.tstest/remediation-manual-only.test.ts