Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
G3.3 #6517: one origin rule; a shared-origin soft delete keeps the file and publishes database-only
garrytan8dd2bb957069
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex d7f4c5bff3..9571861753 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -24,7 +24,7 @@ link it here rather than raising the cap.| Subsystem | Entry range / scope ||---|---|| [Page identity and writer administration](key-files/page-identity-and-administration.md) | Opaque result IDs, current grants, state-bound ownership changes |-| [Canonical reconciliation](key-files/canonical-reconciliation.md) | Exact-page repair, retained originals, derived atom state, receipt diagnostics |+| [Canonical reconciliation](key-files/canonical-reconciliation.md) | Exact-page repair, retained originals, derived atom state, receipt diagnostics, managed sync discovery and the origin rule (`sync-discovery.ts`, `sync-origin.ts`, `file-claims.ts`) || [Company-brain ingestion](key-files/company-brain.md) | Inspection, admission, receipts, derived relationships and schema; [operator guide](../guides/company-brain-ingestion.md) || [Agent operator contract](key-files/agent-contract.md) | `agent-output.ts`, error registry + docs, notice ledger, `isCallable`, `--json` guard, contract scanner || [Commands (1/6)](key-files/commands-1.md) | `src/commands/agent-logs.ts` through `src/commands/db-repair.ts` |diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 141768d711..c28ac7bccf 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -2,7 +2,7 @@- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) pages the "no other page claims this file" census 100 rows at a time below the source's highest page id, so a common file name no longer refuses; realpath still decides each candidate. Its predicates (`fileClaimCandidatesSql`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page.+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesSql`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page.- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).@@ -15,3 +15,5 @@- `src/core/persistence/managed-mode.ts` — the one reader of the brain's persistence mode (#6482). `readManagedMode` / `readPersistenceBrain` accept exactly one `persistence_brain` row with a boolean `enabled` (optionally `FOR SHARE` / `FOR UPDATE`) and refuse anything else (`storage_error`, `detail: persistence_mode_unknown`, fix `gbrain sources writer status --probe --json`); only a well-formed `enabled: false` row selects the unmanaged path, so a missing, duplicated or malformed row can never route a write around the owner. Every non-test reader of the mode goes through it (`test/persistence-mode-reader-guard.test.ts` lists the few schema and admin-intent files allowed their own statement); `ownership.ts` re-exports it for callers that already import ownership.- `src/core/persistence/sync-slices.ts` — #6349 path-sliced staging for a managed target that exceeds the cursor bound with no commit axis to stage on (a first sync, a `--full` tree walk, one commit above the bound). `sliceEntries` cuts the whole resolved manifest in `(phase, code-unit path)` order: every import slice, then bounded deletion slices, the longest prefix the bound admits. The slice cursor `{ phase, after, head, target }` lives in `op_checkpoints` (`managed-sync-slice`, keyed by source, incarnation and the run's cursor options so a resumed invocation with other exclusions starts over), written or cleared by the slice's checkpoint in the same transaction that leaves `last_commit` untouched until the last slice settles; `sync-discovery.ts` resumes an unfinished target pinned at its recorded commit.+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision/liveness snapshots. #6517: `selectOriginClaimant` (sync-origin.ts) is the one origin rule, applied by the discovery census and by `assertSyncPageOrigin` at preparation and publication: a live page wins over tombstones, several live pages refuse `page_identity_changed` naming the soft-delete exit (`sharedOriginExit`), a single tombstone may be reused, several tombstones stay ambiguous. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).+- `src/core/persistence/file-claims.ts` — the recorded-origin census shared by reconcile and the shared-origin delete (#6517): `fileClaimCandidatesSql` (the paged same-name query, 100 rows per batch below the source's highest page id, served by the v219 name indexes; `source_path` in any spelling or a `file:` URI; tombstones excluded) and `findLiveFileClaimants`, realpath deciding each candidate. In `page-prepare.ts`, a `delete_page` whose file another live page records (`prepareFileTarget` with `sharedOrigin`, before the byte comparison) owns no file: a soft delete publishes database-only with receipt `write_through.skipped: 'shared_origin'` and a warning ("hidden … does not erase", the `gbrain sync --source <id> --no-pull --full` that imports the kept file into the survivor), `validate` re-runs the census under the publication guards (`validateSharedOrigin`: the file moved or removed, or a different claimant set, refuses `source_changed` and never removes the file), and the surviving slug is named only when `slugDisclosable` (authority.ts: the local owner, or a remote writer whose prefix grant, delegated namespace and visibility cover it). A purge of a shared-origin page refuses and names the soft delete. Tests: `test/page-prepare-shared-origin-6517.test.ts`, `test/sync-origin-live-wins-6517.test.ts`, `test/e2e/managed-sync-shared-origin-6517.test.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex a254308058..c1243a051b 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -15,7 +15,7 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`.+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`.- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.Atom completion admits replacement and revision-pinned stale-atom deletion children together.Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex bd2321da70..17530f63b9 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -14,7 +14,6 @@- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Reserved skillpack paths (`skills/` at any depth and `skillpack.json`, `src/core/skill-reserved-paths.ts`) never enter discovery: the shared skill publisher owns them and `managedImportContent` refuses them, so a seeded pack cannot block a sync. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Deleting a file that no page records as its origin (for example a skipped slug twin) while its slug's page keeps another origin commits an explicit no-op receipt (`unownedDeletion`, outcome reason `unowned_deleted_path`) that preserves that live page or tombstone; freeze and publication re-prove that no page owns the path and that the file is still absent. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Active Git holds of the source are re-screened when their blob or working bytes changed, the file left, a `sources retry-held` request names them, the hold predates the current `RECOVERY_VERSION`, or the code is `frontmatter_slug_conflict`, `file_too_large`, `rename_held` or `parser_regression`; holds of now-excluded paths are released at the checkpoint. #6278 (B7): `retryTaken` lists every scheduled path the discovery read (screened as an entry, as a candidate, or no longer eligible); `sync-run.ts` clears them in the transaction that saves the fresh cursor. A held rename destination (or a held path renamed again) carries the hold's `renameFrom` when the old page is unchanged, else `renameHeld` (held as `rename_held` / `rename_source_changed`), and a full walk never deletes an origin a hold's `rename_from` names. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`) sets `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; jobs, serve, the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. `cancelOrphanedWindowGroup` runs before the consumer prepares a claimed group: a window group whose predecessor did not commit is cancelled (`WINDOW_CANCEL_MESSAGE`), never published after a failed page. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the drain cancels the window's queued members (`cancelWindow`) and drops the window; resume re-freezes those entries. Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) cancels a head whose predecessor ended without committing, and under lanes a member whose predecessor is unfinished releases its claim and waits; `cancelOrphanedLaneRows` uses the same rule, so a member released mid-group (its group fell back to the single path and an earlier member went back to the queue) never publishes after that member fails. Test: `test/sync-group-member-order.test.ts`. #6402: a group head whose window predecessor was not admitted is cancelled naming it.- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex cd65160a24..e86cae2267 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -37,6 +37,7 @@ of making a duplicate.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- || `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone do not cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. A page that records no file of its own (no `source_path`, typically written by an older release whose write-through also put `ingested_via` / `ingested_at` / `source_kind` in the file only) reconciles against the file at its slug path only when you add `--adopt-slug-path` to the preview; the refusal names the flag in that case, and apply records that file as the page's origin. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). |+| <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. A purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then `gbrain sync --source <id> --no-pull --full` (or the next sync that imports the file) imports its current content into the surviving page. For a purge, soft-delete instead. After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. || <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. |diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5f909480c4..f9ab949ab6 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -475,6 +475,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },// wave 16 (GBRA-79). `since` is provisional at the current VERSION; the integrator restamps it to the merge-slot version.{ since: '0.60.183.0', text: 'A page purge (`gbrain delete <slug> --purge`) now searches the source\'s write journal for the page\'s claims at preparation, in bounded keyset chunks under the preparation budget (`persistence.maintenance_preparation_ms`), and its publication transaction only re-checks the requests admitted or settled since; the receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`), and `complete: false` means a cap was hit and some requests were not tested. A purge whose remaining in-transaction lookup times out now ends `failed` with `purge_lookup_timeout` (nothing removed, tombstoned or redacted; later writes to the source move again) instead of being requeued as `database_contention` without bound, and a sweep that outruns its budget twice ends `preparation_stalled`; either failure needs a new request_id. A schema migration adds the request-table slug index (`gbrain repair request-indexes` rebuilds it).' },+ { since: '0.60.183.0', text: 'A soft delete (`delete_page`, `gbrain delete <slug>`) of a page whose canonical file another live page of the source records now keeps the file and publishes database-only (receipt `write_through.skipped: shared_origin`, with a warning): the selected database page is hidden; the file and the surviving page remain, and nothing is erased. It used to refuse `source_changed` (the shared file renders the other page), leaving no supported exit for a duplicate-origin twin. Managed sync\'s discovery census and its origin guards now apply one rule: a live page wins the origin over tombstones, several live pages refuse `page_identity_changed` naming that soft delete, a single tombstone may still be reused and several tombstones still refuse. The receipt names the surviving slug to the trusted local owner or to a remote writer whose grant and visibility cover it, never otherwise. A purge of a shared-origin page refuses and names the soft delete. The kept file is imported into the surviving page by the next sync that imports it (`gbrain sync --source <id> --no-pull --full` does it now); edit the file first if it holds the deleted page\'s text.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 925e8d648c..ffb5bce0e6 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -76,7 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],- 'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--adopt-slug-path', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--dry-run', '--enable', '--exclude', '--exit-code', '--expected-epoch', '--explain', '--file', '--fix', '--follow', '--force', '--get', '--get-url', '--git-dir', '--git-path', '--grammar-diagnostics', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--manifest', '--name-only', '--no-accept-pending', '--no-cron', '--no-rebase', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--timeout', '--unset-all', '--wait', '--yes'],+ 'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--adopt-slug-path', '--all', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--dry-run', '--enable', '--exclude', '--exit-code', '--expected-epoch', '--expected-revision', '--explain', '--file', '--fix', '--follow', '--force', '--full', '--get', '--get-url', '--git-dir', '--git-path', '--grammar-diagnostics', '--help', '--id', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--manifest', '--name-only', '--no-accept-pending', '--no-cron', '--no-pull', '--no-rebase', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--preview', '--probe', '--progress-interval', '--progress-json', '--purge', '--push', '--push-only', '--quiet', '--rebase', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--project', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex a602ba4632..de4270ae06 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -373,7 +373,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["name": "delete_page","idempotent": true,"outputRedaction": "no_stored_text",- "description": "Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.",+ "description": "Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. A page whose file another live page of the source records is hidden without touching that file (receipt write_through.skipped: shared_origin): the file and the surviving page remain, nothing is erased, and the next sync imports the file's current content into the surviving page. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A purge of a page whose file is shared refuses and names the soft delete. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.","params": {"source_id": {"type": "string",diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex e65a02bbd0..c934f66ef5 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -383,7 +383,7 @@ const delete_page: Operation = {name: 'delete_page',idempotent: true,outputRedaction: 'no_stored_text',- description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.',+ description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. A page whose file another live page of the source records is hidden without touching that file (receipt write_through.skipped: shared_origin): the file and the surviving page remain, nothing is erased, and the next sync imports the file\'s current content into the surviving page. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A purge of a page whose file is shared refuses and names the soft delete. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.',params: {...PAGE_MUTATION_PARAMS,slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex a865c08113..bb91af577d 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -117,6 +117,16 @@ async function replayedAuthority(engine: SqlEngine, stored: WriteAuthority, operreturn a;}+/**+ * #6517: whether a receipt may name another page's slug to this writer: the trusted local owner always; a remote+ * writer only when the slug is inside its prefix grant (and delegated namespace) and visible to it.+ */+export async function slugDisclosable(engine: SqlEngine, a: WriteAuthority, slug: string): Promise<boolean> {+ if (!a.remote) return true;+ if (!prefixAllowed(a.slugPrefixes, slug)) return false;+ if ((a.delegated || a.restrictedNamespace) && !matchesSlugAllowList(slug, a.delegatedPrefixes ?? [])) return false;+ return authorizePageVisibility(engine, a, slug).then(() => true, () => false);+}/** Caller holds source guards first. FOR SHARE serializes publication against revocation. */export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operation: string, slug: string, lock = false): Promise<void> {if (a.version !== 1 || !a.principal || !a.sourceId || !a.sourceIncarnation) deny('Missing durable write authority.');diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 3b2e658462..622751091f 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -53,7 +53,9 @@ interface PreparedMutationBase {contentUnchanged?: boolean;deferEmbedding?: boolean;/** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */- databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only' | 'sync_excluded';+ databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only' | 'sync_excluded' | 'shared_origin';+ /** #6517: the receipt's `write_through.warning` for a database-only publication, set by `validate` under the publication guards. */+ databaseOnlyWarning?: string;/*** Must perform only transaction-composable database work. `preimage` (#5984)* is the publisher's read of the page under its page guard, after the revision@@ -225,6 +227,7 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Preparedif ((outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {outcome.write_through = { ...outcome.write_through as object, warning: unboundWriteWarning(row.operation, row.source_id, row.authority.databaseOnlyReason === 'unbound_source') };}+ if (prepared.databaseOnlyWarning) outcome.write_through = { ...outcome.write_through as object, warning: prepared.databaseOnlyWarning };}/**diff --git a/src/core/persistence/file-claims.ts b/src/core/persistence/file-claims.tsnew file mode 100644index 0000000000..06e836074b--- /dev/null+++ b/src/core/persistence/file-claims.ts@@ -0,0 +1,82 @@+/**+ * The recorded-origin census: which other live pages of a source record the+ * same canonical file (by `source_path` in any spelling or by a `file:` URI,+ * realpath deciding). Reconcile refuses on any claimant (`reconcile-state.ts`+ * `assertSoleFileClaim`); a soft delete of a page whose file another live page+ * records keeps the file and publishes database-only (`page-prepare.ts`,+ * #6517), re-running this census under publication to revalidate the survivor.+ *+ * #6222/#6254: every page whose recorded path or file URI shares the file's+ * name is a candidate, and realpath decides each one. The census is paged+ * (100 rows per batch, keyset on id) below the source's highest page id read+ * once, so a common name like `2015-09.md` no longer refuses, and concurrent+ * imports cannot make it endless. Both name predicates match the expression+ * indexes of migration v219 (`pages_source_path_name_idx`,+ * `pages_file_uri_name_idx`): the path index normalizes backslashes, so on+ * POSIX the slash-only basename is rechecked on the rows it finds. Tombstones+ * are not claimants (#6517): a soft-deleted twin has given the file up.+ */+import { realpathSync } from 'node:fs';+import { basename, join } from 'node:path';+import { pathToFileURL } from 'node:url';+import type { BrainEngine } from '../engine.ts';+import { resolveSourceLocalFilePath } from '../markdown.ts';+import { opError } from '../ops/contract.ts';+import { isWriteTargetContained } from '../path-confine.ts';+import { recordedPathFromFileUri } from '../write-through.ts';++export interface FileClaimTarget {+ sourceId: string; slug: string; pageId: number; root: string; mode: 'git-root' | 'source-root';+ path: string; canonicalPath: string; recordedUri: string | null;+}+export interface FileClaimant { id: number; slug: string }++export function recordedReconcilePath(root: string, page: { slug: string; source_path?: string | null; source_uri?: string | null },+ mode: 'git-root' | 'source-root'): string | null {+ const path = resolveSourceLocalFilePath(root, page.source_path, page.slug, mode);+ if (path) return path;+ const recorded = recordedPathFromFileUri(page.source_uri, root);+ return recorded ? join(root, recorded) : null;+}+/**+ * The paged census query: $1 source, $2 the page itself, $3/$4 the id window, $5 the file name, $6 its+ * name after the last backslash (POSIX) or the name (Windows), $7 the file-URI names. Exported so the+ * Postgres plan test runs the exact text.+ */+export function fileClaimCandidatesSql(platform: NodeJS.Platform = process.platform): string {+ const pathMatch = platform === 'win32'+ ? `source_path IS NOT NULL AND regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')=$6`+ : `source_path IS NOT NULL AND regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')=$6 AND regexp_replace(btrim(source_path),'^.*/','')=$5`;+ return `SELECT id,slug,source_path,source_uri FROM pages WHERE source_id=$1 AND id<>$2 AND id>$3 AND id<=$4 AND deleted_at IS NULL AND (+ (${pathMatch}) OR (source_uri LIKE 'file:%' AND regexp_replace(source_uri, '^.*/', '')=ANY($7::text[])))+ ORDER BY id LIMIT 100`;+}+/** Every other live page of the source whose recorded origin resolves to the target's canonical file, in id order. */+export async function findLiveFileClaimants(engine: BrainEngine, target: FileClaimTarget): Promise<FileClaimant[]> {+ const { sourceId, slug, root, mode, canonicalPath } = target;+ const fileName = basename(target.path), uriName = pathToFileURL(target.path).pathname.split('/').pop()!;+ const indexedName = fileName.replace(/^.*\\/s, '');+ const uriNames = [...new Set([fileName, uriName, ...(target.recordedUri ? [target.recordedUri.replace(/^.*\//s, '')] : [])])];+ const [ceiling] = await engine.executeRaw<{ id: number | string | null }>('SELECT max(id) AS id FROM pages WHERE source_id=$1', [sourceId]);+ const maxId = Number(ceiling?.id ?? 0);+ const claimants: FileClaimant[] = [];+ for (let afterId = 0; ;) {+ const candidates = await engine.executeRaw<{ id: number | string; slug: string; source_path: string | null; source_uri: string | null }>(+ fileClaimCandidatesSql(),+ [sourceId, target.pageId, afterId, maxId, fileName, process.platform === 'win32' ? fileName : indexedName, uriNames]);+ for (const candidate of candidates) {+ const candidatePath = recordedReconcilePath(root, candidate, mode);+ if (!candidatePath || !isWriteTargetContained(candidatePath, root)) continue;+ let canonicalCandidate: string;+ try { canonicalCandidate = realpathSync(candidatePath); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw opError('source_changed', 'A candidate canonical file origin could not be verified.',+ `Nothing changed. Page ${candidate.slug} in '${sourceId}' records a file that could not be resolved; check that the source checkout is readable, then preview ${slug} again.`);+ }+ if (canonicalCandidate === canonicalPath) claimants.push({ id: Number(candidate.id), slug: candidate.slug });+ }+ if (candidates.length < 100) return claimants;+ afterId = Number(candidates[candidates.length - 1]!.id);+ }+}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 9ae96e169a..7b0a07762d 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -2,7 +2,7 @@ import { isEmbedSkipped } from '../embed-skip.ts';import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { boundedReads } from './bounded-reads.ts';import { isQuarantined, quarantineOutcome } from '../quarantine.ts';-import { existsSync, readFileSync } from 'node:fs';+import { existsSync, readFileSync, realpathSync } from 'node:fs';import { join, relative, sep } from 'node:path';import { matchesAnyGlob } from '../sync.ts';import { syncExcludePatterns } from './sync-discovery.ts';@@ -27,7 +27,8 @@ import { isWriteTargetContained } from '../path-confine.ts';import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';import { assertPurgeParams } from './purge-params.ts';-import { authorizeWrite } from './authority.ts';+import { authorizeWrite, slugDisclosable } from './authority.ts';+import { findLiveFileClaimants, type FileClaimant, type FileClaimTarget } from './file-claims.ts';import { digest, sha256 } from './digest.ts';import { getWorktreeBinding } from './ownership.ts';import type { PreparedContentImport } from './prepared-import.ts';@@ -156,7 +157,9 @@ export async function fileMatchesSnapshot(engine: BrainEngine, slug: string, bytexport async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,content: string | null, hostId?: string, options: { allowMissing?: boolean; deleting?: boolean; capture?: { path: string; hash: string }; activePack?: ParseOpts['activePack']; remote?: boolean;/** #6368: a tombstone purge whose file matches these sync.exclude globs (relative to the source root) owns no file. */- excludeTombstone?: { patterns: string[]; onExcluded: (path: string) => void } } = {}): Promise<PreparedMutation['file']> {+ excludeTombstone?: { patterns: string[]; onExcluded: (path: string) => void };+ /** #6517: a delete whose file another live page of the source records owns no file; the census target and claimants are reported. */+ sharedOrigin?: { onShared: (shared: SharedOrigin) => void } } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;// #6212: a legacy slug (admitted only to delete or restore its existing row) never owns a file: its recorded// source_uri or source_path may name the file of another page, such as the one sync now slugs it to.@@ -191,6 +194,12 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequif (matchesAnyGlob(rel, options.excludeTombstone.patterns)) { options.excludeTombstone.onExcluded(rel); return undefined; }}const before = existsSync(path) ? readFileSync(path) : null;+ if (options.deleting === true && options.sharedOrigin && snapshot && before) {+ const target: FileClaimTarget = { sourceId: row.source_id, slug: row.slug, pageId: snapshot.page.id, root, path, canonicalPath: realpathSync(path),+ mode: mode ?? await scannerSlugRootMode(engine, row.source_id, root), recordedUri: capturedPath ? snapshot.page.source_uri ?? null : null };+ const claimants = await findLiveFileClaimants(engine, target);+ if (claimants.length) { options.sharedOrigin.onShared({ target, claimants }); return undefined; }+ }if (!before && snapshot && !snapshot.page.deleted_at && !options.allowMissing) {// A declared db_only page has no canonical file by design and publishes to// the database only. gbrain.yml is consulted only here, where the write@@ -277,12 +286,40 @@ async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest,* database-only: the file is neither compared nor removed. `excludedPath` names that file; the apply re-checks it.*/async function prepareDeleteFileTarget(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, purge: boolean,- options: Parameters<typeof prepareFileTarget>[5]): Promise<{ file: PreparedMutation['file']; excludedPath: string | null }> {- let excludedPath: string | null = null;+ options: Parameters<typeof prepareFileTarget>[5]): Promise<{ file: PreparedMutation['file']; excludedPath: string | null; shared: SharedOrigin | null }> {+ let excludedPath: string | null = null, shared: SharedOrigin | null = null;const exclude = purge && snapshot.page.deleted_at != null ? await syncExcludePatterns(engine) : [];const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { ...options,- ...(exclude.length ? { excludeTombstone: { patterns: exclude, onExcluded: (path: string) => { excludedPath = path; } } } : {}) });- return { file, excludedPath };+ ...(exclude.length ? { excludeTombstone: { patterns: exclude, onExcluded: (path: string) => { excludedPath = path; } } } : {}),+ sharedOrigin: { onShared: value => { shared = value; } } });+ return { file, excludedPath, shared };+}++/** #6517: the recorded-origin census of a delete's file (file-claims.ts) and the other live pages that record it. */+export interface SharedOrigin { target: FileClaimTarget; claimants: FileClaimant[] }+export const sharedOriginReceipt = (sourceId: string) => 'The selected database page is hidden; the file and the surviving page remain. This does not erase that file\'s contents. '+ + `The file's current content will be imported into the surviving page by the next sync that imports it (gbrain sync --source ${sourceId} --no-pull --full imports every file now); edit the file first if it holds the deleted page's text.`;+/**+ * #6517 [R8]: the survivor is revalidated under publication: the kept file must still resolve to the same real file and the+ * same live pages must still record it; otherwise the delete refuses and the file is never removed as a fallback.+ * [R9]: the receipt names a surviving slug only to the trusted local owner, or to a remote writer whose grant and visibility cover it.+ */+async function validateSharedOrigin(tx: BrainEngine, row: WriteRequest, shared: SharedOrigin): Promise<string> {+ let canonicalPath: string;+ try { canonicalPath = realpathSync(shared.target.path); }+ catch { throw sharedOriginChanged(row, 'the shared file was moved or removed'); }+ const claimants = await findLiveFileClaimants(tx, { ...shared.target, canonicalPath });+ if (claimants.map(page => page.id).join(',') !== shared.claimants.map(page => page.id).join(',')) throw sharedOriginChanged(row, 'the pages recording the shared file changed');+ const named: string[] = [];+ for (const page of claimants) if (await slugDisclosable(tx, row.authority, page.slug)) named.push(page.slug);+ const who = named.length ? `Another page of this source records the same file: ${named.join(', ')}.` : 'Another page of this source records the same file.';+ return `${who} ${sharedOriginReceipt(row.source_id)}`;+}+function sharedOriginChanged(row: WriteRequest, what: string): OperationError {+ const error = pageRefusal('source_changed', `The shared canonical file changed while the delete was prepared: ${what} before it published, so nothing was written and the file was not removed. Submit the delete again with a new request_id; it re-reads the file's claimants.`, row,+ `Page ${row.slug}'s file in source ${row.source_id} was recorded by another live page when this delete was prepared.`, pageFix(row.source_id, row.slug));+ error.detail = 'shared_origin';+ return error;}async function assertStillSyncExcluded(tx: BrainEngine, row: WriteRequest, excludedPath: string): Promise<void> {@@ -307,16 +344,28 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,// Tombstones still own their recorded artifact. Purge always attempts its// removal before the guarded hard-delete and receipt commit; failure rolls// back to the prior row, and replay survives the eventual absence of that row.- const { file, excludedPath } = await prepareDeleteFileTarget(engine, row, snapshot, purge, { allowMissing: purge || options.allowMissingFile, deleting: true, activePack: options.activePack, remote: row.authority.remote });+ const { file, excludedPath, shared } = await prepareDeleteFileTarget(engine, row, snapshot, purge, { allowMissing: purge || options.allowMissingFile, deleting: true, activePack: options.activePack, remote: row.authority.remote });+ // #6517: a purge tombstones content hashes source-wide, so a page whose file another live page records is only soft-deleted.+ if (shared && purge) {+ const error = pageRefusal('source_changed', 'The page\'s canonical file is shared with another live page, so a purge (which tombstones its content source-wide) was refused and nothing was removed, tombstoned or redacted. '+ + `Soft-delete it instead (gbrain delete ${row.slug} --source-id ${row.source_id} --expected-revision <rev>): the page is hidden, the file and the surviving page remain, and nothing is erased.`, row,+ `Another live page of source ${row.source_id} records the file of ${row.slug}.`, pageFix(row.source_id, row.slug));+ error.detail = 'shared_origin';+ throw error;+ }// #6511: the purge's journal sweep runs here, under the preparation budget, never inside the 5 s publication transaction.const preparedPurge: PreparedPagePurge | null = purge ? await preparePagePurge(engine, row, snapshot, clock) : null;- return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), ...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), apply: async tx => {- if (purge && excludedPath !== null) await assertStillSyncExcluded(tx, row, excludedPath);- if (preparedPurge) return purgePageInTransaction(tx, row, snapshot, preparedPurge);- if (!noop) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }- return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop,- recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)' };- } };+ const prepared: PreparedMutation = { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file),+ ...(excludedPath !== null ? { databaseOnlyReason: 'sync_excluded' as const } : {}), ...(shared ? { databaseOnlyReason: 'shared_origin' as const } : {}),+ ...(shared ? { validate: async (tx: BrainEngine) => { prepared.databaseOnlyWarning = await validateSharedOrigin(tx, row, shared); } } : {}),+ apply: async tx => {+ if (purge && excludedPath !== null) await assertStillSyncExcluded(tx, row, excludedPath);+ if (preparedPurge) return purgePageInTransaction(tx, row, snapshot, preparedPurge);+ if (!noop) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }+ return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop,+ recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)' };+ } };+ return prepared;}/**diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 0b056bf932..2f5354ff4a 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -1,16 +1,18 @@import { lstatSync, readFileSync, realpathSync } from 'node:fs';-import { basename, join, relative } from 'node:path';-import { pathToFileURL } from 'node:url';+import { join, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';import { loadConfig, loadConfigWithEngine } from '../config.ts';import { loadOperatorLiterals } from '../content-sanity-literals.ts';-import { parseMarkdown, resolveSourceLocalFilePath } from '../markdown.ts';+import { parseMarkdown } from '../markdown.ts';import { parseDataFrontmatter } from '../data-frontmatter.ts';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { PageSnapshot } from '../page-state/types.ts';import { isWriteTargetContained } from '../path-confine.ts';import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';+import { findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';+import { sharedOriginExit } from './sync-origin.ts';+export { fileClaimCandidatesSql } from './file-claims.ts';import { localHostId } from './identity.ts';import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';import { isUnboundSourcePage } from './unbound-source.ts';@@ -67,67 +69,16 @@ export async function reconcilePolicyDigest(engine: BrainEngine, sourceId: strinexport function staleReconcile(what: string): never {throw new OperationError('source_changed', `Reconciliation preview is stale: ${what}.`, 'Generate a fresh preview; submit a corrected intent with a new request ID.');}-function recordedReconcilePath(root: string, page: { slug: string; source_path?: string | null; source_uri?: string | null },- mode: 'git-root' | 'source-root'): string | null {- const path = resolveSourceLocalFilePath(root, page.source_path, page.slug, mode);- if (path) return path;- const recorded = recordedPathFromFileUri(page.source_uri, root);- return recorded ? join(root, recorded) : null;-}-/**- * The paged census query of {@link assertSoleFileClaim}: $1 source, $2 the page itself, $3/$4 the id- * window, $5 the file name, $6 its name after the last backslash (POSIX) or the name (Windows), $7 the- * file-URI names. Exported so the Postgres plan test runs the exact text.- */-export function fileClaimCandidatesSql(platform: NodeJS.Platform = process.platform): string {- const pathMatch = platform === 'win32'- ? `source_path IS NOT NULL AND regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')=$6`- : `source_path IS NOT NULL AND regexp_replace(replace(btrim(source_path), chr(92), '/'), '^.*/', '')=$6 AND regexp_replace(btrim(source_path),'^.*/','')=$5`;- return `SELECT id,slug,source_path,source_uri FROM pages WHERE source_id=$1 AND id<>$2 AND id>$3 AND id<=$4 AND (- (${pathMatch}) OR (source_uri LIKE 'file:%' AND regexp_replace(source_uri, '^.*/', '')=ANY($7::text[])))- ORDER BY id LIMIT 100`;-}/**- * Refuses when another page of the source records the reconciled file as its own.- *- * #6222/#6254: every page whose recorded path or file URI shares the file's- * name is a candidate, and realpath decides each one. The census is paged- * (100 rows per batch, keyset on id) below the source's highest page id read- * once, so a common name like `2015-09.md` no longer refuses, and concurrent- * imports cannot make it endless; preparation re-reads this state inside the- * coordinated write. Both name predicates match the expression indexes of- * migration v219 (`pages_source_path_name_idx`, `pages_file_uri_name_idx`):- * the path index normalizes backslashes, so on POSIX the slash-only basename- * is rechecked on the rows it finds.+ * Refuses when another live page of the source records the reconciled file as its own+ * (`findLiveFileClaimants`, file-claims.ts: the paged same-name census, realpath deciding).+ * #6517: the refusal names the exit, a soft delete of the page that should not own the file.*/-async function assertSoleFileClaim(engine: BrainEngine, target: { sourceId: string; slug: string; pageId: number; root: string;- mode: 'git-root' | 'source-root'; path: string; canonicalPath: string; recordedUri: string | null }): Promise<void> {- const { sourceId, slug, root, mode, canonicalPath } = target;- const fileName = basename(target.path), uriName = pathToFileURL(target.path).pathname.split('/').pop()!;- const indexedName = fileName.replace(/^.*\\/s, '');- const uriNames = [...new Set([fileName, uriName, ...(target.recordedUri ? [target.recordedUri.replace(/^.*\//s, '')] : [])])];- const [ceiling] = await engine.executeRaw<{ id: number | string | null }>('SELECT max(id) AS id FROM pages WHERE source_id=$1', [sourceId]);- const maxId = Number(ceiling?.id ?? 0);- for (let afterId = 0; ;) {- const candidates = await engine.executeRaw<{ id: number | string; slug: string; source_path: string | null; source_uri: string | null }>(- fileClaimCandidatesSql(),- [sourceId, target.pageId, afterId, maxId, fileName, process.platform === 'win32' ? fileName : indexedName, uriNames]);- for (const candidate of candidates) {- const candidatePath = recordedReconcilePath(root, candidate, mode);- if (!candidatePath || !isWriteTargetContained(candidatePath, root)) continue;- let canonicalCandidate: string;- try { canonicalCandidate = realpathSync(candidatePath); }- catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;- throw opError('source_changed', 'A candidate canonical file origin could not be verified.',- `Nothing changed. Page ${candidate.slug} in '${sourceId}' records a file that could not be resolved; check that the source checkout is readable, then preview ${slug} again.`);- }- if (canonicalCandidate === canonicalPath) throw opError('source_changed', 'Several pages claim the recorded canonical file.',- `Nothing changed. Pages ${slug} and ${candidate.slug} in '${sourceId}' both record the same file, so reconcile cannot tell which owns it; decide with the user which page owns the file before reconciling either.`);- }- if (candidates.length < 100) return;- afterId = Number(candidates[candidates.length - 1]!.id);- }+async function assertSoleFileClaim(engine: BrainEngine, target: FileClaimTarget): Promise<void> {+ const [claimant] = await findLiveFileClaimants(engine, target);+ if (claimant) throw opError('source_changed', 'Several pages claim the recorded canonical file.',+ `Nothing changed. Pages ${target.slug} and ${claimant.slug} in '${target.sourceId}' both record the same file, so reconcile cannot tell which owns it; decide with the user which page owns the file before reconciling either. `+ + sharedOriginExit(target.sourceId, [target.slug, claimant.slug]) + ' Then preview again.');}/*** #6394: `adoptSlugPath` lets a live page with no recorded origin and no database-only marker reconcile against the filediff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex c2ce6b3a93..f2441bb7d7 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -19,7 +19,7 @@ import { isWindowsColonTarget } from './native-file-target.ts';import { ERROR_CATALOGUE } from '../error-catalogue.ts';import { currentCompanyBrainSync } from '../company-brain/profile.ts';import type { CompanyBrainPlan } from '../company-brain/types.ts';-import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';+import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, selectOriginClaimant, sharedOriginExit, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';import { assertManagedSyncActive } from './sync-authority.ts';import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';@@ -446,8 +446,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c...(workingTreeKept ? { workingTreeKept } : {}) };// Freeze all logical identities in one database statement, before yielding// between pages. A later interactive edit must conflict with this scan.- const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string }>(- 'SELECT id,slug,source_path,knowledge_revision FROM pages WHERE source_id=$1', [sourceId]);+ const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string; deleted_at: Date | string | null }>(+ 'SELECT id,slug,source_path,knowledge_revision,deleted_at FROM pages WHERE source_id=$1', [sourceId]);const bySlug = new Map(identities.map(p => [p.slug, p]));const byPath = new Map<string, typeof identities>();const storableIdentities = identities.filter(storable);@@ -460,25 +460,24 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst claims = new Map<string, SyncEntry[]>();for (const entry of selected) {const legacy = legacySyncOrigin(originScope, syncOriginPath(entry.sourcePath));- const origins = [...byPath.get(syncOriginPath(entry.sourcePath)) ?? [],+ const claimants = [...byPath.get(syncOriginPath(entry.sourcePath)) ?? [],...(legacy ? byPath.get(legacy) ?? [] : []).filter(page => sameSyncOrigin(page.source_path!, entry.sourcePath, originScope, page.slug))];- if (origins.length > 1) throw opError('page_identity_changed', 'Several pages claim the same imported origin.',- `Pages ${origins.map(page => page.slug).join(', ')} in ${sourceId} all record ${entry.sourcePath} as their origin; nothing was written. Keep one, remove or re-point the others, then run gbrain sync --no-pull --source ${sourceId}.`,- { fix: { argv: ['gbrain', 'get', '--source', sourceId, '--', origins[0]!.slug], consent: [], actor: 'agent', requires_exclusive: false,- why: 'Shows one of the pages that claim the origin, to decide which one keeps it.' } });- let slug = entry.slug ?? origins[0]?.slug ?? resolveSlugForPath(entry.sourcePath);+ // #6517: one origin rule (sync-origin.ts): a live page wins over tombstones; several live pages, or several tombstones, refuse.+ const { winner: origin, ambiguous } = selectOriginClaimant(claimants);+ if (ambiguous) throw ambiguousOriginRefusal(sourceId, entry.sourcePath, ambiguous === 'several_live' ? claimants.filter(page => page.deleted_at == null) : claimants, ambiguous);+ let slug = entry.slug ?? origin?.slug ?? resolveSlugForPath(entry.sourcePath);if (!slug && entry.action === 'import') slug = parseMarkdown(readSyncContent(discovered, entry), '').slug;if (!slug) throw opError('invalid_params', 'The imported file has no usable page slug.',`${entry.sourcePath} in ${sourceId} yields no page slug from its path or frontmatter; nothing was written. Rename the file or set a frontmatter slug and commit, then run gbrain sync --no-pull --source ${sourceId}.`);- if (!company && entry.action === 'import' && !origins.length && !isCodeFilePath(entry.sourcePath)) {+ if (!company && entry.action === 'import' && !origin && !isCodeFilePath(entry.sourcePath)) {entry.slug = slug;claims.set(slug, [...(claims.get(slug) ?? []), entry]);continue;}- const page = origins[0] ?? bySlug.get(slug);+ const page = origin ?? bySlug.get(slug);const foreignOrigin = page?.source_path != null && !sameSyncOrigin(page.source_path, entry.sourcePath, originScope, page.slug);// Deleting a file that no page records (a skipped slug twin) must not delete the page another file backs.- const unownedDeletion = foreignOrigin && entry.action === 'delete' && !origins.length && !company;+ const unownedDeletion = foreignOrigin && entry.action === 'delete' && !origin && !company;if (foreignOrigin && !unownedDeletion) {const error = new OperationError('page_identity_changed', 'A different origin occupies the imported slug.',`Page ${slug} in source ${sourceId} records the origin '${page.source_path}', but sync found it at '${entry.sourcePath}'. On the brain host, rename or move one of the two files so each page has one origin, commit, then run gbrain sync --source ${sourceId} --no-pull --retry-failed.`);@@ -554,6 +553,14 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}return discovered;}+/** #6517: several live pages (the soft-delete exit is named) or several tombstones record one imported origin. */+function ambiguousOriginRefusal(sourceId: string, sourcePath: string, named: Array<{ slug: string }>, ambiguous: 'several_live' | 'several_tombstones'): OperationError {+ return opError('page_identity_changed', 'Several pages claim the same imported origin.',+ `Pages ${named.map(page => page.slug).join(', ')} in ${sourceId} all record ${sourcePath} as their origin; nothing was written. `+ + (ambiguous === 'several_live' ? `${sharedOriginExit(sourceId, named.map(page => page.slug))} Then` : 'Keep one, remove or re-point the others, then') + ` run gbrain sync --no-pull --source ${sourceId}.`,+ { fix: { argv: ['gbrain', 'get', '--source', sourceId, '--', named[0]!.slug], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows one of the pages that claim the origin, to decide which one keeps it.' } });+}export function readSyncContent(discovery: SyncDiscovery, entry: SyncEntry): string {if (entry.working) {const bytes = readSyncFile(discovery.root, entry.path);diff --git a/src/core/persistence/sync-origin.ts b/src/core/persistence/sync-origin.tsindex 1903cccb28..a98216759b 100644--- a/src/core/persistence/sync-origin.ts+++ b/src/core/persistence/sync-origin.ts@@ -68,6 +68,28 @@ export function assertDistinctSyncOrigins(paths: Iterable<string>, platform = pr}}+/**+ * #6517: the one rule for which page an origin file identifies when several+ * pages of the source record it, used by discovery's census and by+ * `assertSyncPageOrigin` (preparation and publication), so the two guards+ * never disagree. A live page beats tombstones (a soft-deleted twin no longer+ * claims the file); several live pages are ambiguous; with no live page a+ * single tombstone may be reused (the file resurrects the page) and several+ * tombstones stay ambiguous.+ */+export function selectOriginClaimant<T extends { deleted_at: unknown }>(pages: readonly T[]): { winner: T | null; ambiguous: 'several_live' | 'several_tombstones' | null } {+ const live = pages.filter(page => page.deleted_at == null);+ if (live.length > 1) return { winner: null, ambiguous: 'several_live' };+ if (live.length === 1) return { winner: live[0]!, ambiguous: null };+ if (pages.length > 1) return { winner: null, ambiguous: 'several_tombstones' };+ return { winner: pages[0] ?? null, ambiguous: null };+}++/** The exit a shared-origin refusal names: soft-delete the page that should not own the file; the file stays for the survivor. */+export function sharedOriginExit(sourceId: string, slugs: readonly string[]): string {+ return `Soft-delete the page that should not own the file (gbrain delete <slug> --source-id ${sourceId} --expected-revision <rev>, one of ${slugs.join(', ')}): a page whose file another live page records is hidden without touching the file, which the surviving page keeps.`;+}+export async function assertSyncPageOrigin(engine: BrainEngine, sourceId: string, sourcePath: string, pageId: number | null, requireOrigin = false,context?: SyncOriginScope): Promise<void> {const origin = syncOriginPath(sourcePath);@@ -75,13 +97,16 @@ export async function assertSyncPageOrigin(engine: BrainEngine, sourceId: stringconst candidates = [origin, ...(legacy ? [legacy] : [])];const pathSql = process.platform === 'win32' ? "lower(replace(source_path,chr(92),'/'))=ANY($2::text[])" : 'source_path=ANY($2::text[])';const key = (path: string) => process.platform === 'win32' ? syncOriginPath(path).toLowerCase() : syncOriginPath(path);- const rows = await engine.executeRaw<{ id: number; slug: string; source_path: string }>(- `SELECT id,slug,source_path FROM pages WHERE source_id=$1 AND ${pathSql}`, [sourceId, candidates.map(key)]);+ const rows = await engine.executeRaw<{ id: number; slug: string; source_path: string; deleted_at: Date | string | null }>(+ `SELECT id,slug,source_path,deleted_at FROM pages WHERE source_id=$1 AND ${pathSql}`, [sourceId, candidates.map(key)]);const pages = rows.filter(page => legacy === null || key(page.source_path) !== key(legacy) || sameSyncOrigin(page.source_path, origin, context, page.slug));- if (pages.length > 1 || requireOrigin && pageId !== null && pages.length !== 1 ||- pages.some(page => page.id !== pageId || !sameSyncOrigin(page.source_path, origin, context, page.slug))) {+ const { winner, ambiguous } = selectOriginClaimant(pages);+ if (ambiguous || requireOrigin && pageId !== null && !winner ||+ winner && (winner.id !== pageId || !sameSyncOrigin(winner.source_path, origin, context, winner.slug))) {throw opError('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.',- `${JSON.stringify(sourcePath)} in source ${sourceId} now maps to a different page or to several pages, so this import was refused. Check the source's writer status before syncing again; do not force the import.`,+ `${JSON.stringify(sourcePath)} in source ${sourceId} now maps to a different page or to several pages, so this import was refused. `+ + (ambiguous === 'several_live' ? sharedOriginExit(sourceId, pages.filter(page => page.deleted_at == null).map(page => page.slug)) + ' Then sync again.'+ : "Check the source's writer status before syncing again; do not force the import."),{ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', why: `Shows source ${sourceId}'s writer and pending requests, read-only.`, requires_exclusive: false } });}}diff --git a/test/e2e/managed-sync-shared-origin-6517.test.ts b/test/e2e/managed-sync-shared-origin-6517.test.tsnew file mode 100644index 0000000000..5325d4eadc--- /dev/null+++ b/test/e2e/managed-sync-shared-origin-6517.test.ts@@ -0,0 +1,153 @@+/**+ * #6517 (GBRA-79 wave 16, G3.3 [R7]): the managed sync path end to end with a+ * duplicate-origin twin. Two live pages of the source record one file: the+ * run refuses `page_identity_changed` and names the soft-delete exit. After+ * the loser is soft-deleted (the shared-origin delete keeps the file), the run+ * imports the file into the survivor through both origin guards (discovery+ * census, `assertSyncPageOrigin` at preparation and publication), then edits+ * and deletes the survivor from the checkout. A single tombstone still+ * resurrects when its file returns; two tombstones still refuse; a winner+ * whose liveness changes between the census and the publication never+ * receives the import. Master: the twin's tombstone kept every run refusing+ * (`assertSyncPageOrigin` counted tombstones), the Eng P1 probe.+ *+ * PGLite and, with DATABASE_URL, Postgres. Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+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 { operations, type OperationContext } from '../../src/core/operations.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { readManagedSyncFailures } from '../../src/core/persistence/sync-failures.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { withEnv } from '../helpers/with-env.ts';++const op = (name: string) => operations.find(o => o.name === name)!;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message = 'synthetic content') => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;++for (const backend of testBackends()) describe(`[${backend}] #6517 managed sync with a duplicate-origin twin`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const home = mkdtempSync(join(tmpdir(), `gbrain-6517-e2e-${backend}-`));+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+ const sync = (opts: Record<string, unknown>) => withEnv(env, () => performManagedSync(engine, opts as Parameters<typeof performManagedSync>[1]));+ const page = async (sourceId: string, slug: string) => (await engine.executeRaw<{ id: number; deleted_at: string | null; compiled_truth: string; source_path: string | null }>(+ 'SELECT id,deleted_at,compiled_truth,source_path FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0] ?? null;+ const coordinated = (sourceId: string, sql: string, params: unknown[]) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+ async function softDelete(sourceId: string, slug: string) {+ const context: OperationContext = { engine, config: { engine: backend, embedding_disabled: true } as never, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId };+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }))!;+ return withEnv(env, () => op('delete_page').handler(context, { slug, source_id: sourceId, request_id: randomUUID(), expected_revision: snapshot.revision })) as Promise<Record<string, any>>;+ }+ /** A managed git source whose `alpha.md` synced into page `alpha`, plus a live page `alpha-twin` recording the same file. */+ async function twins() {+ const id = `tw-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ const file = join(root, 'alpha.md');+ writeFileSync(file, note('Alpha, version one.')); commit(root);+ 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,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await withEnv(env, () => claimWorktree(engine, id, root));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ expect((await sync(opts)).status).toBe('first_sync');+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.putPage('alpha-twin', { type: 'note', title: 'Twin', compiled_truth: 'A twin recording alpha.',+ timeline: '', frontmatter: {}, content_hash: 'twin', source_path: 'alpha.md' }, { sourceId: id }), TEST_WRITE_ATTRIBUTION));+ return { id, root, file, opts };+ }++ beforeAll(async () => {+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ installFaultHook(undefined);+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); });+ await engine.disconnect(); await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+ }, 60_000);++ test('two live claimants refuse the run and name the exit; after the loser is soft-deleted the file imports, edits and deletes through both guards; a single tombstone resurrects', async () => {+ const f = await twins();+ writeFileSync(f.file, note('Alpha, version two.')); commit(f.root, 'version two');+ const refused = await sync(f.opts).then(() => null, error => error as Error & { code?: string; suggestion?: string });+ expect(refused?.code).toBe('page_identity_changed');+ expect(refused?.message).toContain('Several pages claim the same imported origin');+ expect(refused?.suggestion).toContain('Soft-delete the page that should not own the file');+ expect((await page(f.id, 'alpha'))!.compiled_truth).toContain('version one');+ // The exit: the twin is hidden, the file stays.+ expect(await softDelete(f.id, 'alpha-twin')).toMatchObject({ state: 'committed', write_through: { skipped: 'shared_origin' } });+ expect(readFileSync(f.file, 'utf8')).toBe(note('Alpha, version two.'));+ // Import through discovery and both assertSyncPageOrigin calls (master: page_identity_changed, the tombstone still counted).+ const imported = await sync(f.opts);+ expect(imported).toMatchObject({ status: 'synced', filesImported: 1 });+ expect(imported.held_count ?? 0).toBe(0); expect(imported.managedWrite).toBeUndefined();+ const survivor = (await page(f.id, 'alpha'))!;+ expect(survivor.compiled_truth).toContain('version two');+ expect((await page(f.id, 'alpha-twin'))!.deleted_at).not.toBeNull();+ // Edit the survivor from the checkout.+ writeFileSync(f.file, note('Alpha, version three.')); commit(f.root, 'version three');+ expect(await sync(f.opts)).toMatchObject({ status: 'synced', filesImported: 1 });+ expect((await page(f.id, 'alpha'))!.compiled_truth).toContain('version three');+ // Delete the survivor from the checkout: a managed_sync_delete with requireOrigin, the tombstone twin not counted.+ rmSync(f.file); commit(f.root, 'remove alpha');+ const deleted = await sync(f.opts);+ expect(deleted.status).toBe('synced'); expect(deleted.managedWrite).toBeUndefined();+ expect((await page(f.id, 'alpha'))!.deleted_at).not.toBeNull();+ expect((await page(f.id, 'alpha'))!.id).toBe(survivor.id);+ // Two tombstones record the file: its return is ambiguous, as before.+ writeFileSync(f.file, note('Alpha returns.')); commit(f.root, 'alpha returns');+ const ambiguous = await sync(f.opts).then(() => null, error => error as Error & { code?: string });+ expect(ambiguous?.code).toBe('page_identity_changed');+ expect((await page(f.id, 'alpha'))!.deleted_at).not.toBeNull();+ // Point the twin tombstone elsewhere: one tombstone left, which the file resurrects (same page id).+ await coordinated(f.id, 'UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug=$2', [f.id, 'alpha-twin']);+ const resurrected = await sync(f.opts);+ expect(resurrected.managedWrite).toBeUndefined();+ const back = (await page(f.id, 'alpha'))!;+ expect(back).toMatchObject({ id: survivor.id, deleted_at: null });+ expect(back.compiled_truth).toContain('Alpha returns');+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ }, 180_000);++ test('a winner whose liveness changes between the census and the publication never receives the import', async () => {+ const f = await twins();+ expect(await softDelete(f.id, 'alpha-twin')).toMatchObject({ state: 'committed', write_through: { skipped: 'shared_origin' } });+ writeFileSync(f.file, note('Alpha, version two.')); commit(f.root, 'version two');+ // Between the census (winner: alpha) and the publication, the twin comes back and alpha is hidden.+ let swapped = false;+ installFaultHook(async (point, detail) => {+ if (point !== 'consumer:preparing' || detail.sourceId !== f.id || swapped) return;+ swapped = true;+ await coordinated(f.id, 'UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug=$2', [f.id, 'alpha']);+ await coordinated(f.id, 'UPDATE pages SET deleted_at=NULL WHERE source_id=$1 AND slug=$2', [f.id, 'alpha-twin']);+ });+ let result: Awaited<ReturnType<typeof performManagedSync>> | null = null, error: (Error & { code?: string }) | null = null;+ try { result = await sync(f.opts); } catch (e) { error = e as Error & { code?: string }; } finally { installFaultHook(undefined); }+ expect(swapped).toBe(true);+ // Neither page received version two through the stale census: the twin keeps its body, alpha stays hidden and unchanged.+ expect((await page(f.id, 'alpha-twin'))!).toMatchObject({ deleted_at: null, compiled_truth: 'A twin recording alpha.' });+ expect((await page(f.id, 'alpha'))!.compiled_truth).toContain('version one');+ expect((await page(f.id, 'alpha'))!.deleted_at).not.toBeNull();+ expect(error ? error.code : result!.status === 'synced' && (result!.held_count ?? 0) === 0 && !result!.managedWrite ? 'clean import' : 'refused').not.toBe('clean import');+ expect(existsSync(f.file)).toBe(true);+ // Once the twin is the one live claimant, the next run (a new request past the frozen refusal) imports the file into it.+ const next = await sync({ ...f.opts, retryFailed: true });+ expect(next.managedWrite).toBeUndefined();+ expect((await page(f.id, 'alpha-twin'))!.compiled_truth).toContain('version two');+ }, 180_000);+});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 5180c3c803..0cc2c36a87 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 231864,- "stdoutSha256": "7c78c1bc5229533a82e47b508d6208d0d9e993b8e1129664b363a3656b0a193f",+ "stdoutBytes": 232218,+ "stdoutSha256": "95d6ba41a73a47aab417f7e6bd286c7cf3334ae9a62e659711bc0d1bfdcdd594","toolNames": ["remember","entity",@@ -559,7 +559,7 @@"scope": "write"},{- "description": "Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.",+ "description": "Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. A page whose file another live page of the source records is hidden without touching that file (receipt write_through.skipped: shared_origin): the file and the surviving page remain, nothing is erased, and the next sync imports the file's current content into the surviving page. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A purge of a page whose file is shared refuses and names the soft delete. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.","idempotent": true,"local_only": false,"mutating": true,diff --git a/test/managed-sync-page-fault-holds.test.ts b/test/managed-sync-page-fault-holds.test.tsindex a87d19680b..e05621fc58 100644--- a/test/managed-sync-page-fault-holds.test.ts+++ b/test/managed-sync-page-fault-holds.test.ts@@ -56,7 +56,7 @@ function countDiscoveries(engine: BrainEngine, sourceId: string): { count: () =>const executeRaw = engine.executeRaw;let reads = 0;engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {- if (params?.[0] === sourceId && sql.includes('SELECT id,slug,source_path,knowledge_revision FROM pages')) reads++;+ if (params?.[0] === sourceId && sql.includes('SELECT id,slug,source_path,knowledge_revision,deleted_at FROM pages')) reads++;return executeRaw.call(this, sql, params);} as BrainEngine['executeRaw'];return { count: () => reads, restore: () => { engine.executeRaw = executeRaw; } };diff --git a/test/page-prepare-shared-origin-6517.test.ts b/test/page-prepare-shared-origin-6517.test.tsnew file mode 100644index 0000000000..2c17e8e8fd--- /dev/null+++ b/test/page-prepare-shared-origin-6517.test.ts@@ -0,0 +1,235 @@+/**+ * #6517 (GBRA-79 wave 16, G3.3 [R8][R9][R10][UC4]): two live pages of a+ * managed source record the same origin file (a duplicate-origin twin). Master+ * left no supported exit: `delete_page` of either refused `source_changed`+ * (the shared file's bytes render the other twin), reconcile refused the+ * survivor ("Several pages claim the recorded canonical file") and every sync+ * refused `page_identity_changed`.+ *+ * Now a soft delete of a page whose file another live page records keeps the+ * file and publishes database-only: receipt `write_through.skipped ===+ * 'shared_origin'` with the "hidden, not erased" text, file bytes unchanged,+ * the survivor's reconcile state readable again and the next managed sync+ * importing the file into the survivor (both choices of loser; `source_path`+ * in plain and `./`-prefixed spellings, and a `file:` URI). The survivor is+ * revalidated under publication: moved or removed during preparation, the+ * delete refuses and the file is never removed as a fallback. A purge of a+ * shared-origin page refuses and names the soft delete; a page whose origin is+ * not shared still refuses on drift. [R9]: the receipt names the surviving+ * slug to the trusted local owner and to a remote writer whose grant and+ * visibility cover it, never otherwise (no slug, no path in the receipt JSON).+ *+ * PGLite and, with DATABASE_URL, Postgres. Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readReconcileState } from '../src/core/persistence/reconcile-state.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const op = (name: string) => operations.find(o => o.name === name)!;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message = 'synthetic content') => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const note = (title: string, body: string) => `---\ntitle: ${title}\n---\n${body}\n`;+type Twin = 'path' | 'dot-path' | 'uri';++for (const backend of testBackends()) describe(`[${backend}] #6517 delete of a shared-origin page`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const home = mkdtempSync(join(tmpdir(), `gbrain-6517-${backend}-`));+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+ const context = (sourceId: string): OperationContext => ({ engine, config: { engine: backend, embedding_disabled: true } as never,+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId });+ const call = (sourceId: string, name: string, params: Record<string, unknown>) => withEnv(env, () => op(name).handler(context(sourceId), params)) as Promise<Record<string, any>>;+ const page = async (sourceId: string, slug: string) => (await engine.executeRaw<{ id: number; deleted_at: string | null; compiled_truth: string; knowledge_revision: string; source_path: string | null }>(+ 'SELECT id,deleted_at,compiled_truth,knowledge_revision,source_path FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0] ?? null;+ const revision = async (sourceId: string, slug: string) => (await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }))!.revision;+ const count = async (sql: string, params: unknown[] = []) => Number((await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM ${sql}`, params))[0]!.n);+ async function failure(fn: () => Promise<unknown>): Promise<OperationError> {+ try { await fn(); } catch (error) { expect(error).toBeInstanceOf(OperationError); return error as OperationError; }+ throw new Error('expected a refusal');+ }+ /** A managed git source with one synced file `<name>.md` (page `<name>`) and a second live page recording the same file. */+ async function twins(twin: Twin, names: { file: string; twin: string } = { file: 'alpha', twin: 'alpha-twin' }, body = note('Alpha', `Observation of ${names.file}, version one.`)) {+ const id = `tw-${randomUUID().replace(/-/g, '').slice(0, 12)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ const file = join(root, `${names.file}.md`), bytes = body;+ mkdirSync(join(file, '..'), { recursive: true });+ writeFileSync(file, bytes); commit(root);+ 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,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await withEnv(env, () => claimWorktree(engine, id, root));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ expect((await withEnv(env, () => performManagedSync(engine, opts))).status).toBe('first_sync');+ expect((await page(id, names.file))?.source_path).toBe(`${names.file}.md`);+ const sourcePath = twin === 'uri' ? null : twin === 'dot-path' ? `./${names.file}.md` : `${names.file}.md`;+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.putPage(names.twin, { type: 'note', title: 'Twin', compiled_truth: `A twin recording ${names.file}.`,+ timeline: '', frontmatter: {}, content_hash: `twin-${names.file}`, source_path: sourcePath, source_uri: twin === 'uri' ? pathToFileURL(file).href : null }, { sourceId: id }), TEST_WRITE_ATTRIBUTION));+ return { id, root, file, bytes, opts, names };+ }+ const coordinated = (sourceId: string, sql: string, params: unknown[]) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+ const del = (sourceId: string, slug: string, extra: Record<string, unknown> = {}) => async () =>+ call(sourceId, 'delete_page', { slug, source_id: sourceId, request_id: randomUUID(), expected_revision: await revision(sourceId, slug), ...extra });++ beforeAll(async () => {+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ installFaultHook(undefined);+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); });+ await engine.disconnect(); await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+ }, 60_000);++ for (const twin of ['path', 'dot-path', 'uri'] as Twin[]) test(`[UC4][R10] deleting the twin (${twin} origin) keeps the file, publishes shared_origin, and the survivor reconciles and syncs again`, async () => {+ const f = await twins(twin);+ const survivorBefore = (await page(f.id, 'alpha'))!;+ const result = await (await del(f.id, 'alpha-twin'))();+ expect(result).toMatchObject({ state: 'committed', status: 'soft_deleted', write_through: { written: false, skipped: 'shared_origin' } });+ expect(result.write_through.warning).toContain('Another page of this source records the same file: alpha.');+ expect(result.write_through.warning).toContain('hidden');+ expect(result.write_through.warning).toContain('does not erase');+ expect(readFileSync(f.file)).toEqual(Buffer.from(f.bytes));+ expect((await page(f.id, 'alpha-twin'))!.deleted_at).not.toBeNull();+ expect(await page(f.id, 'alpha')).toEqual(survivorBefore);+ // The survivor's reconcile state reads again (master: 'Several pages claim the recorded canonical file.').+ const registration = await registerLocalWriter(engine, 'cli');+ const state = await withEnv(env, () => withVerifiedLocalRegistration(engine, registration, () => readReconcileState(engine, f.id, 'alpha')));+ expect(state.snapshot.page.slug).toBe('alpha');+ expect(state.raw).toEqual(Buffer.from(f.bytes));+ // A `./` spelling is a reconcile-only legacy origin form: sync discovery refuses it as a sync origin (unchanged), so the sync leg covers the two sync-valid forms.+ if (twin === 'dot-path') return;+ // The next managed sync imports the file (edited meanwhile) into the survivor through both origin guards.+ writeFileSync(f.file, note('Alpha', 'Observation of alpha, version two.')); commit(f.root, 'version two');+ const synced = await withEnv(env, () => performManagedSync(engine, f.opts));+ expect(synced).toMatchObject({ status: 'synced', filesImported: 1 });+ expect(synced.held_count ?? 0).toBe(0); expect(synced.managedWrite).toBeUndefined();+ expect((await page(f.id, 'alpha'))!.compiled_truth).toContain('version two');+ expect((await page(f.id, 'alpha-twin'))!.deleted_at).not.toBeNull();+ }, 120_000);++ test('[R8] deleting the page the file was synced into keeps the file for the twin, which the next sync imports the file into', async () => {+ const f = await twins('path');+ const result = await (await del(f.id, 'alpha'))();+ expect(result).toMatchObject({ state: 'committed', status: 'soft_deleted', write_through: { written: false, skipped: 'shared_origin' } });+ expect(result.write_through.warning).toContain('alpha-twin');+ expect(result.write_through.warning).toContain(`gbrain sync --source ${f.id} --no-pull --full`);+ expect(readFileSync(f.file)).toEqual(Buffer.from(f.bytes));+ // The kept file still holds the deleted page's text and is unchanged in git, so an incremental sync has nothing to import;+ // the full sync the receipt names imports it into the survivor.+ expect((await withEnv(env, () => performManagedSync(engine, f.opts))).status).toBe('up_to_date');+ expect((await page(f.id, 'alpha-twin'))!.compiled_truth).toBe('A twin recording alpha.');+ const synced = await withEnv(env, () => performManagedSync(engine, { ...f.opts, full: true }));+ expect(synced.managedWrite).toBeUndefined();+ expect(synced.held_count ?? 0).toBe(0);+ const survivor = (await page(f.id, 'alpha-twin'))!;+ expect(survivor.deleted_at).toBeNull();+ expect(survivor.compiled_truth).toContain('Observation of alpha, version one.');+ expect((await page(f.id, 'alpha'))!.deleted_at).not.toBeNull();+ // The import's write-back normalizes the file's frontmatter; its body is the observation, and the checkout is committed.+ expect(readFileSync(f.file, 'utf8')).toContain('Observation of alpha, version one.');+ }, 120_000);++ test('[R8] a purge of a shared-origin page refuses and names the soft delete; nothing is tombstoned', async () => {+ const f = await twins('path');+ const before = { purges: await count('page_purges'), twin: await page(f.id, 'alpha-twin'), alpha: await page(f.id, 'alpha') };+ const error = await failure(await del(f.id, 'alpha-twin', { purge: true }));+ expect(error.code).toBe('source_changed');+ expect(error.message).toContain('shared with another live page');+ expect(error.message).toContain('Soft-delete it instead');+ expect(error.message).toContain('nothing is erased');+ expect(error.writeRequest?.state).toBe('conflict');+ expect(await count('page_purges')).toBe(before.purges);+ expect(await page(f.id, 'alpha-twin')).toEqual(before.twin);+ expect(await page(f.id, 'alpha')).toEqual(before.alpha);+ expect(readFileSync(f.file)).toEqual(Buffer.from(f.bytes));+ }, 120_000);++ test('[R8] a page whose origin is not shared still refuses on drift: the fix does not widen the window', async () => {+ const f = await twins('path');+ expect((await (await del(f.id, 'alpha-twin'))()).write_through.skipped).toBe('shared_origin');+ writeFileSync(f.file, note('Alpha', 'An uncoordinated local edit.'));+ const error = await failure(await del(f.id, 'alpha'));+ expect(error.code).toBe('source_changed');+ expect(error.message).toContain('uncoordinated local edit');+ expect((await page(f.id, 'alpha'))!.deleted_at).toBeNull();+ expect(readFileSync(f.file, 'utf8')).toBe(note('Alpha', 'An uncoordinated local edit.'));+ }, 120_000);++ test('[R8] the survivor is revalidated under publication: removed, moved or no longer a claimant during preparation refuses, and the file is never removed', async () => {+ const f = await twins('path');+ const moved = join(f.root, 'alpha-moved.md');+ const cases: Array<{ name: string; disturb: () => Promise<void>; restore: () => Promise<void>; what: string }> = [+ { name: 'file moved', disturb: async () => renameSync(f.file, moved), restore: async () => renameSync(moved, f.file), what: 'moved or removed' },+ { name: 'survivor deleted', disturb: async () => { await coordinated(f.id, 'UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug=$2', [f.id, 'alpha']); },+ restore: async () => { await coordinated(f.id, 'UPDATE pages SET deleted_at=NULL WHERE source_id=$1 AND slug=$2', [f.id, 'alpha']); }, what: 'pages recording the shared file changed' },+ { name: 'survivor re-pointed', disturb: async () => { await coordinated(f.id, 'UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, 'alpha', 'elsewhere.md']); },+ restore: async () => { await coordinated(f.id, 'UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, 'alpha', 'alpha.md']); }, what: 'pages recording the shared file changed' },+ ];+ for (const c of cases) {+ const requestId = randomUUID();+ installFaultHook(async (point, detail) => { if (point === 'consumer:prepared' && detail.requestId === requestId) await c.disturb(); });+ try {+ const error = await failure(async () => call(f.id, 'delete_page', { slug: 'alpha-twin', source_id: f.id, request_id: requestId, expected_revision: await revision(f.id, 'alpha-twin') }));+ expect(error.code).toBe('source_changed');+ expect(error.message).toContain('shared canonical file changed');+ expect(error.message).toContain(c.what);+ expect(error.writeRequest?.state).toBe('conflict');+ } finally { installFaultHook(undefined); await c.restore(); }+ expect((await page(f.id, 'alpha-twin'))!.deleted_at).toBeNull();+ expect(existsSync(f.file)).toBe(true);+ expect(readFileSync(f.file)).toEqual(Buffer.from(f.bytes));+ }+ // With nothing disturbed, the same delete commits.+ expect((await (await del(f.id, 'alpha-twin'))()).write_through.skipped).toBe('shared_origin');+ }, 180_000);++ test('[R9] a remote writer learns the surviving slug only when its grant and visibility cover it', async () => {+ const cases = [+ { label: 'out of prefix', names: { file: 'private-area/keeper-7731', twin: 'notes/twin-a' }, visible: false },+ { label: 'in prefix', names: { file: 'notes/keeper-8842', twin: 'notes/twin-b' }, visible: true },+ { label: 'in prefix but private', names: { file: 'notes/keeper-9953', twin: 'notes/twin-c' }, visible: false, privateSurvivor: true },+ ];+ for (const c of cases) {+ const f = await twins('path', c.names, c.privateSurvivor ? `---\ntitle: Keeper\nvisibility: private\n---\nPrivate observation.\n` : undefined);+ if (c.privateSurvivor) expect((await engine.executeRaw<{ v: string }>("SELECT frontmatter->>'visibility' AS v FROM pages WHERE source_id=$1 AND slug=$2", [f.id, c.names.file]))[0]!.v).toBe('private');+ const registration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes/'] });+ const auth = { token: 'fixture', clientId: `fixture-${c.names.twin.replace('/', '-')}`, scopes: ['read', 'write'], sourceId: f.id, boundSlugPrefixes: ['notes/'] };+ const expected = await revision(f.id, c.names.twin);+ const result = await withEnv(env, () => withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, 'delete_page',+ { slug: c.names.twin, source_id: f.id, request_id: randomUUID(), expected_revision: expected },+ { remote: true, config: { engine: backend }, sourceId: f.id, auth, logger: { info() {}, warn() {}, error() {} }, writeWaitMs: 30_000 }))) as { content: Array<{ text: string }> };+ const text = result.content.map(part => part.text).join('\n');+ expect(text).toContain('"skipped":"shared_origin"');+ expect(text).toContain('hidden');+ if (c.visible) expect(text).toContain(`records the same file: ${c.names.file}.`);+ else {+ expect(text).toContain('Another page of this source records the same file.');+ expect(text).not.toContain(c.names.file.split('/').pop()!);+ expect(text).not.toContain(f.root);+ }+ expect((await page(f.id, c.names.twin))!.deleted_at).not.toBeNull();+ expect(existsSync(f.file)).toBe(true);+ }+ }, 180_000);+});diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex 76869504a2..ae7f200f79 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -254,7 +254,7 @@ test('repeated slices reuse one manifest and hold an intervening page identity cconst executeRaw = engine.executeRaw;let manifestReads = 0;engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {- if (params?.[0] === f.id && sql.includes('SELECT id,slug,source_path,knowledge_revision FROM pages')) manifestReads++;+ if (params?.[0] === f.id && sql.includes('SELECT id,slug,source_path,knowledge_revision,deleted_at FROM pages')) manifestReads++;return executeRaw.call(this, sql, params);} as BrainEngine['executeRaw'];try {diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.tsindex 47942d0968..b12482aaf4 100644--- a/test/persistence-sync-failures.serial.test.ts+++ b/test/persistence-sync-failures.serial.test.ts@@ -268,7 +268,7 @@ test('managed failure retry hints name the failed cursor options locally, shell-const d = await fixture(engine, { 'note.md': 'A stable discovery observation.\n' });const execute = engine.executeRaw;engine.executeRaw = function (this: BrainEngine, sql: string, params?: unknown[]) {- if (sql.includes('SELECT id,slug,source_path,knowledge_revision FROM pages') && params?.[0] === d.id) throw new OperationError('storage_error', 'Synthetic discovery failure');+ if (sql.includes('SELECT id,slug,source_path,knowledge_revision,deleted_at FROM pages') && params?.[0] === d.id) throw new OperationError('storage_error', 'Synthetic discovery failure');return execute.call(this, sql, params);} as BrainEngine['executeRaw'];let thrown: Error | undefined;@@ -312,7 +312,7 @@ test('checkpoint, discovery, and freeze failures remain diagnosable without a ficonst d = await fixture(engine, { 'note.md': 'A stable discovery observation.\n' });const execute = engine.executeRaw;engine.executeRaw = function (this: BrainEngine, sql: string, params?: unknown[]) {- if (sql.includes('SELECT id,slug,source_path,knowledge_revision FROM pages') && params?.[0] === d.id) throw new OperationError('storage_error', 'Synthetic discovery failure');+ if (sql.includes('SELECT id,slug,source_path,knowledge_revision,deleted_at FROM pages') && params?.[0] === d.id) throw new OperationError('storage_error', 'Synthetic discovery failure');return execute.call(this, sql, params);} as BrainEngine['executeRaw'];try {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 641b2eac68..db98053539 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -81,6 +81,7 @@ test/migration-persistence-request-slug-index.test.tstest/owner-refusal.test.tstest/pack-relation-direction-engine.test.tstest/page-embedding-install-batch.test.ts+test/page-prepare-shared-origin-6517.test.tstest/page-purge-journal-timeout-6511.test.tstest/page-state-engine.test.tstest/persistence-bounded-read-session.test.ts@@ -140,6 +141,7 @@ test/sync-full-cursor-slices-6349.test.tstest/sync-full-untracked-import-5459.test.tstest/sync-group-member-order.test.tstest/sync-legacy-holds.test.ts+test/sync-origin-live-wins-6517.test.tstest/sync-staged-catchup.test.tstest/sync-waiver-budget.test.tstest/sync-waiver-run-imports.test.tsdiff --git a/test/sync-origin-live-wins-6517.test.ts b/test/sync-origin-live-wins-6517.test.tsnew file mode 100644index 0000000000..a6f620992e--- /dev/null+++ b/test/sync-origin-live-wins-6517.test.ts@@ -0,0 +1,113 @@+/**+ * #6517 (GBRA-79 wave 16, G3.3 [R7]): one origin rule for every origin guard.+ * `selectOriginClaimant` decides which page an origin file identifies when+ * several pages of the source record it: a live page wins over tombstones,+ * several live pages refuse, a single tombstone may be reused (resurrection),+ * several tombstones stay ambiguous. `assertSyncPageOrigin` (preparation and+ * publication) applies it: master selected every page recording the origin,+ * tombstones included, and refused `pages.length > 1`, so a soft-deleted twin+ * kept the survivor's imports refusing `page_identity_changed` (the Eng P1+ * probe). The accepted-`pageId` and `requireOrigin` checks are unchanged.+ * PGLite and, with DATABASE_URL, Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { assertSyncPageOrigin, selectOriginClaimant, sharedOriginExit } from '../src/core/persistence/sync-origin.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++describe('#6517 selectOriginClaimant, the one origin rule', () => {+ const live = (id: number) => ({ id, deleted_at: null });+ const gone = (id: number) => ({ id, deleted_at: '2026-01-01T00:00:00Z' });+ test('no claimant', () => expect(selectOriginClaimant([])).toEqual({ winner: null, ambiguous: null }));+ test('one live page wins', () => expect(selectOriginClaimant([live(1)])).toEqual({ winner: live(1), ambiguous: null }));+ test('a live page wins over any number of tombstones', () => {+ expect(selectOriginClaimant([gone(1), live(2), gone(3)])).toEqual({ winner: live(2), ambiguous: null });+ expect(selectOriginClaimant([live(2), gone(1)])).toEqual({ winner: live(2), ambiguous: null });+ });+ test('several live pages refuse, whatever the tombstones', () => {+ expect(selectOriginClaimant([live(1), live(2)])).toEqual({ winner: null, ambiguous: 'several_live' });+ expect(selectOriginClaimant([gone(3), live(1), live(2)])).toEqual({ winner: null, ambiguous: 'several_live' });+ });+ test('a single tombstone may be reused', () => expect(selectOriginClaimant([gone(1)])).toEqual({ winner: gone(1), ambiguous: null }));+ test('several tombstones stay ambiguous', () => expect(selectOriginClaimant([gone(1), gone(2)])).toEqual({ winner: null, ambiguous: 'several_tombstones' }));+ test('the exit text names the soft delete and the kept file, never a purge', () => {+ const text = sharedOriginExit('src-example', ['a', 'b']);+ expect(text).toContain('gbrain delete <slug> --source-id src-example --expected-revision <rev>');+ expect(text).toContain('one of a, b');+ expect(text).toContain('hidden without touching the file');+ expect(text).not.toContain('--purge');+ });+});++for (const backend of testBackends()) describe(`[${backend}] #6517 assertSyncPageOrigin applies the rule`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ const sourceId = 'default';+ let n = 0;+ async function pages(origin: string, states: Array<'live' | 'gone'>): Promise<number[]> {+ const ids: number[] = [];+ for (const state of states) {+ const slug = `origin-rule/${++n}`;+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ await tx.putPage(slug, { type: 'note', title: slug, compiled_truth: `Page ${n}.`, timeline: '', frontmatter: {}, content_hash: `h-${n}`, source_path: origin }, { sourceId });+ if (state === 'gone') await tx.executeRaw('UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ }, TEST_WRITE_ATTRIBUTION));+ ids.push(Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.id));+ }+ return ids;+ }+ const refuses = (promise: Promise<void>) => promise.then(() => 'accepted', error => error instanceof OperationError ? `${error.code}` : `other:${String(error)}`);++ beforeAll(async () => {+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => { await engine.disconnect(); await closePostgres?.(); }, 60_000);++ test('one live page plus a tombstone: the origin identifies the live page (master refused page_identity_changed)', async () => {+ const origin = `twins/${randomUUID().slice(0, 8)}.md`;+ const [liveId, tombstoneId] = await pages(origin, ['live', 'gone']);+ await assertSyncPageOrigin(engine, sourceId, origin, liveId!);+ await assertSyncPageOrigin(engine, sourceId, origin, liveId!, true);+ // The tombstone is not the page the origin identifies any more.+ expect(await refuses(assertSyncPageOrigin(engine, sourceId, origin, tombstoneId!))).toBe('page_identity_changed');+ // An import that accepted no page for an origin a live page records is refused, as before.+ expect(await refuses(assertSyncPageOrigin(engine, sourceId, origin, null))).toBe('page_identity_changed');+ });++ test('two live pages refuse, and the refusal names the soft-delete exit with both slugs', async () => {+ const origin = `twins/${randomUUID().slice(0, 8)}.md`;+ const [a, b] = await pages(origin, ['live', 'live']);+ for (const id of [a!, b!, null]) {+ let error: OperationError | undefined;+ try { await assertSyncPageOrigin(engine, sourceId, origin, id); } catch (e) { error = e as OperationError; }+ expect(error?.code).toBe('page_identity_changed');+ expect(error?.suggestion).toContain('Soft-delete the page that should not own the file');+ expect(error?.suggestion).toContain(`origin-rule/${n - 1}`);+ expect(error?.suggestion).toContain(`origin-rule/${n}`);+ }+ });++ test('a single tombstone is still reusable (resurrection), two tombstones still refuse', async () => {+ const one = `twins/${randomUUID().slice(0, 8)}.md`;+ const [tombstone] = await pages(one, ['gone']);+ await assertSyncPageOrigin(engine, sourceId, one, tombstone!);+ await assertSyncPageOrigin(engine, sourceId, one, tombstone!, true);+ expect(await refuses(assertSyncPageOrigin(engine, sourceId, one, null))).toBe('page_identity_changed');+ const two = `twins/${randomUUID().slice(0, 8)}.md`;+ const [x, y] = await pages(two, ['gone', 'gone']);+ for (const id of [x!, y!, null]) expect(await refuses(assertSyncPageOrigin(engine, sourceId, two, id))).toBe('page_identity_changed');+ });++ test('requireOrigin: an accepted page whose origin no page records refuses; no page accepted and none recorded is fine', async () => {+ const origin = `twins/${randomUUID().slice(0, 8)}.md`;+ await assertSyncPageOrigin(engine, sourceId, origin, null, true);+ expect(await refuses(assertSyncPageOrigin(engine, sourceId, origin, 123456789, true))).toBe('page_identity_changed');+ });+});