Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(restore): refuse restoring a page whose recorded file is gone; add --detach and doctor missing_recorded_files (#6609)

time-attack6a9acb930c65
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 0734b58aae..571647191e 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -21,4 +21,5 @@
- `src/core/repair/file-drift.ts` — `gbrain repair file-drift` (#6643): explicit-only, preview-bound resolution of drifted pages through `reconcileCanonical` with one side preferred (`preferSideDecisions`) inside reconcile's protections; `driftExceptions` lists where the result differs from the preferred side. The preview writes a private artifact under `configDir()/repair-previews/file-drift/<hash>.json` and saves the approved set; apply runs `runReconcileApply` per page under request ids derived from the hash and slug, so an interrupted apply resumes. `--all-drifted` refuses mixed drift classes unless `--class` keeps one. Repeatable `--only`/`--skip` over the source-relative canonical file path (`src/core/repair/path-glob.ts` `matchesRepairPath`: a value without `*` is an exact path, as every kind's `--only`; with `*` it is a glob, file-drift only: `*` within a segment, `**` across) narrow the selection before the class check, the 1,000-page bound and any preview work (`not_selected` residual); they join the selection digest only when given (so earlier hashes are unchanged) and appear in every printed preview and apply command. `prepareDriftPage` builds one page's ready reconcile preview for a preferred side; the plan and the keep_db policy share it. `--keep` is refused at parse in `src/commands/repair.ts` with the same command rewritten to `--prefer database`. `reconcile-prepare.ts` keeps the file bytes when they already parse to the result digest. Doctor `maintenance_write_drift` (`src/commands/doctor/checks/maintenance-drift.ts`) counts what remains and, on the owner host, echoes each declared `storage.keep_db` policy as `keep_db_policy` (prefixes, matched drifted pages among those checked live, `unchecked`, receipt cost from `keepDbReceiptCost`).
- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.
- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.
+- `src/commands/doctor/checks/missing-recorded-files.ts` — #6609 doctor `missing_recorded_files` (BRAIN, after `ghost_pages`): the classic-brain counterpart of `ghost_pages`. Read-only; per source with a checkout on this host and managed persistence off it runs `scanMissingRecordedFiles` (`src/core/persistence/detached-pages.ts`) and warns with counts, samples and an `ask_user` fix (put the file back and sync, or `gbrain delete` then `gbrain restore <slug> --source-id <id> --detach`) for live pages whose recorded file a `gbrain sync --full` would not find; `ok` + `not_applicable` when no source qualifies. Test: `test/restore-detach-6609.test.ts`.
- `src/core/repair/keep-db-policy.ts` — the opt-in `storage.keep_db` policy (#6696 C7). `readKeepDbPolicy` reads a source's `keep_db` prefixes from the gbrain.yml of its canonical checkout, only when the given host owns the active binding. `runKeepDbPolicy` takes the slugs under the prefixes with a drift conflict receipt in the newest 100,000 request sequences plus the recorded concept drift skips, checks each live, prepares the `--prefer database` resolution (`prepareDriftPage`) and submits it through `runReconcileApply` under this installation's own CLI writer registration (never an inherited caller context), with a request id derived from the page revision and file bytes, so one drift is never submitted twice. A run submits at most `KEEP_DB_BATCH` (10) requests (`stopped: 'rate_limit'`) and asks its `admission` gate before each one (default: the repair core's 90% stop line on lifetime ids and receipt bytes, `stopped: 'capacity'`; the seam for background-producer backpressure). The persistence consumer (`consumer.ts`) runs it while idle at most every 10 minutes when started with `keepDbPolicy` (`service.ts`: serve, jobs and autopilot owners only; never with `requestsOnly`), and `stop()` awaits the pass. Tests: `test/file-drift-bulk-reconcile.test.ts` (PGLite; Postgres via `test/e2e/file-drift-bulk-reconcile-postgres.test.ts`).
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index cf648d5988..28acbab19b 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -51,6 +51,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).
- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).
+- `src/core/persistence/detached-pages.ts` — #6609 (D5) restore of a page whose recorded canonical file is gone on a brain without managed persistence. `assertRestoreOrigin` (called by `submitPageMutation` for `restore_page`, `publishesFile` = write-through on and a file target) refuses a restore that writes no file of a soft-deleted page whose `source_path` file `inSyncableTree` does not find (exists and is tracked or untracked-not-ignored, the set sync imports) with `source_changed` / detail `canonical_file_absent`, `retryable: false`, docs `storage-tiering.md#restoring-a-page-whose-file-is-gone` and an `ask_user` fix (`gbrain restore <slug> --source-id <id> --detach`, MCP `restore_page` `detach: true`); `detach: true` with nothing to detach refuses `invalid_params`. `detachRestoredPage` runs in the restore publication (from `classifyUnboundPage`) and clears `source_path`, stamping `pages.database_only_reason='detached'`; the page upsert in `engine-sql/pages.ts` clears that stamp when a sync writes a `source_path` again. `scanMissingRecordedFiles` (at most `MISSING_FILES_SCAN_LIMIT` live pages per source, `collectSyncableFiles` + `scannerSlugRootMode` path resolution) feeds doctor `missing_recorded_files`. Test: `test/restore-detach-6609.test.ts`.
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot (`mayReprepare`: `revision_conflict` or, #5385 [R13], `revision_required`, both only when the caller named no `expected_revision`); exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The `add_timeline_entry` receipt carries `bullet`, the rendered Markdown line (#5970): there is no update/remove verb because the page is the system of record, so the caller corrects an entry by editing that line with `edit_page` and the row follows the page (both timeline op descriptions say so; `test/timeline-correction-path-5970.test.ts`). #5251: `add_tag` / `remove_tag` prepare with `deferEmbedding: true` (a tag change leaves every chunk's text as it was, so no `embedding` effect is queued and `embedding_state` reads `deferred`; the stale sweep still covers any chunk the republication left without a vector); the full page republication they ride stays, so the issue stays open. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 8db7ff36a5..daf2a016ed 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -54,6 +54,7 @@ of making a duplicate.
| <a id="file_database_drift"></a>`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). Many pages at once: `gbrain sources reconcile <source> --brain host --audit --conflicts` lists them and `gbrain repair file-drift` resolves them, preferring the file or the database copy ([file drift](repair.md#file-drift)). |
| <a id="canonical_file_missing"></a>`canonical_file_missing` | `source_changed` (a caller write; maintenance refuses before admission) | The page's recorded canonical file is gone while its database page is still live (a ghost page: the file was moved or deleted outside gbrain). A caller write refuses with "The canonical file was removed outside coordinated publication." and nothing is written; retrying it refuses the same way. A maintenance write (fact-fence adoption, enrichment, `dream`) is refused before admission: no request id, no receipt (before #6696 each cycle settled a `conflict` receipt). `gbrain sources writer failures <source>` reports such receipts as category `canonical_file_missing`. Neither copy was changed. | Decide which copy is right. If the file should exist, restore it at its recorded path and preview the page with `gbrain sources reconcile <source> <slug> --brain host --preview`, or sync. If the page should go, preview the ghost-page repair with `gbrain repair ghost-pages --source <source>` (read-only; it prints the apply command with its hash) and apply it with `--apply --expect <hash> --yes` only after the user agrees; a soft-deleted page can be restored with `gbrain restore <slug> --force` until the autopilot purge 72 h later. `gbrain pages ghosts --source <source>` and doctor `ghost_pages` list them, doctor `maintenance_write_drift` lists held-back maintenance writes. See [ghost pages](repair.md#ghost-pages). |
| <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. |
+| <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). |
| <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: run `gbrain sync --source <source> --no-pull` on the brain host (the refusal's fix), read the page again and resubmit with a new request ID. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. |
| <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. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. |
diff --git a/docs/storage-tiering.md b/docs/storage-tiering.md
index ac83ed44d4..3bfac52b45 100644
--- a/docs/storage-tiering.md
+++ b/docs/storage-tiering.md
@@ -189,6 +189,39 @@ then counts the pages of the active source that owns the repo path (its
`.gbrain-source` or the longest registered `local_path` containing it), or
every source's pages when no active source owns it.
+## Restoring a page whose file is gone
+
+On a classic brain (no managed persistence) sync keys a page on the file it
+recorded (`source_path`). When that file leaves the checkout (`git rm
+--cached`, an ignore rule, a deletion), sync soft-deletes the page. Restoring
+it with `gbrain restore <slug> --force` while the restore writes no file
+(`sync.write_through` off, a sandboxed agent, a database-only source) used to
+bring the page back still recording the missing file, so the next
+`gbrain sync --full` soft-deleted it again.
+
+Since #6609 such a restore refuses with `source_changed` / detail
+`canonical_file_absent`, restores nothing, and asks you to choose:
+
+- **Keep it file-backed:** put the file back at its recorded path, commit it
+ and run `gbrain sync --source <id>`. Sync restores the page from its file.
+- **Keep it database-only:** `gbrain restore <slug> --source-id <id> --detach`
+ (MCP `restore_page` with `detach: true`). The page is restored without its
+ recorded file and stamped `pages.database_only_reason='detached'`, so no
+ sync removes it. A file synced later at its path binds the page to it again
+ and clears the stamp.
+
+A file that is only missing on this host (an unpulled checkout, another
+machine) never makes a page database-only by itself: detaching is always an
+explicit choice. `--detach` is refused (`invalid_params`) when there is
+nothing to detach (the page is not soft-deleted, its file is in place, or the
+restore re-creates it).
+
+Doctor `missing_recorded_files` warns about live pages whose recorded file is
+not among the files `gbrain sync --full` enumerates (for example a page
+restored the old way), so that sync would soft-delete them; it inspects at most
+50,000 pages per source and asks you which of the choices above each page
+gets. Managed sources are covered by `ghost_pages` instead.
+
## Validation
`loadStorageConfig` runs `normalizeAndValidateStorageConfig` after parsing:
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 71ad0e194b..677664cd73 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -40,7 +40,7 @@ src/core/config.ts 1978 ratchet +2 W5: search.page_rank_cut / page_rank_cut_fact
src/core/persistence/sync-run.ts 1687 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687
src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
-src/core/ops/pages.ts 705 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on
+src/core/ops/pages.ts 706 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts)
src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts
diff --git a/src/commands/doctor/checks/missing-recorded-files.ts b/src/commands/doctor/checks/missing-recorded-files.ts
new file mode 100644
index 0000000000..9cb2b0a0df
--- /dev/null
+++ b/src/commands/doctor/checks/missing-recorded-files.ts
@@ -0,0 +1,60 @@
+/**
+ * #6609 (D5) `missing_recorded_files`: live pages of a classic source (a
+ * checkout on this host, managed persistence off) whose recorded canonical
+ * file is not among the files `gbrain sync --full` enumerates, so the next
+ * full sync soft-deletes them. The usual cause is a page restored after its
+ * file left the checkout (`git rm --cached`, an ignore rule, a deletion not
+ * committed yet). Keeping such a page is the user's choice: put the file back
+ * and sync, or keep it database-only with delete then `restore --detach`.
+ * Read-only; at most `MISSING_FILES_SCAN_LIMIT` pages per source. Managed
+ * sources are `ghost_pages`'s, on their owner host.
+ */
+import type { Check } from '../../doctor.ts';
+import { checkError, doctorVerify } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { scanMissingRecordedFiles, type MissingRecordedFiles } from '../../../core/persistence/detached-pages.ts';
+
+const DOCS = 'docs/storage-tiering.md#restoring-a-page-whose-file-is-gone';
+
+async function runMissingRecordedFiles(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ try {
+ const engine = connectedEngine(ctx);
+ const sourceIds = ctx.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ const scans: MissingRecordedFiles[] = [];
+ for (const sourceId of sourceIds) {
+ const scan = await scanMissingRecordedFiles(engine, sourceId);
+ if (scan) scans.push(scan);
+ }
+ const found = scans.filter(scan => scan.pages.length);
+ const count = found.reduce((sum, scan) => sum + scan.pages.length, 0);
+ const details = { count, sources: scans.map(scan => ({ source_id: scan.source_id, count: scan.pages.length, inspected: scan.inspected, truncated: scan.truncated,
+ samples: scan.pages.slice(0, 5) })), docs: DOCS };
+ if (!scans.length) {
+ checks.push({ name: 'missing_recorded_files', status: 'ok', severity: 'info', readiness_state: 'not_applicable', details,
+ message: 'Not applicable: no source is a classic checkout on this host (managed sources are checked by ghost_pages).' });
+ return checks;
+ }
+ if (!count) {
+ checks.push({ name: 'missing_recorded_files', status: 'ok', details,
+ message: `Every live page's recorded file is in its checkout (${scans.reduce((sum, scan) => sum + scan.inspected, 0)} page(s) inspected${scans.some(scan => scan.truncated) ? '; bounded, more not checked' : ''}).` });
+ return checks;
+ }
+ const first = found[0]!;
+ const sample = first.pages[0]!;
+ checks.push({ name: 'missing_recorded_files', status: 'warn', details,
+ message: `${count} live page(s) record a canonical file that is not in their checkout, so the next gbrain sync --full soft-deletes them `
+ + `(${found.map(scan => `${scan.source_id}: ${scan.pages.length}`).join('; ')}; e.g. ${found.flatMap(scan => scan.pages.slice(0, 3).map(page => `${scan.source_id}:${page.slug} (${page.source_path})`)).slice(0, 5).join(', ')}). `
+ + 'A page restored after its file left the checkout is the usual cause. To keep one with its file, put the file back, commit it and run gbrain sync; '
+ + `to keep it database-only, run gbrain delete ${sample.slug} --source-id ${first.source_id}, then gbrain restore ${sample.slug} --source-id ${first.source_id} --detach. A page whose file you removed on purpose needs nothing.`,
+ fix: { consent: [], actor: 'agent', ask_user: true, requires_exclusive: false, docs: DOCS, verify: doctorVerify('missing_recorded_files'),
+ why: 'Whether each page keeps its file, becomes database-only, or goes away with its file is the user\'s choice; nothing here runs on its own.',
+ user_message: `${count} page(s) point at files that are no longer in your checkout (for example ${sample.slug}), so the next full sync will delete them. `
+ + 'For each one: should I keep it without a file (database-only), will you put the file back, or should it go?' } });
+ } catch (error) {
+ checks.push(checkError('missing_recorded_files', 'check live pages for a recorded file missing from their checkout', error, { details: { count: 'unknown', docs: DOCS } }));
+ }
+ return checks;
+}
+
+export const missingRecordedFilesEntry: DoctorEntry = { name: 'missing_recorded_files', emits: ['missing_recorded_files'], run: runMissingRecordedFiles };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index ac05f20cde..b68eaee827 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -110,6 +110,7 @@ import { providerConsentEntry } from './checks/provider-consent.ts';
import { behaviorChangesEntry } from './checks/behavior-changes.ts';
import { fenceIntegrityEntry } from './checks/fence-integrity.ts';
import { ghostPagesEntry } from './checks/ghost-pages.ts';
+import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';
import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';
import { atomHeldFailedEntry } from './checks/atom-holds.ts';
import { extractionInputTruncatedEntry } from './checks/extraction-input.ts';
@@ -218,6 +219,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
atomHeldFailedEntry,
extractionInputTruncatedEntry,
ghostPagesEntry,
+ missingRecordedFilesEntry,
fenceIntegrityEntry,
searchModeEntry,
];
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 027761ca91..93b3a0e25d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -635,6 +635,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.0.0-wave17', text: 'On Postgres, `remember` about an existing page of a source that has a checkout but no canonical owner now follows the same rule as `put_page`: with `persistence.unbound_write=database_only` a page without a canonical file gets the fact fenced into its database body (database-only, `write_through.skipped: unbound_source`), and otherwise the refusal (still `unavailable` with `write_error: owner_unavailable`) carries `detail: unbound_source`, the opt-in or classic file path, and an ask-the-user fix instead of the generic writer hint. `loops_close` fact retirement and `gbrain facts relink` fence such pages the same way.' },
// #6610: classic unfenced facts on database-only pages.
{ since: '0.0.0-wave17', text: 'On a brain without managed persistence, `extract_facts` (and the v0.32.2 fence step) now fences unfenced facts of a database-only page (no recorded file and none at its slug path) into the page\'s database body when such a write is database-only (`sync.write_through` off, or on Postgres an unbound source with `persistence.unbound_write=database_only`, which stamps the page `unbound_source`), instead of reporting a missing canonical file and halting the facts fence every run. Without that opt-in the rows stay unfenced and their page skips reconciliation, but they no longer count as pending (`legacyRowsPending`) or trigger the guard; doctor `fence_integrity` lists them under `unbound_legacy_facts` and asks the user about the opt-in, and the migration reports them as `skipped_unbound_source`.' },
+ { since: '0.0.0-wave17', text: 'On a brain without managed persistence, `gbrain restore` / `restore_page` of a soft-deleted page whose recorded file is gone from the checkout now refuses (`source_changed`, detail `canonical_file_absent`) when the restore writes no file, instead of restoring a page the next `gbrain sync --full` deletes again. Put the file back and sync, or pass `--detach` (`detach: true`) to restore it database-only (`database_only_reason=detached`, no `source_path`); a file synced back at its path binds the page again. New doctor check `missing_recorded_files` lists live pages a full sync would delete this way.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index b9c28f123c..2bd47b55fb 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -190,6 +190,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'undeclared_db_only_pages',
// #6696 B5: live pages whose canonical file is missing on the owner host (doctor/checks/ghost-pages.ts).
'ghost_pages',
+ // #6609: live pages of a classic checkout whose recorded file a full sync would not find (doctor/checks/missing-recorded-files.ts).
+ 'missing_recorded_files',
'unified_multimodal_coverage',
'unverified_extractions',
'voice_gate_health',
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 512ba96e46..9a24d03904 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -169,6 +169,7 @@ export async function putPage(
import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename),
chunker_version = ${trustedSql(bodyWriteChunkVersion('EXCLUDED.compiled_truth', 'EXCLUDED.timeline'))},
source_path = COALESCE(EXCLUDED.source_path, pages.source_path),
+ database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason = 'detached' THEN NULL ELSE pages.database_only_reason END,
source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind),
source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri),
ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via),
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index e29c0f1ec1..cd9261ca40 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -553,7 +553,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"name": "restore_page",
"idempotent": true,
"outputRedaction": "no_stored_text",
- "description": "Restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.",
+ "description": "Restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag. A restore that writes no file refuses (source_changed, detail canonical_file_absent) when the page's recorded file is gone from the checkout, because the next full sync would delete it again; the user chooses between putting the file back and detach: true.",
"params": {
"source_id": {
"type": "string",
@@ -575,6 +575,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "string",
"required": true,
"description": "Slug of the soft-deleted page to restore, e.g. 'people/alice-example'."
+ },
+ "detach": {
+ "type": "boolean",
+ "description": "Restore a page whose recorded canonical file is gone from the checkout as a database-only page: it forgets the file, so sync never deletes it again. Only accepted when a plain restore refuses with canonical_file_absent; ask the user first."
}
},
"mutating": true,
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index fce30c0054..00508954fe 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -434,11 +434,12 @@ const restore_page: Operation = {
name: 'restore_page',
idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.',
+ description: 'Restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag. A restore that writes no file refuses (source_changed, detail canonical_file_absent) when the page\'s recorded file is gone from the checkout, because the next full sync would delete it again; the user chooses between putting the file back and detach: true.',
params: {
...PAGE_MUTATION_PARAMS,
slug: { type: 'string', required: true, description: "Slug of the soft-deleted page to restore, e.g. 'people/alice-example'." },
source_id: { type: 'string', description: "#4329: source holding the row to restore (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer restore access." },
+ detach: { type: 'boolean', description: 'Restore a page whose recorded canonical file is gone from the checkout as a database-only page: it forgets the file, so sync never deletes it again. Only accepted when a plain restore refuses with canonical_file_absent; ask the user first.' },
},
mutating: true,
scope: 'write',
diff --git a/src/core/persistence/detached-pages.ts b/src/core/persistence/detached-pages.ts
new file mode 100644
index 0000000000..114bd91e5b
--- /dev/null
+++ b/src/core/persistence/detached-pages.ts
@@ -0,0 +1,130 @@
+/**
+ * #6609 (D5): a page restored while its recorded canonical file is gone from
+ * the source's syncable tree. Classic sync keys pages on `source_path`, so a
+ * plain restore of such a page (one that writes no file: `sync.write_through`
+ * off, a sandbox, a database-only source) is undone by the next
+ * `gbrain sync --full`, which soft-deletes every live page whose recorded file
+ * it does not find. `restore_page` therefore refuses it with
+ * `canonical_file_absent` and the user's two choices: put the file back and
+ * sync, or restore with `detach: true`, which clears the page's `source_path`
+ * in the publication and stamps `pages.database_only_reason='detached'`, so no
+ * sync sweeps it. A transient absence (an unpulled checkout, another machine)
+ * never turns a page database-only by itself. Doctor `missing_recorded_files`
+ * (`scanMissingRecordedFiles`) lists the live pages a full sync would delete
+ * that way on a brain without managed persistence (`ghost_pages` covers
+ * managed sources on their owner host).
+ */
+import { execFileSync } from 'node:child_process';
+import { existsSync, statSync } from 'node:fs';
+import { basename, dirname, join, resolve } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+import { isSyncable, type SyncStrategy } from '../sync.ts';
+import { resolveSourceLocalFilePath } from '../markdown.ts';
+import { resolvePageWriteTarget, scannerSlugRootMode } from '../write-through.ts';
+import { managedPersistenceEnabled } from './ownership.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import type { SqlEngine, WriteRequest } from './model.ts';
+
+export const DETACHED_REASON = 'detached';
+const DOCS = 'docs/storage-tiering.md#restoring-a-page-whose-file-is-gone';
+
+/**
+ * Whether classic sync would import the file at `path`: it exists and, inside
+ * a Git work tree, is tracked or untracked but not ignored (`git ls-files
+ * --cached --others --exclude-standard`, the enumeration sync uses). Outside a
+ * work tree, or without git, sync walks the directory, so existence decides.
+ */
+export function inSyncableTree(path: string): boolean {
+ if (!existsSync(path)) return false;
+ try {
+ return execFileSync('git', ['-C', dirname(path), 'ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', basename(path)],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).length > 0;
+ } catch {
+ return true;
+ }
+}
+
+/**
+ * The recorded `source_path` of a page whose file the next full sync would
+ * not find, else null. A page without a recorded file, a path sync never
+ * reconciles, or a source with no checkout on this host is never absent.
+ */
+export async function absentRecordedFile(engine: BrainEngine, sourceId: string, page: { slug: string; source_path?: string | null }): Promise<string | null> {
+ const sourcePath = page.source_path?.trim();
+ if (!sourcePath || !isSyncable(sourcePath)) return null;
+ const target = await resolvePageWriteTarget(engine, page.slug, sourceId, { includeDeleted: true });
+ return target.ok && !inSyncableTree(target.filePath) ? sourcePath : null;
+}
+
+/**
+ * Admission rule for `restore_page`: a restore that publishes no file
+ * (`publishesFile` false) of a soft-deleted page whose recorded file is absent
+ * refuses unless `detach`; `detach` is refused when there is nothing to detach.
+ */
+export async function assertRestoreOrigin(engine: BrainEngine, input: { sourceId: string; slug: string; snapshot: PageSnapshot | null;
+ publishesFile: boolean; detach: boolean; remote: boolean }): Promise<void> {
+ const { sourceId, slug, snapshot } = input;
+ const absent = snapshot?.page.deleted_at && !input.publishesFile ? await absentRecordedFile(engine, sourceId, snapshot.page) : null;
+ if (input.detach) {
+ if (absent) return;
+ throw opError('invalid_params', 'There is nothing to detach.',
+ `detach applies only to restoring a soft-deleted page whose recorded canonical file is gone from the checkout of '${sourceId}' while the restore writes no file. `
+ + `Page ${slug} ${!snapshot?.page.deleted_at ? 'is not soft-deleted' : input.publishesFile ? 'gets its file re-created by this restore' : 'has its file in place, or records none'}, so restore it without detach.`);
+ }
+ if (!absent) return;
+ const command = ['gbrain', 'restore', slug, '--source-id', sourceId, '--detach'];
+ throw opError('source_changed', `The page's canonical file ${absent} is no longer in the checkout of source '${sourceId}'.`,
+ `Nothing was restored: a restored page whose recorded file is gone is soft-deleted again by the next gbrain sync --full. Choose one: put ${absent} back in the checkout, `
+ + `commit it and run gbrain sync --source ${sourceId} (sync restores the page from its file); or restore the page database-only with ${command.join(' ')} `
+ + '(restore_page with detach: true), which forgets its recorded file so sync keeps it; a file synced later at its path updates it again.',
+ { detail: 'canonical_file_absent', retryable: false, docs: DOCS, fix: {
+ argv: command, mcp: { tool: 'restore_page', arguments: { slug, source_id: sourceId, detach: true } },
+ consent: [], actor: input.remote ? 'user' : 'agent', ask_user: true, requires_exclusive: false, docs: DOCS,
+ why: 'Detaching makes the page database-only for good, while putting the file back keeps it file-backed; which one is the user\'s choice, because the file may only be missing on this host.',
+ user_message: `The file of ${slug} (${absent}) is gone from the ${sourceId} checkout, so a plain restore would be undone by the next full sync. `
+ + 'I can restore it as a database-only page (it forgets its file), or you can put the file back, commit it and sync. Which do you want?',
+ } });
+}
+
+/** In the restore publication: a detached restore forgets the page's recorded file and stamps it database-only. */
+export async function detachRestoredPage(tx: SqlEngine, row: Pick<WriteRequest, 'operation' | 'intent' | 'source_id' | 'slug'>): Promise<void> {
+ if (row.operation !== 'restore_page' || row.intent?.detach !== true) return;
+ await tx.executeRaw('UPDATE pages SET source_path=NULL, database_only_reason=$3 WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL',
+ [row.source_id, row.slug, DETACHED_REASON]);
+}
+
+/** Live pages of a source read per scan; past it the result says `truncated`. */
+export const MISSING_FILES_SCAN_LIMIT = 50_000;
+
+export interface MissingRecordedFiles { source_id: string; pages: Array<{ slug: string; source_path: string }>; inspected: number; truncated: boolean }
+
+/**
+ * #6609: the live pages of a classic source (a `local_path` checkout on this
+ * host, managed persistence off) whose recorded file is not in the files
+ * `gbrain sync --full` enumerates (`collectSyncableFiles`), so that sync would
+ * soft-delete them. Null when the source has no such checkout here.
+ */
+export async function scanMissingRecordedFiles(engine: BrainEngine, sourceId: string): Promise<MissingRecordedFiles | null> {
+ if (await managedPersistenceEnabled(engine)) return null;
+ const [source] = await engine.executeRaw<{ local_path: string | null; strategy: SyncStrategy | null }>(
+ "SELECT local_path, config->>'strategy' AS strategy FROM sources WHERE id=$1 AND archived IS NOT TRUE", [sourceId]);
+ const root = source?.local_path;
+ if (!root || !existsSync(root) || !statSync(root).isDirectory()) return null;
+ const strategy = source.strategy ?? 'markdown';
+ const rows = await engine.executeRaw<{ slug: string; source_path: string }>(
+ `SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND NULLIF(btrim(source_path), '') IS NOT NULL
+ ORDER BY id LIMIT ${MISSING_FILES_SCAN_LIMIT + 1}`, [sourceId]);
+ const truncated = rows.length > MISSING_FILES_SCAN_LIMIT;
+ const inspected = rows.slice(0, MISSING_FILES_SCAN_LIMIT).filter(row => isSyncable(row.source_path, { strategy }));
+ const result: MissingRecordedFiles = { source_id: sourceId, pages: [], inspected: inspected.length, truncated };
+ if (!inspected.length) return result;
+ const { collectSyncableFiles } = await import('../../commands/import.ts');
+ const mode = await scannerSlugRootMode(engine, sourceId, root);
+ const present = new Set(collectSyncableFiles(root, { strategy }).map(file => resolve(file)));
+ for (const row of inspected) {
+ const path = resolveSourceLocalFilePath(root, row.source_path, row.slug, mode) ?? join(root, row.source_path);
+ if (!present.has(resolve(path))) result.pages.push({ slug: row.slug, source_path: row.source_path });
+ }
+ return result;
+}
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 700bb4b828..6a9c6c092b 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -34,6 +34,7 @@ import type { Principal, WriteRequest } from './model.ts';
import { normalizeSubagentPageInput, undeclaredPageTypeWarning, type PageTypeWarning } from './page-input.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
import { decideUnboundWrite, isUnboundSourcePage } from './unbound-source.ts';
+import { assertRestoreOrigin } from './detached-pages.ts';
import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';
import { publishesDatabaseOnly } from './page-prepare.ts';
import { cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';
@@ -379,6 +380,9 @@ export async function preparePageAdmission(ctx: OperationContext,
if (decision.kind === 'claim') binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });
else authority.databaseOnlyReason = decision.reason;
}
+ // #6609 (D5): a restore that writes no file refuses a page whose recorded file is gone, unless detach.
+ if (input.operation === 'restore_page') await assertRestoreOrigin(ctx.engine, { sourceId, slug, snapshot,
+ publishesFile: writeThrough && binding !== null, detach: p.detach === true, remote: ctx.remote !== false });
// #5032: this host publishes the canonical file, and on Windows a ':' in its
// name cannot be stored; refuse before admission. Database-only writes pass,
// including read-only mirror sources and pages created while one (#5409).
diff --git a/src/core/persistence/unbound-source.ts b/src/core/persistence/unbound-source.ts
index 668727d0ea..a9859d45de 100644
--- a/src/core/persistence/unbound-source.ts
+++ b/src/core/persistence/unbound-source.ts
@@ -3,6 +3,7 @@ import { opError, OperationError } from '../ops/contract.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
import { managedPersistenceEnabled } from './ownership.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
+import { detachRestoredPage } from './detached-pages.ts';
/**
* #5254: a Postgres page write to a filesystem source with no canonical owner
@@ -149,7 +150,13 @@ export async function assertUnboundPublication(tx: SqlEngine, row: Pick<WriteReq
throw error;
}
-export async function classifyUnboundPage(tx: SqlEngine, row: Pick<WriteRequest, 'authority' | 'source_id' | 'slug'>): Promise<void> {
+/**
+ * The publication's database-only stamp of the page it wrote: `unbound_source`
+ * for a write admitted that way, and `detached` (forgetting the recorded file)
+ * for a `restore_page` with `detach` (#6609, `detached-pages.ts`).
+ */
+export async function classifyUnboundPage(tx: SqlEngine, row: Pick<WriteRequest, 'authority' | 'source_id' | 'slug' | 'operation' | 'intent'>): Promise<void> {
+ await detachRestoredPage(tx, row);
if (row.authority.databaseOnlyReason !== 'unbound_source') return;
await tx.executeRaw("UPDATE pages SET database_only_reason='unbound_source' WHERE source_id=$1 AND slug=$2 AND database_only_reason IS NULL",
[row.source_id, row.slug]);
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 47824174b4..cf3cb991a2 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -2516,6 +2516,20 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "count": 0,
+ "docs": "docs/storage-tiering.md#restoring-a-page-whose-file-is-gone",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "Not applicable: no source is a classic checkout on this host (managed sources are checked by ghost_pages).",
+ "name": "missing_recorded_files",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -2581,6 +2595,10 @@
"top_writers": []
}
],
+ "unbound_legacy_facts": {
+ "pages": [],
+ "total": 0
+ },
"uncommitted_repairs": 0,
"unrenderable_legacy_facts": {
"complete": true,
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index db527afe0a..9f55df819e 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -2568,6 +2568,20 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "count": 0,
+ "docs": "docs/storage-tiering.md#restoring-a-page-whose-file-is-gone",
+ "sources": []
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "Not applicable: no source is a classic checkout on this host (managed sources are checked by ghost_pages).",
+ "name": "missing_recorded_files",
+ "readiness_state": "not_applicable",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -2633,6 +2647,10 @@
"top_writers": []
}
],
+ "unbound_legacy_facts": {
+ "pages": [],
+ "total": 0
+ },
"uncommitted_repairs": 0,
"unrenderable_legacy_facts": {
"complete": true,
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 00e3e0346d..9e24195c90 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -809,6 +809,10 @@
"category": "brain",
"name": "ghost_pages"
},
+ {
+ "category": "brain",
+ "name": "missing_recorded_files"
+ },
{
"category": "brain",
"name": "fence_integrity"
diff --git a/test/restore-detach-6609.test.ts b/test/restore-detach-6609.test.ts
new file mode 100644
index 0000000000..02fb91284b
--- /dev/null
+++ b/test/restore-detach-6609.test.ts
@@ -0,0 +1,140 @@
+/**
+ * #6609 (D5): restoring a page whose recorded canonical file is gone.
+ *
+ * Protects: on a classic brain whose restore writes no file
+ * (`sync.write_through` off), `restore_page` of a soft-deleted page whose
+ * recorded file left the checkout refuses with `source_changed` /
+ * `canonical_file_absent` and an ask-the-user fix naming `--detach`, and
+ * nothing is restored; `detach: true` restores it database-only (no
+ * `source_path`, `database_only_reason='detached'`) and a later
+ * `gbrain sync --full` keeps it live; `detach` is refused when there is
+ * nothing to detach; doctor `missing_recorded_files` warns about a live page
+ * whose recorded file a full sync would not find.
+ * Fails when: the restore succeeds and keeps the stale `source_path`, so the
+ * next full sync soft-deletes the page again (the reported bug).
+ * Seams: none; PGLite in memory, a real Git checkout, `performSync`.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execSync } from 'node:child_process';
+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import { missingRecordedFilesEntry } from '../src/commands/doctor/checks/missing-recorded-files.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+const restore_page = operations.find(o => o.name === 'restore_page')!;
+let engine: PGLiteEngine;
+const dirs: string[] = [];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
+}, 60_000);
+
+/** A classic source `id` whose checkout holds `people/<name>.md`, synced, then the file untracked and ignored, and synced again (page soft-deleted). */
+async function untrackedPage(id: string, name: string): Promise<{ dir: string; slug: string }> {
+ const dir = mkdtempSync(join(tmpdir(), 'restore-detach-'));
+ dirs.push(dir);
+ execSync('git init -q && git config user.email [email protected] && git config user.name t', { cwd: dir });
+ mkdirSync(join(dir, 'people'), { recursive: true });
+ writeFileSync(join(dir, 'people', `${name}.md`), `---\ntype: person\ntitle: ${name}\n---\n# ${name}\n\nA fixture.\n`);
+ execSync('git add -A && git commit -qm seed', { cwd: dir });
+ await runSources(engine, ['add', id, '--path', dir, '--no-federated']);
+ await performSync(engine, { repoPath: dir, sourceId: id, noPull: true, noEmbed: true });
+ appendFileSync(join(dir, '.gitignore'), `/people/${name}.md\n`);
+ execSync(`git rm -q --cached people/${name}.md && git add .gitignore && git commit -qm untrack`, { cwd: dir });
+ await performSync(engine, { repoPath: dir, sourceId: id, noPull: true, noEmbed: true });
+ return { dir, slug: `people/${name}` };
+}
+
+function ctx(sourceId: string): OperationContext {
+ return { engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId } as unknown as OperationContext;
+}
+async function restore(sourceId: string, slug: string, extra: Record<string, unknown> = {}) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ return restore_page.handler(ctx(sourceId), { slug, source_id: sourceId, expected_revision: snapshot!.revision, request_id: randomUUID(), ...extra }) as Promise<Record<string, any>>;
+}
+async function refusal(promise: Promise<unknown>): Promise<OperationError> {
+ try { await promise; } catch (error) { return error as OperationError; }
+ throw new Error('restore_page did not refuse');
+}
+async function pageRow(sourceId: string, slug: string) {
+ const [row] = await engine.executeRaw<{ source_path: string | null; database_only_reason: string | null; live: boolean }>(
+ 'SELECT source_path, database_only_reason, deleted_at IS NULL AS live FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ return row;
+}
+async function doctor(): Promise<Check> {
+ const checks = await missingRecordedFilesEntry.run({ engine } as unknown as DoctorContext) as Check[];
+ return checks[0]!;
+}
+
+describe('#6609 restore of a page whose recorded file is gone', () => {
+ test('a plain restore refuses with canonical_file_absent and the detach choice; nothing is restored', async () => {
+ const { slug } = await untrackedPage('refuse', 'alice-example');
+ expect(await pageRow('refuse', slug)).toEqual({ source_path: `${slug}.md`, database_only_reason: null, live: false });
+ const error = await refusal(restore('refuse', slug));
+ expect(error.code).toBe('source_changed');
+ expect(error.detail).toBe('canonical_file_absent');
+ expect(error.retryable).toBe(false);
+ expect(error.fix).toMatchObject({ ask_user: true, argv: ['gbrain', 'restore', slug, '--source-id', 'refuse', '--detach'],
+ mcp: { tool: 'restore_page', arguments: { slug, source_id: 'refuse', detach: true } } });
+ expect(error.suggestion).toContain(`put ${slug}.md back in the checkout`);
+ expect(await pageRow('refuse', slug)).toEqual({ source_path: `${slug}.md`, database_only_reason: null, live: false });
+ }, 60_000);
+
+ test('detach restores it database-only, a full sync keeps it live, and its file synced back re-binds it', async () => {
+ const { dir, slug } = await untrackedPage('detach', 'bob-example');
+ const restored = await restore('detach', slug, { detach: true });
+ expect(restored.status).toBe('restored');
+ expect(await pageRow('detach', slug)).toEqual({ source_path: null, database_only_reason: 'detached', live: true });
+ await performSync(engine, { repoPath: dir, sourceId: 'detach', noPull: true, noEmbed: true, full: true });
+ expect(await pageRow('detach', slug)).toEqual({ source_path: null, database_only_reason: 'detached', live: true });
+ // A file synced back at its path re-binds the page and clears the detached stamp.
+ execSync(`git rm -q --cached .gitignore && rm .gitignore && git add people && git commit -qm retrack`, { cwd: dir });
+ await performSync(engine, { repoPath: dir, sourceId: 'detach', noPull: true, noEmbed: true, full: true });
+ expect(await pageRow('detach', slug)).toEqual({ source_path: `${slug}.md`, database_only_reason: null, live: true });
+ }, 60_000);
+
+ test('detach is refused when the recorded file is still in the checkout', async () => {
+ const { dir, slug } = await untrackedPage('present', 'carol-example');
+ execSync(`git rm -q --cached .gitignore && rm .gitignore && git add people && git commit -qm retrack`, { cwd: dir });
+ const error = await refusal(restore('present', slug, { detach: true }));
+ expect(error.code).toBe('invalid_params');
+ expect(error.suggestion).toContain('has its file in place');
+ expect((await pageRow('present', slug)).live).toBe(false);
+ expect((await restore('present', slug)).status).toBe('restored');
+ expect(await pageRow('present', slug)).toEqual({ source_path: `${slug}.md`, database_only_reason: null, live: true });
+ }, 60_000);
+
+ test('doctor missing_recorded_files warns about a live page a full sync would delete, and asks the user', async () => {
+ expect(categorizeCheck('missing_recorded_files')).toBe('brain');
+ const before = await doctor();
+ expect(before.status).toBe('ok');
+ const { slug } = await untrackedPage('stale', 'dana-example');
+ // A page restored the old way: live, still recording the file that left the checkout.
+ await engine.executeRaw('UPDATE pages SET deleted_at=NULL WHERE source_id=$1 AND slug=$2', ['stale', slug]);
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ count: 1 });
+ expect(check.message).toContain(`stale:${slug} (${slug}.md)`);
+ expect(check.message).toContain(`gbrain restore ${slug} --source-id stale --detach`);
+ expect(check.fix).toMatchObject({ ask_user: true });
+ }, 60_000);
+});