Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Managed restore --detach and sync keep declared db_only pages
garrytanb78b1acb6f27
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex c80eafd12e..1fe923e1ae 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -20,7 +20,7 @@ See [generations](generations.md).- **`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). `resolveManagedSyncContext` refuses `skipFailed` / `includeGitignored` on a managed source with `managed_sync_flag_refused` (`managed-sync-flags.ts`, `detail` = the flag, fix = the same `gbrain sync` argv without it), the one refusal jobs, MCP and the cycle reach; `gbrain sync` raises it at parse, before the legacy ledger acknowledgement and the cost gate, `--all` included (#6696). #6865: the per-path eligibility (scope, `sync.exclude`, `sync.include_hidden`, strategy, reserved skillpack paths) and the origin a path maps to under the slug mode come from one exported `loadSyncEligibility(engine, context, opts?, company?)`, which the unindexed-file detector shares.- `src/core/hardened-git.ts` (#6712 additions; base entry in [persistence-stalls](persistence-stalls.md)) — `assertHardenedGitArgs` now checks exact options in every wrapper: `cat-file` with at most `--batch` (never `--filters`, `--textconv` or `--batch-command`), `hash-object --no-filters` optionally with `--stdin-paths`, `check-attr` with `-z`/`--stdin`, and `diff-tree` only as `-r -z --no-renames`. `hardenedGitStream` is the third wrapper: it spawns asynchronously, streams stdout to a callback, feeds stdin with backpressure, SIGKILLs past its timeout or byte cap and rejects when the consumer or the stdin iterable throws; `NulRecordSplitter` and `hardenedStreamComplete` give the completeness rule (exit 0, no signal, output ending at a NUL or empty). Tests: `test/hardened-git-stream-6712.test.ts`, `test/hardened-git-filters.test.ts`.- `src/core/persistence/sync-git-stream.ts` — the managed-sync reconcile's Git level reads (#6712), all through `hardenedGitStream` (allow-listed, filter-free plumbing; the checkout's clean/process filters and textconv never run) and parsed as they stream, so memory is the result maps. `readTreeLevel` (`ls-tree -r -z <commit> -- <scope>`: blobs plus symlinks and gitlinks with their mode), `readIndexLevel` (`ls-files -s -z`, the index only; a conflicted path keeps its highest stage) and `readRenameHints` (`diff-tree -r -z --no-renames`: a deleted and an added regular file paired only when their blob OID is unique to them; hints, never candidates) throw `SyncTreeReadIncomplete` (code `reconcile_read_incomplete`) unless Git exited 0, was not signalled and its output ended at a NUL. `readBlobs` reads contents through one `cat-file --batch`, leaving out missing, oversized and over-total objects. `probeDirtiness` is the batched `hardenedPathDirty` (`Dp`): per batch of 2,000 paths one `hash-object --no-filters --stdin-paths` and one `check-attr -z --stdin`, presence and bytes from `readSyncFile`; verdicts in order `untracked`, `staged` (index and tree differ in OID or mode, a non-zero stage, or one side missing), `deleted`, `unknown` (symlink or gitlink, unreadable file, a path with a newline or a leading quote, any Git failure, an OID that disagrees with the bytes read), then `clean` (raw OID equals the tree with the executable bit matching), `clean_eol` (only `text`/`eol` set and the CRLF-folded bytes hash to the tree), `clean_lfs` (a valid pointer whose sha256 and size match the bytes) or `modified`; another filter, `working-tree-encoding`, an executable-bit-only change or CRLF bytes that fold to the tree with no attribute are `unknown`, never clean. Tests: `test/hardened-git-stream-6712.test.ts` (every verdict, completeness, and a forced probe that 1,000 passes of every read never run a configured filter or textconv while `git status`/`git diff` on the same checkout do). Working mode: `probeDirtiness(..., { working: true })` never reads the index (a path with no file is `deleted`, a present file outside the tree `untracked` with its raw OID, every other present file judged from its bytes against the tree through the same `clean_eol`/`clean_lfs` domains), so a staged edit, a staged new file, `git rm --cached`, a staged deletion and a staged file removed from disk probe as the same disk does with a pristine index: the working level is the physical bytes (design v3.2 §2.1). `hashWorkingLevel` hashes every path of a working round that way with hash-then-restat (a path whose bigint `lstat` moved across the hash is rehashed, up to three attempts) and returns the stat cache it leaves: `WorkingStatCache` is plain JSON (`{v: 1, root, entries: {path: 'dev:ino:mode:uid:size:mtime_ns:ctime_ns' | 'absent'}}`), an entry is written only for a stable stat whose `mtime` and `ctime` are older than 2 s before the attempt began (Git's racy rule) and a probe with a level, and at most `WORKING_STAT_CACHE_MAX_ENTRIES` (100,000) entries are kept in path order. `workingChanged(cache, paths)` is the idle tick's check: a path the cache does not hold, a moved stat, a failed stat, a zero `ctime`, a missing cache or a moved root all read as changed, never as unchanged. `parseWorkingStatCache` validates a serialized copy (junk is null, so everything reads changed); `rememberWorkingStatCache`/`recallWorkingStatCache` keep up to 64 caches per process. Working-mode tests: `test/sync-working-level-6712.test.ts` (probe 41, on the Git reads and on a managed PGLite pass), `test/sync-working-stat-cache-6712.test.ts` (probe 42); the probe 28 marker test also runs `hashWorkingLevel`.-- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).+- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept` (and an absent db_only page), `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and a cross product against a reference model).- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; one call's preparations share group-publish.ts's `preparationReads` memo plus the binding, trust-config and purge-tombstone reads, read their pages through `importGroupReads`' batch (`reread`), and answer each page's origin, timeline, take-collision and safe-chunk-fence reads from one read per kind per call (`sliceReads`), so a call costs a constant, not a statement per page (GBRA-108); equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.- `src/core/persistence/sync-dry-run-writer.ts` — #7167: `readDryRunWriterState(engine, sourceId)`, the writer state a managed dry run reports (`SyncResult.writer`: open queued/running/recovering requests of the source, the oldest one's age, and `gbrain sources writer status` as the next step) instead of waiting on the writer. A CLI dry run runs once outside the drain (`commands/sync/perform.ts`), so the drain's no-progress governor never abandons a long read as a writer stall, and a dry run that is not delegated to a serve says it previews in this process (`commands/sync-delegate.ts`). Test: `test/sync-dry-run-drain-7167.test.ts`.@@ -44,7 +44,7 @@ See [generations](generations.md).- `src/core/persistence/overwritten-edits.ts` — #6712 follow-up: `scanOverwrittenEdits` finds live pages whose database-only revision a managed-sync import replaced with different content and no hold, from durable rows only (it survives receipt compaction): `page_versions.write_request_id` / `archived_write_request_id`, the writer's committed receipt (`outcome.persistence.mode = 'database'`, not an import, no `git` effect for that revision, not a read-only mirror write), the archiving request recognised as a managed-sync import by intent kind or, once compacted, by operation `submit_job` + `outcome.imported_file` without `connector_database`, and `reconcileCanonical` digests (the import's own revision differs; no later revision holds the edit again). `high` or `unknown` (`no_persistence_outcome`, `import_content_unreadable`, `segmented`); the newest open overwrite per page; at most `OVERWRITE_SCAN_LIMIT` candidate versions per source. Revisions with no recorded writer are not reported.- `src/commands/doctor/checks/overwritten-edits.ts` — doctor `sync_overwritten_db_edits` (BRAIN, after `missing_recorded_files`): per source count and first slugs from `scanOverwrittenEdits`; `warn` only for `high` findings, with the read-only `gbrain repair overwritten-edits --source <id>` preview as an `ask_user` fix; `unknown` findings are counted in `details` and never warn.- `src/core/repair/overwritten-edits.ts` — `gbrain repair overwritten-edits`, explicit-only and preview-bound (`--slug` narrows): the preview lists each `high` page with a diff of the live page against the archived edit and saves the set; `--apply --expect <hash>` rechecks the page revision and version digest, then submits `revert_version` with `expected_revision` and `databaseOnly: 'overwrite_restore'` (`page-mutations.ts`: no worktree, receipt `write_through.skipped: overwrite_restore`), so the committed file is never rewritten; when this host owns the checkout and the committed HEAD blob differs from the restored page (`fileMatchesSnapshot`), it writes a `file_drift` hold (`fileDriftHold` + `writeGitHold`, `page_revision` = the restored revision). On another host, or for a file over the read bound, the outcome is `restored_file_unheld` with `next` naming the owner host's `gbrain repair file-drift --prefer database`; an apply whose restore request already committed replays it and writes the hold. Outcomes `restored`, `restored_file_held`, `restored_file_unheld`, `changed_since_preview`. Test: `test/overwritten-edits-6712.test.ts` (PGLite and Postgres).-- `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/detached-pages.ts` — #6609 (D5) restore of a page whose recorded canonical file is gone. `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 (tracked or untracked-not-ignored) with `source_changed` / detail `canonical_file_absent` (not retryable), 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`; on a declared db_only page it is database-only even with write-through (#7324). `detachRestoredPage` runs in the restore publication (from `classifyUnboundPage`) and clears `source_path`, stamping `pages.database_only_reason='detached'`; the page upsert (`engine-sql/pages.ts`) clears that stamp when 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/repair/keep-db-policy.ts` — the opt-in `storage.keep_db` policy (#6696 C7), since #6712 PR 4b an admission of the managed sync pass (design v3.2 §4, d1b option C); the consumer's keep_db worker and its 10-minute timer are gone. `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; doctor `maintenance_write_drift` reads it and `keepDbReceiptCost`. `freezeKeepDbReconcile` builds the `--prefer database` artifact (`prepareDriftPage`) for a path the pass classified `keep_db` (row 18) or `db_ahead`/`db_only` under keep_db (row 15), committed mode with `Dp = clean`, under this host's policy on a source that is not mirror-read-only, and refuses (`{ refused }`) unless the artifact's own read matches the frozen page id, revision, file bytes (`sha256` = `preconditions.raw_file_hash`) and path. `admitKeepDbReconcile` (trusted local pass only, `remote: false`) admits it through `admitReconcileArtifact` (`persistence/reconcile.ts`, the core `runReconcileApply` shares) under this installation's own CLI writer registration as a background producer, without waiting for publication; inside the admission transaction it re-reads `sync.admission` (`admission_paused` when not `normal`) and runs the pass's `inTx` fence, whose error rolls back and is rethrown as is. The request id derives from the page revision and frozen bytes (one drift, one request), skipping an id whose request `sync.admission` cancelled or that holds a retained backup but no request; the intent carries `keepDb: { passId }`, and its publication re-reads `sync.admission` and completes `cancelled`/`admission_paused` with nothing written (`reconcile-prepare.ts`, `coordinator.ts` `failureState`). `releaseMatchedDriftSkips` releases the concept drift skips of pages the pass classified `matched`. Tests: `test/keep-db-pass-admission.test.ts` (probes 26, 27, 47, 51; Postgres via `test/e2e/keep-db-pass-admission-postgres.test.ts`), `test/keep-db-consumer-retired.test.ts`, `test/file-drift-bulk-reconcile.test.ts` (PGLite; Postgres via `test/e2e/file-drift-bulk-reconcile-postgres.test.ts`).- `src/core/persistence/sync-origin-evidence.ts` — #7130: whether a missing file is deletion evidence. `readOriginEvidence(gitRoot, tips, paths)` answers `committed` / `never_committed` / `ignored` / `unknown` per Git-root-relative path from one cached history walk per tip (`historyIndex`: `git log --full-history --name-status`, extended past a cached ancestor; 600 s) and `git check-ignore --no-index -z --stdin` per 500-path batch; a failed read is `unknown`, which the classifier holds. `readDeletionProvenance` reads the same walk. `gitIgnoresUntracked` is the write-through test (`page-prepare.ts` keeps a managed write into an ignored path database-only; classic `sync/full.ts` keeps a stale page whose ignored file is still on disk). Read by `sync-pass.ts` (`reclassifyByOrigin`, delete and delete_drift paths only), `sync-discovery.ts` (tree-absent deletes) and the doctor scanner `src/core/uncommitted-deletions.ts`. Test: `test/sync-uncommitted-origin-7130.test.ts`.- `src/core/persistence/sync-delete-tombstones.ts` — #7130: the record a `managed_sync_delete` apply writes in its own transaction (op `sync-delete-tombstone`, fingerprint = page id, `deleted_at` equal to the page row's), the `syncDeleteOrigin` SQL predicate (record, or the uncompacted committed receipt) and `readUnreviewedSyncTombstones` (sync tombstones with no live twin by `content_hash`). `purge-deleted.ts` holds that set when `automatic` (cycle purge phase, `purge` job; `blocked` code `sync_delete_unreviewed`) and only counts it for the consented manual purge; `purgeStaleCheckpoints` keeps a record while its tombstone exists. Test: `test/purge-sync-tombstone-hold-7130.test.ts`.diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 3564a4c43b..5bae9f98db 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -418,8 +418,8 @@ it, and a `--full` continues until every path it covers is settled.- `none`, nothing to do: `matched` (the page is what the file says),`adopt` (the import record is updated to the file without a page write),- `kept` (the commit no longer has a file that is still on disk, so its page- stays), `untracked` (a file on disk the commit does not have, with no+ `kept` (the commit no longer has a file that is still on disk, or the page+ is under a declared `storage.db_only` dir, so its page stays), `untracked` (a file on disk the commit does not have, with nopage), `gone` (no file and no live page), `deleted_same` and `legacy_same` (a deleted page whose file isunchanged), and `db_ahead` (the page changed in the database and the filedid not; the sub-labels `pending`, `db_only` and `unproven` arediff --git a/docs/storage-tiering.md b/docs/storage-tiering.mdindex 4307073308..9cf3b4c028 100644--- a/docs/storage-tiering.md+++ b/docs/storage-tiering.md@@ -53,7 +53,7 @@ storage:When storage configuration is present, `gbrain sync` automatically manages `.gitignore` entries on every successful sync:- Adds missing `db_only` directory patterns to `.gitignore`.-- A file under a `db_only` directory that git already tracked before the declaration stays tracked and shows as modified once the database updates it; untrack it with `git rm --cached <path>`.+- A file under a `db_only` directory that git already tracked before the declaration stays tracked and shows as modified once the database updates it; untrack it with `git rm --cached <path>`. A managed sync never soft-deletes a live page under a declared `db_only` directory because its file left Git (untracked, ignored or gone): the database copy is canonical (#7324).- Idempotent — re-running adds no duplicate entries.- Stable comment header so the managed block is grep-able.- Skipped on `--dry-run` (don't mutate disk in preview mode).@@ -216,6 +216,14 @@ explicit choice. `--detach` is refused (`invalid_params`) when there isnothing to detach (the page is not soft-deleted, its file is in place, or therestore re-creates it).+A page under a declared `db_only` directory is canonical in the database, so+its `--detach` restore publishes database-only even on a managed checkout with+`sync.write_through` on (#7324): it keeps its page id, content and history,+forgets its recorded file, writes no file and leaves an ignored cache file+untouched. Its recorded file must still be gone from the syncable tree. A plain+restore of such a page keeps its recorded file and its cache file as before;+sync no longer deletes it either way.+Doctor `missing_recorded_files` warns about live pages whose recorded file isnot among the files `gbrain sync --full` enumerates (for example a pagerestored the old way), so that sync would soft-delete them; it inspects at mostdiff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 2ee7cf1e52..a17dab7e27 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -632,7 +632,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"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."+ "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, or for a page under a declared storage.db_only dir whose recorded file left the checkout; ask the user first."}},"mutating": true,diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 7ddce71a7b..25f0e0576d 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -454,7 +454,7 @@ const restore_page: Operation = {...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.' },+ 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, or for a page under a declared storage.db_only dir whose recorded file left the checkout; ask the user first.' },},mutating: true,scope: 'write',diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex f479e77114..0b038eb494 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -35,6 +35,7 @@ import { normalizeSubagentPageInput, undeclaredPageTypeWarning, type PageTypeWarimport { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { decideUnboundWrite, isUnboundSourcePage } from './unbound-source.ts';import { assertRestoreOrigin } from './detached-pages.ts';+import { isSourceDbOnlySlug } from './source-storage.ts';import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';import { publishesDatabaseOnly } from './page-prepare.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';@@ -389,17 +390,21 @@ export async function preparePageAdmission(ctx: OperationContext,let binding = boundAtStart;const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);const configuredWriteThrough = !/^(false|0|off|no)$/i.test(writeThroughSetting ?? 'true');- const writeThrough = configuredWriteThrough && !sandbox && !input.databaseOnly;const root = source.local_path || repoPath;+ // Checkout paths belong to a host binding; sources.local_path may name+ // another host's original checkout after a verified ownership transfer.+ const localRoot = binding ? binding.owner_host_id === localHostId() && binding.local_path+ ? join(binding.local_path, binding.relative_path) : null : root;+ // #7324: a declared db_only page is canonical in the database, so its detach restore publishes database-only even+ // where write-through would re-create its file (a managed checkout); assertRestoreOrigin still requires the file gone.+ const databaseOnly = input.databaseOnly ?? (input.operation === 'restore_page' && p.detach === true && localRoot+ && isSourceDbOnlySlug(localRoot, slug, 'not_db_only') ? 'detached' : undefined);+ const writeThrough = configuredWriteThrough && !sandbox && !databaseOnly;if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';- else if (input.databaseOnly) authority.databaseOnlyReason = input.databaseOnly;+ else if (databaseOnly) authority.databaseOnlyReason = databaseOnly;else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';else if (!root && !binding) authority.databaseOnlyReason = 'no_repo_configured';if (p.local_dir !== undefined) {- // Checkout paths belong to a host binding; sources.local_path may name- // another host's original checkout after a verified ownership transfer.- const localRoot = binding ? binding.owner_host_id === localHostId() && binding.local_path- ? join(binding.local_path, binding.relative_path) : null : root;let matches = false;if (ctx.remote === false && typeof p.local_dir === 'string' && localRoot) {try { matches = realpathSync(resolve(p.local_dir)) === realpathSync(resolve(localRoot)); } catch { /* missing local binding */ }diff --git a/src/core/persistence/sync-classify.ts b/src/core/persistence/sync-classify.tsindex 7f607ad932..92d215fb1d 100644--- a/src/core/persistence/sync-classify.ts+++ b/src/core/persistence/sync-classify.ts@@ -64,6 +64,8 @@ export interface SyncPathState {fullObligation?: boolean;/** Under a `storage.keep_db` prefix, on a source that is not mirror-read-only. */keepDb: boolean;+ /** #7324: a page under a declared `storage.db_only` dir: its database row is canonical, so an absent file is no deletion evidence. */+ dbOnly?: boolean;/** Open work on the page or path (a queued/running/recovering request, a pending Git effect). */openWork: boolean;/**@@ -151,6 +153,7 @@ function afterHold(s: SyncPathState): Matched {if (live && s.level === null) {if (s.mode === 'committed' && s.present) return { cls: 'kept', settled: true, action: 'none' };if (!s.present) {+ if (s.dbOnly) return { cls: 'kept', settled: true, action: 'none' };if (s.originEvidence && s.originEvidence !== 'committed') return { cls: 'delete_drift', settled: false, action: 'hold', side: 'deleted', state: 'file_gone',uncommitted: s.originEvidence === 'unknown' ? 'origin_unknown' : s.originEvidence };return proof ? { cls: 'delete', settled: false, action: 'delete' } : { cls: 'delete_drift', settled: false, action: 'hold', side: 'deleted', state: 'file_gone' };diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex a9ba86d746..97d4516dbf 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -34,6 +34,7 @@ import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHoimport { readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';import { gitChildEnv } from '../git-env.ts';import { readOriginEvidence } from './sync-origin-evidence.ts';+import { isSourceDbOnlySlug } from './source-storage.ts';import { movedDriftHolds, prescreenSyncEntries, type SyncDriftSide } from './sync-prescreen.ts';import { sliceEntries, type SyncSliceCursor, type SyncSliceState } from './sync-slices.ts';@@ -649,6 +650,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, celse winner.renameHeld = held;}}+ // #7324: a page under a declared db_only dir is canonical in the database, so its file leaving Git deletes nothing (the pass's `kept`).+ if (!company) for (const entry of selected) if (entry.action === 'delete' && entry.slug && isSourceDbOnlySlug(root, entry.slug, 'not_db_only')) retired.add(entry);if (retired.size) discovered.entries = selected.filter(entry => !retired.has(entry));if (collisions.length) discovered.slugCollisions = collisions;// Identities and origin collisions were resolved over the whole target above; only the frozen manifest is cut.diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 22de03f7bb..2e9945cba8 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -24,7 +24,7 @@ import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';import { resolveSlugRootMode } from '../sync-anchor.ts';import { resolveSlugForPath } from '../sync.ts';import { join } from 'node:path';-import { isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';+import { isDeclaredDbOnlySlug, isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { currentCompanyBrainSync, getCompanyBrainProfile } from '../company-brain/profile.ts';import { sha256 } from './digest.ts';@@ -628,7 +628,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst settings = await readLevelSettings(engine, context, scope, input);timings.setup = t();if (!settings) return null;- const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, workingConfig, metafilePages } = settings;+ const { slugMode, exclude, pack, mirror, strategy, includeHidden, keepDbPrefixes, storage, workingConfig, metafilePages } = settings;const sourceRelative = (gitPath: string) => (scope ? gitPath.slice(scope.length + 1) : gitPath);let metafilePage: (gitPath: string) => boolean = () => false;// Eligibility of a path outside the cached tree (every path of the tree is eligible); origins validate per call: a@@ -799,6 +799,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st: input.full === true && live,fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true,keepDb: !mirror && keepDbPrefixes.length > 0 && row && isKeepDbSlug(pages.slug[at!]!, keepDbPrefixes),+ dbOnly: row && isDeclaredDbOnlySlug(pages.slug[at!]!, storage),openWork: row && open.pageIds.has(Number(pages.id[at!])) || open.origins.has(origin),};return { state, ...(row ? { at } : {}), ...(legacyPageless ? { legacyPageless } : {}) };@@ -817,7 +818,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st}).then(found => { timings.legacy = t(); return found; }): new Map<string, string>();- const classifiedKey = JSON.stringify([treeKey, mode, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);+ const classifiedKey = JSON.stringify([treeKey, mode, input.pass?.episodeFullId ?? null, input.full === true, mirror, keepDbPrefixes, storage?.db_only ?? [], pack?.identity ?? null, baselineCommit, !!input.pass?.bootstrap, [...colonRefused].sort()]);const reuse = snapshot.changed && priorClassified?.key === classifiedKey ? reusableMatched(priorClassified.paths, matchedUnchanged({ pages, tree, byOrigin, claimants, holds: holdByGitPath, markers, open,changed: confirmChangedPaths(pages, snapshot.changed, (sourcePath, slug) => gitPathOf(pageOrigin(sourcePath, slug))), indexDelta, spelled: path => twins.has(path) || legacySpelling.has(path), originOf })) : null;// A round that reuses nothing lets the previous round's paths go before it builds its own: one level held, not two.@@ -951,10 +952,11 @@ async function readLevelSettings(engine: BrainEngine, context: ManagedSyncContex]);const settled = <T>(read: PromiseSettledResult<T>): T => { if (read.status === 'rejected') throw read.reason; return read.value; };if (settled(company)) return null;+ const storage = (() => { try { return loadStorageConfig(root); } catch { return null; } })();return { slugMode: settled(slugModeRead), exclude: settled(excludeRead), pack: settled(packRead), mirror: settled(mirrorRead), workingConfig: settled(workingRead),metafilePages: settled(metafilePagesRead), strategy: input.pass?.strategy ?? (context.source.config?.strategy as string | undefined) ?? 'markdown',includeHidden: [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))],- keepDbPrefixes: (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })() };+ keepDbPrefixes: storage?.keep_db ?? [], storage };}/** A failed mark, proof or delta read: the round reads again without them (it aborted a Postgres snapshot). */diff --git a/test/e2e/restore-detach-db-only-7324-postgres.test.ts b/test/e2e/restore-detach-db-only-7324-postgres.test.tsnew file mode 100644index 0000000000..95405d8d26--- /dev/null+++ b/test/e2e/restore-detach-db-only-7324-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../restore-detach-db-only-7324.test.ts'));diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 7400005fa8..3040885ed2 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": 262702,- "stdoutSha256": "bfd962a82f16847c7969963ab23410170196491231dcdef214ab3863873b495e",+ "stdoutBytes": 262792,+ "stdoutSha256": "812ee4d094e1ff2456bfea1cd565a32bce5fb60c85419c766c8f46ae378055db","toolNames": ["remember","entity",@@ -837,7 +837,7 @@"schema": {"properties": {"detach": {- "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.",+ "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, or for a page under a declared storage.db_only dir whose recorded file left the checkout; ask the user first.","type": "boolean"},"expected_revision": {diff --git a/test/restore-detach-db-only-7324.test.ts b/test/restore-detach-db-only-7324.test.tsnew file mode 100644index 0000000000..8584379861--- /dev/null+++ b/test/restore-detach-db-only-7324.test.ts@@ -0,0 +1,150 @@+/**+ * #7324: a managed brain (write-through on) whose library/ cards were committed, then declared storage.db_only in+ * gbrain.yml, untracked and ignored. On a real managed brain (PGLite, and Postgres through the E2E wrapper), this+ * protects:+ * - a managed sync, incremental and full, keeps every live page under a declared db_only dir whose file left Git (an+ * ignored cache file still on disk, or no file at all): zero deletions, while a committed-then-removed page outside+ * db_only is still deleted;+ * - restore_page with detach: true of a sync-deleted db_only card restores it database-only on the managed source:+ * same page id, content and history, source_path cleared, database_only_reason='detached', the ignored cache file+ * left as it was and no file created for the card that has none; the next syncs keep it live;+ * - a plain restore of a db_only card keeps its recorded file and the next full sync no longer deletes it;+ * - the guards stay: a stale expected_revision refuses, and a tracked page outside db_only still refuses detach+ * because the restore re-creates its file.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { operations } from '../src/core/operations.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { discoverManagedSync } from '../src/core/persistence/sync-discovery.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { waitFor } from './helpers/wait-for.ts';++const restore_page = operations.find(op => op.name === 'restore_page')!;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const CARDS = ['library/card-cached', 'library/card-gone', 'library/card-plain'];+const setup = ({ root }: { root: string }) => {+ git(root, 'init', '-q');+ for (const slug of [...CARDS, 'notes/keep', 'notes/control']) {+ mkdirSync(join(root, slug, '..'), { recursive: true });+ writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));+ }+ commit(root, 'seed');+};++/** Untracks and ignores library/ (its cache files stay on disk, except card-gone's) and git rm's notes/control. */+function untrackLibrary(root: string) {+ writeFileSync(join(root, '.gitignore'), 'library/\n');+ git(root, 'rm', '-r', '-q', '--cached', 'library');+ git(root, 'rm', '-q', 'notes/control.md');+ rmSync(join(root, 'library/card-gone.md'));+ commit(root, 'untrack library');+}+function declareDbOnly(root: string) {+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - library/\n');+ commit(root, 'declare library db_only');+}++const pageRow = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ id: number; live: boolean; source_path: string | null; database_only_reason: string | null; compiled_truth: string }>(+ "SELECT id, deleted_at IS NULL AS live, source_path, database_only_reason, compiled_truth FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!;+const versions = async (engine: BrainEngine, slug: string) => Number((await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id='default' AND p.slug=$1", [slug]))[0]!.n);+const syncDeletes = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM persistence_requests WHERE source_id='default' AND state='committed' AND intent->>'kind'='managed_sync_delete'"))[0]!.n);++async function restore(ctx: OperationContext, slug: string, extra: Record<string, unknown> = {}) {+ const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });+ return restore_page.handler(ctx, { slug, source_id: 'default', 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) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++for (const backend of testBackends()) describe(`[${backend}] #7324: declared db_only pages on a managed write-through source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('a managed sync, incremental and full, keeps live db_only pages whose file left Git; a removed page outside db_only is deleted', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ declareDbOnly(root);+ untrackLibrary(root);+ const ids = await Promise.all(CARDS.map(async slug => (await pageRow(engine, slug)).id));+ // The frozen manifest a dry run and a company brain read selects the same: only notes/control is deleted.+ for (const full of [false, true]) {+ const discovered = await discoverManagedSync(engine, { ...OPTS, full });+ expect(discovered.entries.filter(entry => entry.action === 'delete').map(entry => entry.sourcePath)).toEqual(['notes/control.md']);+ }+ await performManagedSync(engine, OPTS);+ expect((await pageRow(engine, 'notes/control')).live).toBe(false);+ const deletes = await syncDeletes(engine);+ await performManagedSync(engine, { ...OPTS, full: true });+ for (const [i, slug] of CARDS.entries()) expect(await pageRow(engine, slug)).toMatchObject({ id: ids[i], live: true, source_path: `${slug}.md` });+ expect((await pageRow(engine, 'notes/keep')).live).toBe(true);+ expect(await syncDeletes(engine)).toBe(deletes);+ expect(readFileSync(join(root, 'library/card-cached.md'), 'utf8')).toBe(note('library/card-cached', 'The committed body of library/card-cached.'));+ }, { databaseUrl, setup }), 240_000);++ test('detach restores a sync-deleted db_only card database-only with its identity; the next syncs keep it; guards stay', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const liveRevision = (await engine.readPageSnapshot('library/card-cached', { sourceId: 'default' }))!.revision;+ // The reported state: the cards were committed, untracked and ignored, and a full managed sync soft-deleted them.+ untrackLibrary(root);+ await performManagedSync(engine, { ...OPTS, full: true });+ for (const slug of CARDS) expect((await pageRow(engine, slug)).live).toBe(false);+ expect(await syncDeletes(engine)).toBe(CARDS.length + 1);+ declareDbOnly(root);+ const cached = readFileSync(join(root, 'library/card-cached.md'), 'utf8');+ const before = Object.fromEntries(await Promise.all(CARDS.map(async slug => [slug, { row: await pageRow(engine, slug), versions: await versions(engine, slug) }] as const)));++ const stale = await refusal(restore(ctx, 'library/card-cached', { detach: true, expected_revision: liveRevision }));+ expect(stale.code).toBe('revision_conflict');+ expect((await pageRow(engine, 'library/card-cached')).live).toBe(false);++ for (const slug of ['library/card-cached', 'library/card-gone']) {+ expect((await restore(ctx, slug, { detach: true })).status).toBe('restored');+ expect(await pageRow(engine, slug)).toEqual({ ...before[slug]!.row, live: true, source_path: null, database_only_reason: 'detached' });+ expect(await versions(engine, slug)).toBeGreaterThanOrEqual(before[slug]!.versions);+ }+ expect(readFileSync(join(root, 'library/card-cached.md'), 'utf8')).toBe(cached);+ expect(existsSync(join(root, 'library/card-gone.md'))).toBe(false);++ // A plain restore keeps the recorded file; the full sync below must not delete it again.+ expect((await restore(ctx, 'library/card-plain')).status).toBe('restored');+ expect(await pageRow(engine, 'library/card-plain')).toMatchObject({ id: before['library/card-plain']!.row.id, live: true, source_path: 'library/card-plain.md' });++ const deletes = await syncDeletes(engine);+ await performManagedSync(engine, OPTS);+ await performManagedSync(engine, { ...OPTS, full: true });+ expect(await syncDeletes(engine)).toBe(deletes);+ for (const slug of ['library/card-cached', 'library/card-gone']) {+ expect(await pageRow(engine, slug)).toMatchObject({ id: before[slug]!.row.id, live: true, source_path: null, database_only_reason: 'detached' });+ }+ expect(await pageRow(engine, 'library/card-plain')).toMatchObject({ live: true, source_path: 'library/card-plain.md' });+ expect(existsSync(join(root, 'library/card-gone.md'))).toBe(false);++ // A tracked page outside db_only: the restore re-creates its file, so detach is refused exactly as before.+ const keep = await engine.readPageSnapshot('notes/keep', { sourceId: 'default' });+ const requestId = randomUUID();+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: 'notes/keep', expected_revision: keep!.revision, request_id: requestId } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed',+ { timeoutMs: 20_000, label: 'delete_page notes/keep commits' });+ await settleManagedGitEffects(engine);+ const refused = await refusal(restore(ctx, 'notes/keep', { detach: true }));+ expect(refused.code).toBe('invalid_params');+ expect(refused.suggestion).toContain('gets its file re-created by this restore');+ expect((await pageRow(engine, 'notes/keep')).live).toBe(false);+ expect((await restore(ctx, 'notes/keep')).status).toBe('restored');+ expect(await pageRow(engine, 'notes/keep')).toMatchObject({ live: true, source_path: 'notes/keep.md', database_only_reason: null });+ expect(existsSync(join(root, 'notes/keep.md'))).toBe(true);+ }, { databaseUrl, setup }), 240_000);+});