Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(purge,doctor): hold unreviewed sync tombstones from automatic purge, purge.retention_hours, doctor uncommitted_sync_deletions + preview-first restore (#7130)
garrytan40e7a9b3b7ad
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex f0cffb1ff1..74b907191e 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -146,6 +146,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync, or by a connector source on an older gbrain), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. || `file-drift` | `maintenance_write_drift` | Explicit-only, preview-bound. Resolves pages whose canonical file differs from the database copy (`source_changed` / `file_database_drift`) through canonical reconciliation, preferring the file or the database copy within reconcile's protections. `--all-drifted` refuses mixed drift classes unless `--class` keeps one; `--only`/`--skip` narrow by canonical file path glob. Opt-in `storage.keep_db` lets the owner host's resident consumer resolve drift under declared prefixes with the database copy. A page whose file is gone from the last commit: `--prefer database` recreates the file, `--prefer file` soft-deletes the page ([deleted canonical files](#deleted-canonical-files)). See [file drift](#file-drift). | Protected metadata, the tag union and protected takes or private fact rows, listed per page as `exceptions`; pages changed after the preview (`changed_since_preview`). || `ghost-pages` | `ghost_pages` | Explicit-only, preview-bound, destructive consent. Soft-deletes live pages whose canonical file is missing on the owner host (ghost pages: every write refuses `canonical_file_missing` and no sync can import a file that is not there), through `delete_page` bound to the previewed owner, path and revision. `--apply --expect <hash> --yes`. See [ghost pages](#ghost-pages). | Declared db_only and never-filed derived pages (never listed); a page whose file came back before the apply (`file_restored`); pages changed after the preview (`changed_since_preview`). |+| `uncommitted-deletions` | `uncommitted_sync_deletions` | Explicit-only, preview-bound, consent. Restores soft-deleted pages a managed sync removed before #7130 although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), one `restore_page` with `detach` each, published database-only: the page comes back live, forgets its recorded file, and no file is written. `--apply --expect <hash> --yes`. See [uncommitted deletions](#uncommitted-deletions). | Pages another writer deleted (listed, restored only with `--include-ambiguous`); tombstones whose file Git once committed or that is on the disk again; paths Git could not answer for (`unknown`); purged pages (only a backup brings them back). || `receipt-compaction` | `persistence_capacity` (terminal bytes) | Explicit-only, preview-bound, destructive consent. Compacts terminal write receipts now instead of on the idle maintenance tick (#6696): the intent and error message are dropped, the outcome, error code and detail stay, and the unused reservation returns to the receipt-bytes counters. `--older-than <72h\|30d>` is floored at the configured retention unless `--force`; committed receipts only unless `--include-failures`. No admission, so it runs at a full cap. See [receipt compaction](#receipt-compaction). | `failures_kept`: failed, conflict and cancelled receipts left without `--include-failures`. Receipts of a run whose sync cursor is still open, and the newest sync receipt of each worktree, are never listed. || `aliases` | `dangling_aliases` (orphaned rows) | Explicit-only. Deletes free-text page aliases and slug redirects whose target page has no row at all (a page purged before purge removed its aliases, #6619, or a hard-deleted page), each target rechecked under its page lock; a coordinated maintenance write on a managed brain. A redirect from an old name of a page that still exists is never touched. See [aliases](#aliases). | `soft_deleted_target`: aliases of a soft-deleted page, kept for `gbrain restore` and removed when the page is purged. || `rename-identity` | `rename_identity_downgrades` | Explicit-only, preview-bound, destructive consent. For an inexact Git rename that sync split into a delete plus an add (#6729): carries the old page's identity (id, version history, timeline, links, facts, aliases) onto the new slug, imports the new file onto it as an edit and retires the provisional page; or, with `--close`, settles the pair and moves nothing. `--slug <new-slug>` (and `--from <old-slug>`) names one pair; `--apply --expect <hash> --yes`. See [rename identity](#rename-identity). | `fact_rows_collide` (a fence row of the old page the new file does not keep with the same claim); `managed_remedy_unavailable` (a carry on a managed source; `--close` is the remedy there); pages changed after the preview (`changed_since_preview`). |@@ -1130,6 +1131,51 @@ database only and are never ghosts. Doctor `undeclared_db_only_pages` is aseparate audit. A preview lists at most 1,000 ghosts; apply them, then previewagain for the rest. Sync never removes ghost pages by itself.+<a id="uncommitted-deletions"></a>+### Uncommitted deletions++Before #7130 a managed sync read any absent recorded file as a deletion, even a+file Git never committed: an agent's write-through file in a directory+`.gitignore` excludes, or an untracked file removed before any commit. It+soft-deleted those pages, and the purge removes a tombstone for good after its+retention window. Sync now holds such a page instead+([file drift](#file-drift), side `deleted`, reason `never_committed` or+`ignored`). For a brain already hit, doctor `uncommitted_sync_deletions`+counts, on each source's owner host, the tombstones a sync deleted whose file+`.gitignore` excludes or no commit of HEAD's history holds (and that is not on+the disk). It reads at most 20,000 tombstones per source and the Git evidence+of 2,000 files per run, sync deletions first, and says when it was bounded.+Off the owner host, or on a brain without managed sync, it is `ok` and not+applicable. To restore them, preview, then apply after the user agrees:++```bash+gbrain repair uncommitted-deletions --source default # preview: slug, recorded path, deletion time, evidence, who deleted it, and a hash+gbrain repair uncommitted-deletions --source default --apply --expect <hash> --yes+```++**Pages already purged cannot be restored by this command; only a backup+(`pg_dump`, or a `gbrain backup create` taken before the purge) can bring them+back.** Restore what is still there before the purge runs.++The preview writes nothing. Its default set is the pages a sync deleted (a+committed `managed_sync_delete` request is the newest deletion of the slug);+pages another writer deleted are listed apart and join the hashed set only with+`--include-ambiguous`. The apply needs the user's consent: without `--yes` a+terminal asks, and a non-interactive run exits 3 with the consent payload and+changes nothing. It restores exactly the previewed set, bound to the owner and+each page's revision, through one coordinated `restore_page` with+`detach: true` per page, published database-only: the page comes back live+with no recorded file (`database_only_reason='detached'`) and no file is+written, so no later sync reads its file as missing. A page that moved since+the preview is skipped `changed_since_preview`; one whose file is in the+checkout again is skipped `file_restored` (commit it and sync instead); one+purged in between is skipped `purged`. A wrong or stale hash refuses+[`preview_changed`](#preview-changed), and off the owner host the preview and+the apply refuse [`not_owner_host`](error-codes.md#not_owner_host). Undo one+page with `gbrain delete <slug>`. A preview lists at most 1,000 pages; apply+them, then preview again. The repair runs only when named, never on upgrade or+from a maintenance cycle.+<a id="legacy-twins"></a>### Legacy twinsdiff --git a/src/commands/doctor/checks/uncommitted-sync-deletions.ts b/src/commands/doctor/checks/uncommitted-sync-deletions.tsnew file mode 100644index 0000000000..facc567365--- /dev/null+++ b/src/commands/doctor/checks/uncommitted-sync-deletions.ts@@ -0,0 +1,77 @@+/**+ * #7130 `uncommitted_sync_deletions`: soft-deleted pages a managed sync removed although Git never held their recorded+ * file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), one reader in+ * `src/core/uncommitted-deletions.ts`. Before #7130 sync read such an absent file as a deletion, so the tombstone may hold+ * the only copy of the page and the purge removes it for good after its retention window. The finding names the+ * read-only `gbrain repair uncommitted-deletions --source <id>` preview; restoring is the user's decision.+ *+ * Read-only and bounded: at most `TOMBSTONE_SCAN_LIMIT` tombstones per source and `DOCTOR_PATH_LIMIT` Git evidence reads+ * per run (sync deletions first), with `truncated` / `exact` details. Pages deleted by another writer are counted apart+ * and never warn. Off the owner host, on a brain without managed sync or with no bound source it is `ok` + info+ * (`not_applicable`); a checkout or Git history that cannot be read is the unknown convention (`warn`, `health: unknown`).+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { DOCTOR_PATH_LIMIT, PURGED_NOTE, scanUncommittedDeletions, type UncommittedDeletionScan } from '../../../core/uncommitted-deletions.ts';++const DOCS = 'docs/guides/repair.md#uncommitted-deletions';+const SAMPLE_LIMIT = 5;++async function runUncommittedSyncDeletions(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const engine = connectedEngine(ctx);+ const sourceIds = (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const scans: UncommittedDeletionScan[] = [];+ let budget = DOCTOR_PATH_LIMIT;+ for (const sourceId of sourceIds) {+ const scan = await scanUncommittedDeletions(engine, sourceId, { pathLimit: budget });+ budget -= scan.checked;+ scans.push(scan);+ }+ const bySync = scans.flatMap(scan => scan.pages.filter(page => page.deleted_by === 'sync'));+ const byOther = scans.flatMap(scan => scan.pages.filter(page => page.deleted_by !== 'sync'));+ const unknown = scans.filter(scan => scan.status === 'unknown' || scan.unknown > 0);+ const truncated = scans.some(scan => scan.truncated);+ const details = { count: bySync.length, other_writer_count: byOther.length, truncated, exact: !truncated && !unknown.length, purged: PURGED_NOTE, docs: DOCS,+ by_source: scans.map(scan => ({ source_id: scan.source_id, status: scan.status, ...(scan.reason ? { reason: scan.reason } : {}), sync_deleted: scan.pages.filter(page => page.deleted_by === 'sync').length,+ other_writer: scan.pages.filter(page => page.deleted_by !== 'sync').length, tombstones: scan.tombstones, checked: scan.checked, unknown: scan.unknown, truncated: scan.truncated })),+ samples: bySync.slice(0, SAMPLE_LIMIT).map(({ source_id, slug, source_path, deleted_at, evidence }) => ({ source_id, slug, source_path, deleted_at, evidence })) };+ const otherNote = byOther.length ? ` ${byOther.length} more soft-deleted page(s) with an uncommitted file were deleted by another writer, not by a sync (the preview lists them; --include-ambiguous restores them).` : '';+ if (bySync.length) {+ const sources = [...new Set(bySync.map(page => page.source_id))];+ checks.push({ name: 'uncommitted_sync_deletions', status: 'warn', details: { ...details, ...(unknown.length ? { health: 'unknown' } : {}) },+ message: `${bySync.length}${details.exact ? '' : '+'} soft-deleted page(s) were removed by a sync although Git never held their file (.gitignore excludes it, or it was never committed), so each tombstone may be the only copy and the purge removes it for good `+ + `(${sources.map(source => `${source}: ${bySync.filter(page => page.source_id === source).length}`).join('; ')}; e.g. ${details.samples.map(page => `${page.source_id}:${page.slug} (${page.source_path}, ${page.evidence})`).join(', ')}). `+ + `Preview the restore with gbrain repair uncommitted-deletions --source ${sources[0]}. ${PURGED_NOTE}${otherNote}`,+ fix: agentFix(['gbrain', 'repair', 'uncommitted-deletions', '--source', sources[0]!, '--json'],+ 'Read-only preview: lists each page with its recorded path, deletion time and evidence, and prints the apply command with its hash. Apply only after the user agrees (each page comes back live and database-only).',+ 'uncommitted_sync_deletions', { docs: DOCS }) });+ return checks;+ }+ if (unknown.length) {+ checks.push({ name: 'uncommitted_sync_deletions', status: 'warn', details: { ...details, health: 'unknown' },+ message: `Soft-deleted pages of ${unknown.map(scan => `${scan.source_id} (${scan.reason ?? `${scan.unknown} unreadable path(s)`})`).join(', ')} could not be checked: the checkout or its Git history could not be read, so no count is reported.`,+ fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', unknown[0]!.source_id, '--json'],+ 'Read-only: shows the source\'s canonical root and owner host so the checkout can be inspected.', 'uncommitted_sync_deletions', { docs: DOCS }) });+ return checks;+ }+ if (!scans.some(scan => scan.status === 'known')) {+ const reason = scans.some(scan => scan.reason === 'not_owner_host') ? 'not_owner_host' : scans[0]?.reason === 'not_managed' ? 'not_managed' : 'not_applicable';+ checks.push({ name: 'uncommitted_sync_deletions', status: 'ok', severity: 'info', readiness_state: 'not_applicable', details: { ...details, reason },+ message: reason === 'not_owner_host'+ ? 'Not applicable on this host: soft-deleted pages are checked against each source\'s checkout on its canonical owner host (run doctor there).'+ : reason === 'not_managed' ? 'Not applicable: this brain has no managed sync, which is what removed pages whose file Git never held.'+ : 'Not applicable: no source has a canonical checkout on this host.' });+ return checks;+ }+ checks.push({ name: 'uncommitted_sync_deletions', status: 'ok', details,+ message: `No soft-deleted page was removed by a sync while Git never held its file (${scans.reduce((sum, scan) => sum + scan.checked, 0)} tombstone(s) checked${truncated ? '; bounded, more not checked' : ''}).${otherNote}` });+ } catch (error) {+ checks.push(checkError('uncommitted_sync_deletions', 'check soft-deleted pages for files Git never held', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } }));+ }+ return checks;+}++export const uncommittedSyncDeletionsEntry: DoctorEntry = { name: 'uncommitted_sync_deletions', emits: ['uncommitted_sync_deletions'], run: runUncommittedSyncDeletions };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex cc72c86ea7..fe9151a5d4 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -123,6 +123,7 @@ import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgradimport { unindexedFilesEntry } from './checks/unindexed-files.ts';import { purgeParkedPagesEntry } from './checks/purge-parks.ts';import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';+import { uncommittedSyncDeletionsEntry } from './checks/uncommitted-sync-deletions.ts';import { overwrittenEditsEntry } from './checks/overwritten-edits.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';import { managedSyncLatencyEntry } from './checks/managed-sync-latency.ts';@@ -258,6 +259,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [renameIdentityDowngradesEntry,purgeParkedPagesEntry,missingRecordedFilesEntry,+ uncommittedSyncDeletionsEntry,unindexedFilesEntry,overwrittenEditsEntry,syncConfigKeysEntry,diff --git a/src/commands/pages.ts b/src/commands/pages.tsindex fcc9f9acd8..9b7f181228 100644--- a/src/commands/pages.ts+++ b/src/commands/pages.ts@@ -53,12 +53,14 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voiif (dryRun) {// Read-only: the same predicate and DB now() clock as the real purge; only the verb differs.if (json) {- console.log(JSON.stringify({ dry_run: true, older_than_hours: olderThanHours, count: selection.count, slugs: selection.slugs, ...notes }, null, 2));+ console.log(JSON.stringify({ dry_run: true, older_than_hours: olderThanHours, count: selection.count, slugs: selection.slugs, sync_unreviewed: selection.sync_unreviewed, ...notes }, null, 2));return;}console.log(`(dry-run) Would purge ${selection.count} page(s) soft-deleted more than ${olderThanHours}h ago.`);+ // #7130: the automatic purge keeps these; a purged page can only come back from a backup.+ if (selection.sync_unreviewed) console.log(` ${selection.sync_unreviewed} of them were deleted by a managed sync, not a person, and no live page has their content; restore any you need first (gbrain restore <slug> --source-id <id> --force). A purged page can only come back from a backup.`);for (const p of selection.pages ?? []) console.log(` ${p.slug} deleted_at=${p.deleted_at.toISOString()}`);- for (const c of selection.candidates) console.log(` ${c.source_id}/${c.slug}${c.park ? ' (parked; retried once more)' : ''}`);+ for (const c of selection.candidates) console.log(` ${c.source_id}/${c.slug}${c.park ? ' (parked; retried once more)' : ''}${c.sync_unreviewed ? ' (deleted by a managed sync; no live twin)' : ''}`);for (const p of selection.parked.filter(park => !park.retried)) console.log(` parked: ${p.source_id}/${p.slug} after ${p.failures} failures (${p.code ?? 'error'}); skipped unless --retry-parked`);for (const b of selection.blocked.filter(entry => entry.code === 'writer_not_active')) console.log(` waiting: ${b.source_id}/${b.slug}: ${b.reason}`);return;@@ -75,7 +77,7 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voi}return;}- const authorized = await consentGate(purgeConsentRequest(selection.count, olderThanHours, json, args, retryParked, retried), { json });+ const authorized = await consentGate(purgeConsentRequest(selection.count, olderThanHours, json, args, retryParked, retried, selection.sync_unreviewed), { json });if (!authorized) return;const result = await purgeDeletedPagesCoordinated(engine, olderThanHours, { retryParked });diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 4b2b76ba7a..031341b952 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -76,6 +76,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i[--keep prior|disk|withdrawn --apply --expect <preview-hash> --yes] [--json]gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]gbrain repair legacy-twins --source <id> [--apply --expect <preview-hash> --yes] [--json]+ gbrain repair uncommitted-deletions --source <id> [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]gbrain repair url-clone-fences [--source <id>] [--apply --expect <preview-hash> --yes] [--json]gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close][--apply --expect <preview-hash> --yes]] [--json]@@ -133,7 +134,7 @@ Options:withdrawn is a withdrawal-mirror effect's only choice).--request-id <uuid>stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).- --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences --apply: the user agreed+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, legacy-twins, rename-identity, url-clone-fences, uncommitted-deletions --apply: the user agreedto the previewed changes (destructive consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).--json Machine-readable output with a stable shape (frontmatter: every per-file diff).@@ -145,6 +146,7 @@ Held files (the content lane, then the two-pass frontmatter repair): docs/guidesMalformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.+Pages a sync soft-deleted although Git never held their file (restore before the purge; purged pages need a backup): docs/guides/repair.md#uncommitted-deletions.A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/guides/repair.md#url-clone-fences.Renames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 5b8af25fdf..b2a0c43eee 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1698,7 +1698,8 @@ async function runPhaseEmbed(engine: BrainEngine, dryRun: boolean, signal?: Abor* v0.26.5 — purge phase. Hard-deletes:* - source rows where `archived = true AND archive_expires_at <= now()`* (paired with the cascade FK to `pages`, this also drops the source's pages)- * - page rows where `deleted_at` is older than 72h+ * - page rows where `deleted_at` is older than `purge.retention_hours` (default 72h), except+ * managed sync tombstones with no live twin (#7130), which wait for `gbrain pages purge-deleted`** Cascade on `pages` covers `content_chunks`, `page_links`, `chunk_relations`.* `dryRun` short-circuits — no DELETEs are issued.@@ -1753,13 +1754,15 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phasdetails: { dry_run: true, purged_sources_count: 0, purged_pages_count: 0, purged_orphan_clones_count: 0 },};}- const [{ purgeExpiredSources }, { purgeDeletedPagesCoordinated, purgePhaseNote, purgePhaseStatus }] = await Promise.all([import('./destructive-guard.ts'), import('./persistence/purge-deleted.ts')]);+ const [{ purgeExpiredSources }, { purgeDeletedPagesCoordinated, purgePhaseNote, purgePhaseStatus }, { readPurgeRetentionHours }] = await Promise.all([import('./destructive-guard.ts'), import('./persistence/purge-deleted.ts'), import('./sync-reconcile.ts')]);// gbrain#4115: {purged, blocked} — a RESTRICT-FK-held source (revoked// oauth_client, v64) is reported and skipped instead of aborting the sweep.const purgeResult = await purgeExpiredSources(engine);const purgedSources = purgeResult.purged;- const purgedPages = await purgeDeletedPagesCoordinated(engine, SOFT_DELETE_TTL_HOURS_FOR_PURGE); // #5405: coordinated on managed brains- const purgedClones = await purgeOrphanClones(SOFT_DELETE_TTL_HOURS_FOR_PURGE);+ const retentionHours = await readPurgeRetentionHours(engine); // #7130: purge.retention_hours (default 72, at least 24)+ // #5405: coordinated on managed brains; #7130: `automatic` keeps managed sync tombstones with no live twin.+ const purgedPages = await purgeDeletedPagesCoordinated(engine, retentionHours, { automatic: true });+ const purgedClones = await purgeOrphanClones(retentionHours);// v0.36+ folded scope item +C: GC stale op_checkpoints rows.// 7-day TTL is deliberately generous; any reasonable long-running op// finishes inside that window. Cheap (few KB per row).@@ -1846,10 +1849,6 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas}}-/** v0.26.5: matches SOFT_DELETE_TTL_HOURS in destructive-guard.ts. Inlined here- * to avoid a static import (purge phase is only loaded in the autopilot path). */-const SOFT_DELETE_TTL_HOURS_FOR_PURGE = 72;-async function runPhaseOrphans(engine: BrainEngine, sourceId?: string): Promise<PhaseResult> {try {const { findOrphans } = await import('../commands/orphans.ts');diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 765cfee9b0..1978e56dff 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -211,6 +211,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['rename_identity_downgrades',// #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',+ // #7130: soft-deleted pages a managed sync removed although Git never held their file (doctor/checks/uncommitted-sync-deletions.ts).+ 'uncommitted_sync_deletions',// #6865: committed files of a managed Git source with no page and no hold, from the stored detector result (doctor/checks/unindexed-files.ts).'unindexed_files',// #6712: live pages whose database-only edit an incremental sync overwrote without a hold (doctor/checks/overwritten-edits.ts).diff --git a/src/core/ghost-pages.ts b/src/core/ghost-pages.tsindex 5024f0b4fa..2ffb1ae9ce 100644--- a/src/core/ghost-pages.ts+++ b/src/core/ghost-pages.ts@@ -97,12 +97,12 @@ export const GHOST_SCAN_LIMIT = 250_000;const BATCH = 10_000;interface PageRow { id: number; slug: string; source_path: string | null; source_uri: string | null }-type SourceContext = { ok: true; root: string; owner: GhostOwner; mode: Awaited<ReturnType<typeof scannerSlugRootMode>>; gitScope: string[] | null }+export type SourceContext = { ok: true; root: string; owner: GhostOwner; mode: Awaited<ReturnType<typeof scannerSlugRootMode>>; gitScope: string[] | null }| { ok: false; status: 'unknown' | 'not_applicable'; reason: string };const missing = (error: unknown) => ['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException)?.code ?? '');-async function sourceContext(engine: BrainEngine, sourceId: string): Promise<SourceContext> {+export async function sourceContext(engine: BrainEngine, sourceId: string): Promise<SourceContext> {const hostId = existingLocalHostId();const binding = await getWorktreeBinding(engine, sourceId, hostId);if (!binding) return { ok: false, status: 'not_applicable', reason: 'not_applicable' };@@ -121,7 +121,7 @@ async function sourceContext(engine: BrainEngine, sourceId: string): Promise<Sou}/** The path `prepareFileTarget` compares, resolved the same way (recorded source path, captured file URI, then the slug path). */-function canonicalPath(context: Extract<SourceContext, { ok: true }>, page: Pick<PageRow, 'slug' | 'source_path' | 'source_uri'>): string {+export function canonicalPath(context: Extract<SourceContext, { ok: true }>, page: Pick<PageRow, 'slug' | 'source_path' | 'source_uri'>): string {const captured = recordedPathFromFileUri(page.source_uri, context.root);return resolveSourceLocalFilePath(context.root, page.source_path, page.slug, page.source_path ? context.mode : undefined, context.gitScope)?? (captured ? join(context.root, captured) : join(context.root, `${page.slug}.md`));diff --git a/src/core/minions/handlers/purge.ts b/src/core/minions/handlers/purge.tsindex d7f1375926..ff44681274 100644--- a/src/core/minions/handlers/purge.ts+++ b/src/core/minions/handlers/purge.ts@@ -9,14 +9,15 @@ export function makePurgeHandler(engine: BrainEngine): MinionHandler {const scope = (typeof job.data.scope === 'string' && ['pages', 'sources', 'all'].includes(job.data.scope))? (job.data.scope as 'pages' | 'sources' | 'all'): 'all';- const olderThanHours = typeof job.data.olderThanHours === 'number' ? job.data.olderThanHours : 72;+ const olderThanHours = typeof job.data.olderThanHours === 'number' ? job.data.olderThanHours : await (await import('../../sync-reconcile.ts')).readPurgeRetentionHours(engine);const dryRun = !!job.data.dryRun;let pagesPurged = 0;let pagesBlocked: Array<{ source_id: string; slug: string; reason: string }> = [];let pagesError: string | undefined;let sourcesPurged: string[] = [];if (scope === 'pages' || scope === 'all') {- const result = await (await import('../../persistence/purge-deleted.ts')).purgeDeletedPagesCoordinated(engine, olderThanHours);+ // #7130: the job runs without consent, so it keeps managed sync tombstones with no live twin, like the cycle phase.+ const result = await (await import('../../persistence/purge-deleted.ts')).purgeDeletedPagesCoordinated(engine, olderThanHours, { automatic: true });pagesPurged = result.count; pagesBlocked = result.blocked; pagesError = result.error?.message;}let sourcesBlocked: Array<{ id: string; reason: string }> = [];diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.tsindex 0bc9b7ac56..064a593615 100644--- a/src/core/op-checkpoint.ts+++ b/src/core/op-checkpoint.ts@@ -5,6 +5,7 @@ import { FENCE_REPAIR_ATTEMPT_OP } from './fence-repair/attempts.ts';import { FENCE_CANDIDATE_OP, FENCE_SCAN_OP } from './fence-repair/census-store.ts';import { FENCE_UNCOMMITTED_OP } from './fence-repair/uncommitted.ts';import { SYNC_PASS_ROW_OPS } from './persistence/sync-pass-row.ts';+import { SYNC_DELETE_TOMBSTONE_OP } from './persistence/sync-delete-tombstones.ts';/** Max paths per append-INSERT round-trip; bounds the param-array size. */const APPEND_CHUNK = 1000;@@ -499,7 +500,8 @@ export function syncFingerprint(p: { sourceId?: string; lastCommit: string }): s* resolution audit entries never expire (#5988, #6650); a managed purge's* tombstone failure records and parks (#6741, purge-parks.ts) leave only with* their tombstone, its purge or a rearm; an open #6729 rename-identity downgrade- * record stays until its pair is settled or its old page is restored or purged.+ * record stays until its pair is settled or its old page is restored or purged, and a #7130 managed sync+ * deletion record while its tombstone (same page id and deleted_at) exists.*/export async function purgeStaleCheckpoints(engine: BrainEngine,@@ -517,6 +519,8 @@ export async function purgeStaleCheckpoints(AND op<>'connector-hold-retry'AND op<>'stuck-recovery-resolution'AND op<>'sync-admission'+ AND NOT (op='${SYNC_DELETE_TOMBSTONE_OP}' AND EXISTS (+ SELECT 1 FROM pages p WHERE p.id::text=op_checkpoints.fingerprint AND p.deleted_at=(op_checkpoints.completed_keys->0->>'deleted_at')::timestamptz))AND op<>'purge-deleted-park'AND NOT (op='sync-identity-downgrade' AND completed_keys->0->>'disposition' IS NULL AND EXISTS (SELECT 1 FROM pages p WHERE p.id::text=op_checkpoints.fingerprint AND p.deleted_at=(op_checkpoints.completed_keys->0->>'old_deleted_at')::timestamptz))diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 4115925496..82857cdf72 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -9,7 +9,7 @@ export interface WriteAuthority {remote: boolean;/** Original page-visibility ceiling; current policy can only narrow it. */excludePrivate?: boolean;- databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore';+ databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached';autoLinkTrusted?: boolean;restrictedNamespace?: boolean;sourceId: string;diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 23e85cb6dd..0ead1145de 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -214,7 +214,7 @@ const OWNER_FILE_INTENTS: ReadonlySet<string> = new Set(['managed_file_import',export interface PageBatchMember { id: string; index: number; size: number; requestId: string; repeats?: number[] }export async function submitPageMutation(ctx: OperationContext,- input: { operation: string; params: Record<string, unknown>; waitMs?: number; managedFileImport?: true; timelineSection?: TimelineSection; databaseOnly?: 'overwrite_restore';+ input: { operation: string; params: Record<string, unknown>; waitMs?: number; managedFileImport?: true; timelineSection?: TimelineSection; databaseOnly?: 'overwrite_restore' | 'detached';/** commit_page_upload: `params.body_ref` names the caller's sealed upload session (persistence/page-upload.ts). */stagedBody?: true }): Promise<Record<string, unknown>> {assertPersistenceAccepting(ctx.engine);@@ -254,7 +254,7 @@ export async function submitPageMutation(ctx: OperationContext,export async function preparePageAdmission(ctx: OperationContext,input: { operation: string; params: Record<string, unknown>; managedFileImport?: true; batch?: PageBatchMember; timelineSection?: TimelineSection;/** #6712 `repair overwritten-edits`: publish to the database only, so the restore never rewrites the committed file. */- databaseOnly?: 'overwrite_restore'; stagedBody?: true }+ databaseOnly?: 'overwrite_restore' | 'detached'; stagedBody?: true }): Promise<{ prior: WriteRequest; admission?: undefined; typeWarning?: undefined; slugAdvisory?: undefined } | { prior?: undefined; admission: WriteAdmission; typeWarning: PageTypeWarning | null; slugAdvisory: string | null }> {if (input.operation === 'put_page' && ['kind', 'preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {if (ctx.remote !== false || input.managedFileImport !== true || !OWNER_FILE_INTENTS.has(String(input.params.kind)) ||diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 70b8c614c6..4c858e57d1 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'uncommitted-deletions';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex bd8255e6d9..04c3f2deda 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -16,6 +16,7 @@ import { atomRetirementPurgeHold } from './atom-retirement-hold.ts';import { writerOnboardingPreflight } from './onboarding.ts';import { clearPurgePark, notePurgeSourceWriter, PURGE_PARK_LIMIT, purgeParkKey, prunePurgeParks, readPurgeParks, recordPurgeFailure, type PurgePark } from './purge-parks.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';+import { readUnreviewedSyncTombstones, syncDeleteHeld } from './sync-delete-tombstones.ts';/** A tombstone that moved under a concurrent writer; the next run retries it. */const DEFERRAL_CODES = new Set(['revision_conflict', 'page_not_found', 'page_identity_changed']);@@ -38,6 +39,8 @@ export interface DeletedPagePurge {* `write_capacity_deferred`); the next run submits them. Never a failure and never a park.*/capacity_deferred: number;+ /** #7130: managed sync tombstones with no live twin an automatic purge kept (in `blocked`, code `sync_delete_unreviewed`). */+ held: number;/** Present when `failed > 0`, so the caller cannot report success. */error?: { class: string; code: string; message: string };}@@ -47,17 +50,18 @@ export interface DeletedPagePurge {* `gbrain pages purge-deleted` and by the `purge_deleted_pages` op (reached* through `gbrain call`), so no manual entry point purges without it. The* approved command is always the gated `pages purge-deleted --yes`. The- * autopilot purge phase calls `purgeDeletedPagesCoordinated` directly.+ * autopilot purge phase calls `purgeDeletedPagesCoordinated` directly, with `automatic` (#7130).*/-export function purgeConsentRequest(count: number, olderThanHours: number, json: boolean, args: readonly string[], retryParked = false, parked = 0): ConsentRequest {+export function purgeConsentRequest(count: number, olderThanHours: number, json: boolean, args: readonly string[], retryParked = false, parked = 0, syncUnreviewed = 0): ConsentRequest {const retry = retryParked ? ['--retry-parked'] : [];const retried = retryParked && parked > 0 ? `, including ${parked} parked page(s) retried once more` : '';+ const sync = syncUnreviewed > 0 ? `; ${syncUnreviewed} of them were deleted by a managed sync, not a person, and no live page has their content` : '';return {command: 'pages purge-deleted', effects: ['destructive'], actor: 'agent',- what: `Permanently purge ${count} soft-deleted page(s)${retried}`,+ what: `Permanently purge ${count} soft-deleted page(s)${retried}${sync}`,why: 'A hard purge removes soft-deleted pages, their chunks and links, from every source of this brain.',- risk: 'Purged pages cannot be restored with `gbrain restore`.',- user_message: `Permanently delete ${count} page(s) soft-deleted more than ${olderThanHours}h ago${retried}, across every source in this brain? They cannot be restored afterwards.`,+ risk: 'Purged pages cannot be restored with `gbrain restore`; they can only come back from a backup.',+ user_message: `Permanently delete ${count} page(s) soft-deleted more than ${olderThanHours}h ago${retried}, across every source in this brain${sync}? They cannot be restored afterwards; only a backup brings them back.`,argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, ...retry, ...(json ? ['--json'] : []), '--yes'],preview_argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, ...retry, '--dry-run', '--json'],args,@@ -68,7 +72,7 @@ export function purgeConsentRequest(count: number, olderThanHours: number, json:export async function consentedPurgeDeletedPages(engine: BrainEngine, olderThanHours: number, yes: boolean) {const preview = await selectPurgeCandidates(engine, olderThanHours);if (preview.count === 0) return { status: 'purged', count: 0, slugs: [] };- await requireConsent(purgeConsentRequest(preview.count, olderThanHours, false, yes ? ['--yes'] : []));+ await requireConsent(purgeConsentRequest(preview.count, olderThanHours, false, yes ? ['--yes'] : [], false, 0, preview.sync_unreviewed));const result = await purgeDeletedPagesCoordinated(engine, olderThanHours);return { status: result.failed ? 'partial' : 'purged', count: result.count, slugs: result.slugs, ...(result.blocked.length ? { blocked: result.blocked } : {}) };}@@ -105,13 +109,14 @@ interface RecordedExpiry { slugs: string[]; exclude: number[]; blocked: DeletedP* delete (`exclude`). A content failure counts toward the shared purge park (purge-parks.ts), so after* PURGE_PARK_LIMIT failures it is parked and skipped, like the managed purge's; a transient one is retried next run.*/-async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: number, retryParked: boolean): Promise<RecordedExpiry> {+async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: number, retryParked: boolean, held: ReadonlySet<number>): Promise<RecordedExpiry> {const hours = String(Math.max(0, Math.floor(olderThanHours)));await prunePurgeParks(engine);const run = new ItemRun('purge.recorded_tombstones');const out: RecordedExpiry = { slugs: [], exclude: [], blocked: [], failed: 0, parked: 0 };const failures: Array<{ row: RecordedTombstone; failure: ItemFailure }> = [];for (const row of await recordedTombstones(engine, hours)) {+ if (held.has(row.id)) continue;if (row.park && row.park.failures >= PURGE_PARK_LIMIT && !retryParked) {out.parked++;out.exclude.push(row.id);@@ -151,7 +156,7 @@ async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: num}/** One expired tombstone a managed purge submits, in scan order; `park` is its live failure record, if any. */-export interface PurgeCandidate { source_id: string; slug: string; cutoff: string; deleted_us: string; key: string; park?: PurgePark }+export interface PurgeCandidate { source_id: string; slug: string; cutoff: string; deleted_us: string; key: string; park?: PurgePark; sync_unreviewed?: true }/*** #6741 C: what a purge with these options would do, read-only. The one eligibility selector behind the@@ -173,31 +178,41 @@ export interface PurgeSelection {/** Every parked tombstone the cutoff selects; `retried` when `retryParked` puts it back among the candidates. */parked: Array<{ source_id: string; slug: string; failures: number; code: string | null; retried: boolean }>;inactive: number;+ /** #7130 `automatic`: managed sync tombstones with no live twin kept out of the candidates (in `blocked`, code `sync_delete_unreviewed`). */+ held: number;+ /** #7130: how many candidates are managed sync tombstones with no live twin (the manual preview and consent name them). */+ sync_unreviewed: number;/** Per source in the scan: whether its writer passed the owner verification (the park rearm reads it). */writers: Record<string, boolean>;}-export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean } = {}): Promise<PurgeSelection> {+export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean } = {}): Promise<PurgeSelection> {if (!await managedPersistenceEnabled(engine)) {const parked = (await recordedTombstones(engine, String(Math.max(0, Math.floor(olderThanHours))))).filter((row): row is RecordedTombstone & { park: PurgePark } => !!row.park && row.park.failures >= PURGE_PARK_LIMIT);- const preview = await engine.purgeDeletedPages(olderThanHours, { dryRun: true, ...(opts.retryParked ? {} : { excludeIds: parked.map(row => row.id) }) });+ const skipped = new Set(opts.retryParked ? [] : parked.map(row => row.id));+ const unreviewed = (await readUnreviewedSyncTombstones(engine, olderThanHours)).filter(row => !skipped.has(row.id));+ const kept = opts.automatic ? unreviewed : [];+ const preview = await engine.purgeDeletedPages(olderThanHours, { dryRun: true, excludeIds: [...skipped, ...kept.map(row => row.id)] });+ const held = kept.filter(row => row.expired);return { managed: false, count: preview.count, slugs: preview.slugs, pages: preview.pages, candidates: [],- blocked: opts.retryParked ? [] : parked.map(row => ({ source_id: row.source_id, slug: row.slug, code: 'purge_parked', reason: parkedReason(row.park) })),+ blocked: [...(opts.retryParked ? [] : parked.map(row => ({ source_id: row.source_id, slug: row.slug, code: 'purge_parked', reason: parkedReason(row.park) }))),+ ...held.map(row => syncDeleteHeld(row, olderThanHours))],parked: parked.map(row => ({ source_id: row.source_id, slug: row.slug, failures: row.park.failures, code: row.park.code, retried: opts.retryParked === true })),- inactive: 0, writers: {} };+ inactive: 0, held: held.length, sync_unreviewed: opts.automatic ? 0 : unreviewed.filter(row => row.expired).length, writers: {} };}const hours = Math.max(0, Math.floor(olderThanHours));- const rows = await engine.executeRaw<{ source_id: string; slug: string; cutoff: string; deleted_us: string }>(- `SELECT p.source_id, p.slug, (now() - ($1 || ' hours')::interval)::text AS cutoff,+ const rows = await engine.executeRaw<{ id: number | string; source_id: string; slug: string; cutoff: string; deleted_us: string }>(+ `SELECT p.id, p.source_id, p.slug, (now() - ($1 || ' hours')::interval)::text AS cutoff,floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text AS deleted_us FROM pages p JOIN sources s ON s.id = p.source_idWHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived AND ${identityDowngradePurgeHold('p')} AND ${atomRetirementPurgeHold('p')}ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [String(hours)]);const states = new Map<string, { state: string; physical_error?: string }>();if (rows.length) for (const source of (await writerOnboardingPreflight(engine)).sources) states.set(source.source_id, source);const parks = rows.length ? await readPurgeParks(engine) : new Map<string, PurgePark>();- const selection: PurgeSelection = { managed: true, count: 0, slugs: [], candidates: [], blocked: [], parked: [], inactive: 0, writers: {} };- for (const row of rows) {+ const unreviewed = new Set(rows.length ? (await readUnreviewedSyncTombstones(engine, hours)).map(row => row.id) : []);+ const selection: PurgeSelection = { managed: true, count: 0, slugs: [], candidates: [], blocked: [], parked: [], inactive: 0, held: 0, sync_unreviewed: 0, writers: {} };+ for (const { id, ...row } of rows) {const writer = states.get(row.source_id);const active = writer?.state !== 'recovery_required';selection.writers[row.source_id] = active;@@ -207,6 +222,12 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours:reason: `Source ${row.source_id}'s writer is ${writer!.state}${writer!.physical_error ? ` (${writer!.physical_error})` : ''}, so the purge submitted nothing; it resumes once gbrain sources writer status --source ${row.source_id} shows the writer ready.` });continue;}+ const syncUnreviewed = unreviewed.has(Number(id));+ if (syncUnreviewed && opts.automatic) {+ selection.held++;+ selection.blocked.push(syncDeleteHeld(row, hours));+ continue;+ }const key = purgeParkKey(row.source_id, row.slug, row.deleted_us);// A record marked while the writer was not active is dropped by this run (the rearm), so it does not count here.const park = parks.get(key)?.inactive_seen ? undefined : parks.get(key);@@ -217,7 +238,8 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours:continue;}}- selection.candidates.push({ ...row, key, ...(park ? { park } : {}) });+ if (syncUnreviewed) selection.sync_unreviewed++;+ selection.candidates.push({ ...row, key, ...(park ? { park } : {}), ...(syncUnreviewed ? { sync_unreviewed: true as const } : {}) });}selection.count = selection.candidates.length;selection.slugs = selection.candidates.map(candidate => candidate.slug);@@ -229,14 +251,15 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours:* and so does an unmanaged recorded tombstone whose delete failed (GBRA-130 A-49: `failed` without `error`).*/export function purgePhaseStatus(result: DeletedPagePurge): 'ok' | 'warn' | 'fail' {- return result.error ? 'fail' : result.inactive || result.parked || result.capacity_deferred || result.failed ? 'warn' : 'ok';+ return result.error ? 'fail' : result.inactive || result.parked || result.capacity_deferred || result.failed || result.held ? 'warn' : 'ok';}/** The purge phase summary's note on the pages it did not submit (empty when there are none). */export function purgePhaseNote(result: DeletedPagePurge): string {const parts = [result.inactive ? `${result.inactive} waiting on a writer in recovery` : '', !result.error && result.failed ? `${result.failed} failed (see details)` : '',result.parked ? `${result.parked} parked (gbrain doctor: purge_parked_pages)` : '',- result.capacity_deferred ? `${result.capacity_deferred} deferred to the next run (write capacity in use)` : ''].filter(Boolean);+ result.capacity_deferred ? `${result.capacity_deferred} deferred to the next run (write capacity in use)` : '',+ result.held ? `${result.held} deleted by a managed sync held for review (gbrain pages purge-deleted --dry-run; purge with --yes or restore each)` : ''].filter(Boolean);return parts.length ? ` (${parts.join(', ')})` : '';}@@ -258,13 +281,21 @@ export function purgePhaseNote(result: DeletedPagePurge): string {* (at the background pause line for a background run), so a large backlog* no longer turns into thousands of `queue_capacity` failures and parks* ahead of interactive writes; the rest is `capacity_deferred` to the next run.+ *+ * #7130: `automatic` (the cycle purge phase and the `purge` job, which run without consent) keeps every tombstone a+ * managed sync made unless a live page of its source has the same content (sync-delete-tombstones.ts); it is+ * reported `held` (code `sync_delete_unreviewed`). The consented manual purge leaves `automatic` unset.*/-export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean } = {}): Promise<DeletedPagePurge> {+export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean } = {}): Promise<DeletedPagePurge> {if (!await managedPersistenceEnabled(engine)) {- const recorded = await expireRecordedTombstones(engine, olderThanHours, opts.retryParked === true);- const result = await engine.purgeDeletedPages(olderThanHours, recorded.exclude.length ? { excludeIds: recorded.exclude } : undefined);- return { slugs: [...recorded.slugs, ...result.slugs], count: recorded.slugs.length + result.count, blocked: recorded.blocked, deferred: 0,- failed: recorded.failed, inactive: 0, parked: recorded.parked, capacity_deferred: 0 };+ // #7130: a brain deactivated after managed syncs keeps their tombstones' records and receipts, so the hold applies here too.+ const kept = opts.automatic ? await readUnreviewedSyncTombstones(engine, olderThanHours) : [];+ const recorded = await expireRecordedTombstones(engine, olderThanHours, opts.retryParked === true, new Set(kept.map(row => row.id)));+ const exclude = [...recorded.exclude, ...kept.map(row => row.id)];+ const result = await engine.purgeDeletedPages(olderThanHours, exclude.length ? { excludeIds: exclude } : undefined);+ const held = kept.filter(row => row.expired);+ return { slugs: [...recorded.slugs, ...result.slugs], count: recorded.slugs.length + result.count, blocked: [...recorded.blocked, ...held.map(row => syncDeleteHeld(row, olderThanHours))],+ deferred: 0, failed: recorded.failed, inactive: 0, parked: recorded.parked, capacity_deferred: 0, held: held.length };}const selection = await selectPurgeCandidates(engine, olderThanHours, opts);for (const [sourceId, active] of Object.entries(selection.writers)) await notePurgeSourceWriter(engine, sourceId, active);@@ -306,10 +337,10 @@ export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThablocked.push({ source_id: row.source_id, slug: row.slug, code, reason });}}- const failures = blocked.filter(b => !b.code || !DEFERRAL_CODES.has(b.code) && b.code !== 'writer_not_active' && b.code !== 'purge_parked' && b.code !== 'write_capacity_deferred');+ const failures = blocked.filter(b => !b.code || !DEFERRAL_CODES.has(b.code) && b.code !== 'writer_not_active' && b.code !== 'purge_parked' && b.code !== 'write_capacity_deferred' && b.code !== 'sync_delete_unreviewed');const error = failed > 0 ? { class: 'ManagedPurgeFailed', code: 'managed_purge_failed',message: `${failed} expired page(s) could not be purged through the coordinator: ${failures.slice(0, 3).map(b => `${b.source_id}/${b.slug}: ${b.reason}`).join('; ')}` } : undefined;const parked = selection.parked.filter(park => !park.retried).length;- return { slugs, count: slugs.length, blocked, deferred, failed, inactive: selection.inactive, parked, capacity_deferred: capacityDeferred, ...(error ? { error } : {}) };+ return { slugs, count: slugs.length, blocked, deferred, failed, inactive: selection.inactive, parked, capacity_deferred: capacityDeferred, held: selection.held, ...(error ? { error } : {}) };}diff --git a/src/core/persistence/sync-delete-tombstones.ts b/src/core/persistence/sync-delete-tombstones.tsnew file mode 100644index 0000000000..91b2bd4ed5--- /dev/null+++ b/src/core/persistence/sync-delete-tombstones.ts@@ -0,0 +1,60 @@+/**+ * #7130: a managed sync deletion is a machine's inference that a file is gone, not a person's decision, so its+ * tombstone must not turn into a hard delete without review. Each `managed_sync_delete` apply records the tombstone it+ * made, in the same transaction: one `op_checkpoints` row per page (op `sync-delete-tombstone`, fingerprint = the page+ * id), `completed_keys[0]` holding the record. A record is open while its page is still soft-deleted at the recorded+ * `deleted_at`; a restore, a purge or a later delete of the restored page closes it, and only then may the checkpoint+ * sweep (purgeStaleCheckpoints) drop it.+ *+ * The automatic purges (the cycle purge phase and the `purge` job) leave such a tombstone alone unless another live+ * page of its source holds the same content (a live twin); the consented `gbrain pages purge-deleted` purges it and+ * says how many of its set these are. A tombstone made before records existed is recognized by its uncompacted+ * committed `managed_sync_delete` receipt; once that receipt is compacted it is no longer recognized.+ */+import type { BrainEngine } from '../engine.ts';++export const SYNC_DELETE_TOMBSTONE_OP = 'sync-delete-tombstone';++/**+ * Records the tombstone this transaction's soft delete made (`deleted_at = now()`, so it equals the page row's), after+ * `softDeletePage`. A page not soft-deleted by this transaction records nothing.+ */+export async function recordSyncDeleteTombstone(tx: Pick<BrainEngine, 'executeRaw'>,+ row: { source_id: string; source_incarnation: string; slug: string; request_id: string }, p: { passId?: string; runId?: string }): Promise<void> {+ await tx.executeRaw(`INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at)+ SELECT $1, p.id::text, jsonb_build_array(jsonb_build_object('source_id', p.source_id, 'incarnation', $2::text, 'page_id', p.id, 'slug', p.slug,+ 'source_path', p.source_path, 'pass_id', $3::text, 'run_id', $4::text, 'request_id', $5::text, 'deleted_at', p.deleted_at)), now()+ FROM pages p WHERE p.source_id = $6 AND p.slug = $7 AND p.deleted_at = now()+ ON CONFLICT (op, fingerprint) DO UPDATE SET completed_keys = EXCLUDED.completed_keys, updated_at = now()`,+ [SYNC_DELETE_TOMBSTONE_OP, row.source_incarnation, p.passId ?? null, p.runId ?? null, row.request_id, row.source_id, row.slug]);+}++/**+ * SQL: the tombstone `alias` (a soft-deleted `pages` row) was made by a managed sync deletion: its open record, or the+ * uncompacted committed `managed_sync_delete` receipt that deleted it (completed at or after its `deleted_at`).+ */+export const syncDeleteOrigin = (alias: string): string => `(EXISTS (SELECT 1 FROM op_checkpoints sdt WHERE sdt.op = '${SYNC_DELETE_TOMBSTONE_OP}'+ AND sdt.fingerprint = ${alias}.id::text AND ${alias}.deleted_at = (sdt.completed_keys->0->>'deleted_at')::timestamptz)+ OR EXISTS (SELECT 1 FROM persistence_requests sdr WHERE sdr.source_id = ${alias}.source_id AND sdr.slug = ${alias}.slug AND sdr.page_id = ${alias}.id+ AND sdr.intent IS NOT NULL AND NOT sdr.compacted AND sdr.state = 'committed' AND sdr.intent->>'kind' = 'managed_sync_delete'+ AND sdr.completed_at >= ${alias}.deleted_at))`;++/**+ * Every tombstone a managed sync made whose content no live page of its source holds (`expired`: older than the cutoff),+ * whatever its age, so a purge that excludes them cannot race a tombstone across its cutoff.+ */+export async function readUnreviewedSyncTombstones(engine: Pick<BrainEngine, 'executeRaw'>, olderThanHours: number):+ Promise<Array<{ id: number; source_id: string; slug: string; expired: boolean }>> {+ const rows = await engine.executeRaw<{ id: number | string; source_id: string; slug: string; expired: boolean }>(+ `SELECT p.id, p.source_id, p.slug, p.deleted_at < now() - ($1 || ' hours')::interval AS expired FROM pages p+ WHERE p.deleted_at IS NOT NULL AND ${syncDeleteOrigin('p')}+ AND NOT EXISTS (SELECT 1 FROM pages tw WHERE tw.source_id = p.source_id AND tw.deleted_at IS NULL AND tw.content_hash = p.content_hash)+ ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [String(Math.max(0, Math.floor(olderThanHours)))]);+ return rows.map(row => ({ ...row, id: Number(row.id) }));+}++/** The `blocked` entry of a tombstone an automatic purge keeps. */+export const syncDeleteHeld = (row: { source_id: string; slug: string }, olderThanHours: number) => ({ source_id: row.source_id, slug: row.slug,+ code: 'sync_delete_unreviewed', reason: `A managed sync deleted this page and no live page of ${row.source_id} has its content, so the automatic purge keeps it. `+ + `Restore it with gbrain restore ${row.slug} --source-id ${row.source_id} --force, or review the set with gbrain pages purge-deleted --older-than ${olderThanHours}h --dry-run `+ + 'and purge it with --yes; a purged page can only come back from a backup.' });diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex d113ad11c1..5b3b9f7f3b 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -61,6 +61,7 @@ import { addFencesNormalized, clearGitHold, clearGitHoldRetryPaths, countGitHoldimport { clearSyncSlice, writeSyncSlice, type SyncSliceState } from './sync-slices.ts';import { CHECKPOINT_MOVED_MESSAGE, emptySyncScope, pinnedSlugModeMismatch, slugModeMismatchCause } from './sync-slug-mode.ts';import { readPagePurgeTombstones } from './page-purge.ts';+import { recordSyncDeleteTombstone } from './sync-delete-tombstones.ts';import { fenceWhere } from '../fence-repair/refusal.ts';import { recordSyncRunTrend } from '../fence-repair/census-store.ts';import { fencesNormalizeEnabled } from '../fence-repair/config.ts';@@ -767,7 +768,10 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c}if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,trust: await ownerImportTrust(engine, row, snapshot?.page.frontmatter, p.sourcePath), validate, apply: async (tx, preimage) => {- if (snapshot && snapshot.page.deleted_at == null) { await tx.createVersion(row.slug, preimage ? { ...source, preimage } : source); await tx.softDeletePage(row.slug, source); }+ if (snapshot && snapshot.page.deleted_at == null) {+ await tx.createVersion(row.slug, preimage ? { ...source, preimage } : source); await tx.softDeletePage(row.slug, source);+ await recordSyncDeleteTombstone(tx, row, p); // #7130: the automatic purge holds this tombstone+ }await releaseHold(tx);return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };} };diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 830c7738df..10b3a669eb 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -49,7 +49,7 @@ import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';import { readFix } from '../ops/op-fix.ts';import { ItemRun, type ItemFailure } from '../item-failure.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex d7622113c7..20ef3a10f8 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -79,6 +79,7 @@ import { overwrittenEditsRepair } from './overwritten-edits.ts';import { missingTablesRepair } from './missing-tables.ts';import { urlCloneFencesRepair } from './url-clone-fences.ts';import { segmentedMirrorRepair } from './segmented-mirror.ts';+import { uncommittedDeletionsRepair, UNCOMMITTED_DELETIONS_CONSENT_TEXT } from './uncommitted-deletions.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -478,6 +479,17 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ '(file_database_drift) and never rewritten. Preview-bound and destructive: --apply --expect <hash> --yes re-checks each page and commits, per '+ 'page, one receipted request whose withdrawal-mirror and Git effects rewrite and commit the file. Runs only when named; never on upgrade.',},+ 'uncommitted-deletions': {+ handler: uncommittedDeletionsRepair, embeds: 'none', checks: ['uncommitted_sync_deletions'], explicit_only: true, preview_bound: true, consent: 'destructive',+ consentText: UNCOMMITTED_DELETIONS_CONSENT_TEXT,+ summary: 'Restore soft-deleted pages whose recorded file Git never held (.gitignore excludes it, or no commit holds it and it is not on the disk), which a managed '+ + 'sync deleted before #7130 because it read the absent file as a deletion. Needs --source; refused off the canonical owner host (not_owner_host). The preview '+ + 'lists each page (slug, recorded path, deletion time, evidence, whether a sync deleted it) and prints the apply command with its hash; pages another writer '+ + 'deleted are listed apart and join the set only with --include-ambiguous. --apply --expect <hash> --yes restores exactly that set, one coordinated '+ + 'restore_page with detach per page, published database-only: each comes back live, forgets its recorded file and no file is written, so the next sync '+ + 'never deletes it again. Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create) can bring them back. '+ + 'Runs only when named; never on upgrade.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --git a/src/core/repair/uncommitted-deletions.ts b/src/core/repair/uncommitted-deletions.tsnew file mode 100644index 0000000000..d5fe305e8f--- /dev/null+++ b/src/core/repair/uncommitted-deletions.ts@@ -0,0 +1,151 @@+/**+ * `gbrain repair uncommitted-deletions --source <id>` (#7130): restore soft-deleted pages whose recorded file Git never+ * held (`.gitignore` excludes it, or no commit holds it and it is not on the disk), which a managed sync deleted before+ * #7130 because it read the absent file as a deletion. Such a tombstone may hold the only copy of its page, and the+ * purge removes it for good after its retention window.+ *+ * Explicit-only, preview-bound and consented: the preview (`scanUncommittedDeletions`, on the source's canonical owner+ * host only, `not_owner_host` elsewhere) lists each page with its slug, recorded path, deletion time, evidence and who+ * deleted it, binds the set to the owner it ran under and saves it under its hash; the default set is the pages a sync+ * deleted, and `--include-ambiguous` adds the ones another writer deleted. `--apply --expect <hash> --yes` restores+ * exactly that set, one coordinated `restore_page` with `detach: true` per page, published database-only: the page+ * comes back live, forgets its recorded file (`database_only_reason='detached'`, `detached-pages.ts`) and no file is+ * written, so the next sync has no file to read as missing and never deletes it again. A page that changed since the+ * preview is skipped `changed_since_preview`; one whose file is back in the checkout is skipped `file_restored` (sync+ * reads it); one purged in between is skipped `purged`. Pages already purged cannot be restored by this command; only+ * a backup can bring them back. Never runs on upgrade or from a maintenance cycle.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { sourceContext, type GhostOwner } from '../ghost-pages.ts';+import { absentRecordedFile } from '../persistence/detached-pages.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { PURGED_NOTE, scanUncommittedDeletions, type UncommittedDeletion } from '../uncommitted-deletions.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++/** Pages one preview lists; a larger set is restored in rounds (preview, apply, preview again). */+export const UNCOMMITTED_DELETIONS_LIMIT = 1000;+/** Recorded files whose Git evidence one preview reads. */+const PATH_LIMIT = 5000;+const DOCS = 'docs/guides/repair.md#uncommitted-deletions';++export const uncommittedDeletionsPreviewCommand = (sourceId: string) => `gbrain repair uncommitted-deletions --source ${sourceId}`;+const previewFix = (sourceId: string) => readFix('Previews the restorable soft-deleted pages of the source again; writes nothing.',+ { argv: ['gbrain', 'repair', 'uncommitted-deletions', '--source', sourceId, '--json'] });++/** The consent payload of `--apply --expect <hash>` (registry `consentText`). */+export const UNCOMMITTED_DELETIONS_CONSENT_TEXT = {+ what: 'Restore the previewed soft-deleted pages whose recorded file Git never held, as database-only pages',+ why: 'The preview listed each page with its recorded path and the evidence that Git never committed that file (or .gitignore excludes it), so the tombstone may hold the only copy and the purge would remove it for good.',+ risk: 'Each page comes back live and detached: it forgets its recorded file path (database_only_reason=detached) and no file is written, so sync never deletes it again; a file put at that path later is not linked to it. '+ + `Undo one with gbrain delete <slug>. ${PURGED_NOTE}`,+ user_message: 'Restore the previewed pages that a sync deleted without Git evidence? They come back live as database-only pages; no file is written',+};++interface Selection { source_ids: string[]; include_ambiguous: boolean }+interface ApprovedDeletion extends UncommittedDeletion { owner: GhostOwner; selection: Selection }+interface DeletionItem extends RepairItem { page: UncommittedDeletion; hash: string; last: boolean }++const sameOwner = (a: GhostOwner | undefined, b: GhostOwner) => !!a && a.host_id === b.host_id && a.worktree_id === b.worktree_id+ && a.owner_epoch === b.owner_epoch && a.source_incarnation === b.source_incarnation;++function notOwnerHost(sourceId: string): OperationError {+ return opError('not_owner_host', `Soft-deleted pages of source ${sourceId} can only be checked and restored on its canonical owner host.`,+ `This host does not own source ${sourceId}'s active canonical worktree, so it cannot read whether Git ever held a page's file; nothing was listed or changed. Run ${uncommittedDeletionsPreviewCommand(sourceId)} in a terminal on the owner host (writer status names it).`,+ { fix: readFix('Shows the source\'s canonical binding and owner host, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }), docs: DOCS });+}++const hashParts = (scope: RepairScope, owner: GhostOwner | undefined, selection: Selection, pages: UncommittedDeletion[]) =>+ ({ kind: 'uncommitted-deletions-v1', brain_id: scope.brain_id, selection, owner: owner ?? null, pages });++const describeDeletion = (page: UncommittedDeletion) => `file ${page.source_path} ${page.evidence === 'ignored' ? 'is excluded by .gitignore' : 'was never committed'}; `+ + `deleted ${page.deleted_at} by ${page.deleted_by === 'sync' ? 'a managed sync' : 'another writer'}; revision ${page.revision}`;++function item(page: UncommittedDeletion, hash: string, last: boolean): DeletionItem {+ return { cursor: { phase: 1, id: page.page_id }, source_id: page.source_id, slug: page.slug, chars: 0, action: `restore_detached:${page.evidence}`, page, hash, last };+}++export const uncommittedDeletionsRepair: RepairHandler = {+ kind: 'uncommitted-deletions',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ if (scope.source_ids.length !== 1) {+ throw opError('invalid_params', 'gbrain repair uncommitted-deletions needs --source <id>.',+ 'Git evidence is read in each source\'s own checkout on its canonical owner host; name one source, e.g. gbrain repair uncommitted-deletions --source default.',+ { fix: readFix('Lists the registered sources.', { argv: ['gbrain', 'sources', 'list', '--json'] }), docs: DOCS });+ }+ const sourceId = scope.source_ids[0]!;+ const command = uncommittedDeletionsPreviewCommand(sourceId);+ const selection: Selection = { source_ids: scope.source_ids, include_ambiguous: opts?.includeAmbiguous === true };+ if (opts?.apply) {+ if (!opts.expect) {+ throw opError('invalid_params', 'gbrain repair uncommitted-deletions --apply restores only the set a preview printed.',+ `Preview first: ${command} — then, after the user agrees, run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`,+ { fix: previewFix(sourceId), docs: DOCS });+ }+ const context = await sourceContext(engine, sourceId);+ if (!context.ok && context.reason === 'not_owner_host') throw notOwnerHost(sourceId);+ const owner = context.ok ? context.owner : undefined;+ const approved = await loadApprovedSet<ApprovedDeletion>(engine, { command: 'uncommitted-deletions', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(hashParts(scope, owner, selection, [])) });+ if (approved.items.some(page => JSON.stringify(page.selection) !== JSON.stringify(selection) || !sameOwner(owner, page.owner))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map(({ selection: _selection, owner: _owner, ...page }, index) => item(page, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ }+ const scan = await scanUncommittedDeletions(engine, sourceId, { pathLimit: PATH_LIMIT });+ if (scan.reason === 'not_owner_host') throw notOwnerHost(sourceId);+ const eligible = scan.pages.filter(page => selection.include_ambiguous || page.deleted_by === 'sync');+ const selected = eligible.slice(0, UNCOMMITTED_DELETIONS_LIMIT);+ const excluded = scan.pages.filter(page => !selection.include_ambiguous && page.deleted_by !== 'sync');+ const hash = previewHash(hashParts(scope, scan.owner, selection, selected));+ if (selected.length) await saveApprovedSet<ApprovedDeletion>(engine, { command: 'uncommitted-deletions', hash }, selected.map(page => ({ ...page, owner: scan.owner!, selection })));+ const warnings = [+ PURGED_NOTE,+ ...(scan.status !== 'known' ? [`Source ${sourceId} was not checked (${scan.reason}): ${scan.reason === 'not_managed' ? 'this brain has no managed sync, which is what deleted these pages'+ : scan.reason === 'mirror_read_only' ? 'a read-only mirror publishes no file' : 'its checkout or Git history could not be read on this host'}; nothing is listed.`] : []),+ ...(scan.unknown ? [`${scan.unknown} soft-deleted page(s) are not listed because Git could not answer for their file; fix the checkout and preview again.`] : []),+ ...(excluded.length ? [`${excluded.length} more soft-deleted page(s) with an uncommitted file were deleted by another writer, not by a sync; they are listed apart and restored only with --include-ambiguous.`] : []),+ ...(scan.truncated || eligible.length > selected.length ? [`More soft-deleted pages may qualify past this bounded preview; apply this set, then preview again.`] : []),+ ];+ return { warnings, items: selected.map((page, index) => item(page, hash, index === selected.length - 1)), preview_hash: hash,+ residuals: { tombstones: scan.tombstones, checked: scan.checked, committed: scan.committed, file_present: scan.file_present, unknown: scan.unknown, ...(excluded.length ? { deleted_by_other: excluded.length } : {}) },+ listing: [...selected.map(page => ({ item: `${page.source_id}:${page.slug}`, class: `restore:${page.evidence}`, detail: describeDeletion(page) })),+ ...excluded.map(page => ({ item: `${page.source_id}:${page.slug}`, class: 'excluded:deleted_by_other', detail: `${describeDeletion(page)}; restored only with --include-ambiguous` }))],+ details: { pages: selected.map(({ source_id, slug, source_path, deleted_at, evidence, deleted_by }) => ({ source_id, slug, source_path, deleted_at, evidence, deleted_by })),+ purged: PURGED_NOTE, undo: 'gbrain delete <slug>', truncated: scan.truncated, docs: DOCS } };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { page, hash, last } = entry as DeletionItem;+ const outcome = await restoreDeletion(ctx, page);+ if (last) await clearApprovedSet(ctx.engine, { command: 'uncommitted-deletions', hash });+ return outcome;+ },+ render(details) {+ return [` each restored page: live, database-only (detached), no file written; undo per slug: ${details.undo}; guide: ${details.docs}`, ` ${details.purged}`];+ },+};++const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });++/** Restores one approved tombstone database-only (`restore_page` with `detach`), after checking it is still the previewed one. */+async function restoreDeletion(ctx: OperationContext, page: UncommittedDeletion): Promise<RepairItemOutcome> {+ const engine: BrainEngine = ctx.engine;+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id, includeDeleted: true });+ if (!snapshot) return { applied: false, outcome: 'purged', reason: `${page.slug} was purged after the preview. ${PURGED_NOTE}` };+ if (Number(snapshot.page.id) !== page.page_id || snapshot.revision !== page.revision || snapshot.page.source_path !== page.source_path) return changed('the page or its recorded file changed since the preview');+ if (!snapshot.page.deleted_at) return { applied: false, outcome: 'already_live' };+ if (!await absentRecordedFile(engine, page.source_id, snapshot.page)) {+ return { applied: false, outcome: 'file_restored', reason: `${page.source_path} is in the checkout again, so ${page.slug} was not detached; commit the file and run gbrain sync --source ${page.source_id}, or restore it with gbrain restore ${page.slug} --source-id ${page.source_id}.` };+ }+ const requestId = await repairRequestId(ctx, 'uncommitted-deletions', page, page.revision);+ try {+ await submitPageMutation({ ...ctx, sourceId: page.source_id }, { operation: 'restore_page', databaseOnly: 'detached',+ params: { slug: page.slug, source_id: page.source_id, detach: true, expected_revision: page.revision, request_id: requestId } });+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_identity_changed', 'page_not_found'].includes(error.code)) return changed(error.message);+ throw error;+ }+ return { applied: true, outcome: 'restored_detached', detail: { request_id: requestId, evidence: page.evidence, deleted_by: page.deleted_by } };+}diff --git a/src/core/uncommitted-deletions.ts b/src/core/uncommitted-deletions.tsnew file mode 100644index 0000000000..f6fbe11af5--- /dev/null+++ b/src/core/uncommitted-deletions.ts@@ -0,0 +1,113 @@+/**+ * #7130: soft-deleted pages whose recorded file Git never held. Before #7130 a managed sync deleted a live page whose+ * recorded file was absent from the tree and the disk even when that file had never been committed (an agent's+ * write-through into a `.gitignore`d directory, an untracked file removed before any commit), so the tombstone may hold+ * the only copy of the page and the purge removes it for good after its retention window.+ *+ * One source is scanned on its canonical owner host only (the checkout and its `.gitignore` are read there): its+ * tombstones that still record a file (newest deletion first, at most `TOMBSTONE_SCAN_LIMIT`), the request that deleted+ * each (a committed `managed_sync_delete` request, or an `op_checkpoints` `sync-delete-tombstone` marker naming the page,+ * is a sync deletion), and, for at most `pathLimit` of them, sync deletions first, the Git evidence of the recorded file+ * (`readOriginEvidence` over HEAD's history, `sync-origin-evidence.ts`). A page is listed when `.gitignore` excludes its+ * file, or when no commit holds it and it is not on the disk. A path whose evidence could not be read is counted+ * `unknown`, never listed. Purged pages have no row left and are out of reach: only a backup brings them back.+ *+ * Readers: doctor `uncommitted_sync_deletions` and `gbrain repair uncommitted-deletions`.+ */+import { existsSync } from 'node:fs';+import { relative, resolve, sep } from 'node:path';+import type { BrainEngine } from './engine.ts';+import { isOpPageSlug } from './ops/context.ts';+import { canonicalPath, sourceContext, type GhostOwner } from './ghost-pages.ts';+import { managedPersistenceEnabled } from './persistence/ownership.ts';+import { readOriginEvidence } from './persistence/sync-origin-evidence.ts';++/** `deleted_by: 'sync'` when a committed managed sync request (or a sync tombstone marker) deleted the page; `other` otherwise (a hand delete, a repair, an unknown writer). */+export interface UncommittedDeletion {+ source_id: string; slug: string; page_id: number; revision: string; source_path: string;+ /** The recorded file's path relative to the Git work tree. */+ git_path: string;+ deleted_at: string;+ evidence: 'ignored' | 'never_committed';+ deleted_by: 'sync' | 'other';+}++export interface UncommittedDeletionScan {+ source_id: string;+ status: 'known' | 'unknown' | 'not_applicable';+ /** 'not_managed' | 'not_applicable' | 'not_owner_host' | 'mirror_read_only' | 'storage_unavailable' | 'not_a_git_checkout' */+ reason?: string;+ pages: UncommittedDeletion[];+ /** Tombstones recording a file that were read. */+ tombstones: number;+ /** Tombstones whose file evidence was read (at most the path limit). */+ checked: number;+ /** Checked tombstones whose file Git once committed: not listed. */+ committed: number;+ /** Checked tombstones whose never-committed file is on the disk again: not listed. */+ file_present: number;+ /** Checked tombstones whose evidence could not be read: not listed. */+ unknown: number;+ truncated: boolean;+ owner?: GhostOwner;+ root?: string;+}++/** Tombstones read per source. */+export const TOMBSTONE_SCAN_LIMIT = 20_000;+/** File evidence the doctor reads per run, across sources (each 500 paths cost one `git log` and one `git check-ignore`). */+export const DOCTOR_PATH_LIMIT = 2_000;+export const SYNC_DELETE_TOMBSTONE_OP = 'sync-delete-tombstone';+export const PURGED_NOTE = 'Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create taken before the purge) can bring them back.';++interface TombstoneRow { id: number; slug: string; source_path: string; source_uri: string | null; deleted_at: Date | string; revision: string }++/** The tombstones a sync deleted: the newest deleting request of the slug is a managed sync delete, or a sync tombstone marker names the page. */+async function readSyncDeleted(engine: BrainEngine, sourceId: string, rows: TombstoneRow[]): Promise<Set<number>> {+ if (!rows.length) return new Set();+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ const requests = source ? await engine.executeRaw<{ slug: string; kind: string | null }>(`SELECT DISTINCT ON (slug) slug, intent->>'kind' AS kind FROM persistence_requests+ WHERE source_id=$1 AND source_incarnation=$2::uuid AND state='committed' AND slug=ANY($3::text[])+ AND (operation='delete_page' OR intent->>'kind'='managed_sync_delete') ORDER BY slug, sequence DESC`, [sourceId, source.incarnation, rows.map(row => row.slug)]) : [];+ const bySync = new Set(requests.filter(row => row.kind === 'managed_sync_delete').map(row => row.slug));+ const markers = new Set((await engine.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[])',+ [SYNC_DELETE_TOMBSTONE_OP, rows.map(row => String(row.id))])).map(row => row.fingerprint));+ return new Set(rows.filter(row => bySync.has(row.slug) || markers.has(String(row.id))).map(row => Number(row.id)));+}++/** One source's soft-deleted pages whose recorded file Git never held, sync deletions first. */+export async function scanUncommittedDeletions(engine: BrainEngine, sourceId: string, opts: { pathLimit: number }): Promise<UncommittedDeletionScan> {+ const scan: UncommittedDeletionScan = { source_id: sourceId, status: 'known', pages: [], tombstones: 0, checked: 0, committed: 0, file_present: 0, unknown: 0, truncated: false };+ if (!await managedPersistenceEnabled(engine)) return { ...scan, status: 'not_applicable', reason: 'not_managed' };+ const context = await sourceContext(engine, sourceId);+ if (!context.ok && context.status === 'not_applicable') return { ...scan, status: 'not_applicable', reason: context.reason };+ const rows = await engine.executeRaw<TombstoneRow>(`SELECT id, slug, source_path, source_uri, deleted_at, knowledge_revision::text AS revision FROM pages+ WHERE source_id=$1 AND deleted_at IS NOT NULL AND NULLIF(btrim(source_path), '') IS NOT NULL ORDER BY deleted_at DESC, id LIMIT ${TOMBSTONE_SCAN_LIMIT + 1}`, [sourceId]);+ scan.truncated = rows.length > TOMBSTONE_SCAN_LIMIT;+ const tombstones = rows.slice(0, TOMBSTONE_SCAN_LIMIT).filter(row => isOpPageSlug(row.slug));+ scan.tombstones = tombstones.length;+ if (!context.ok) return tombstones.length ? { ...scan, status: 'unknown', reason: context.reason } : scan;+ Object.assign(scan, { owner: context.owner, root: context.root });+ if (!tombstones.length) return scan;+ if (!context.gitScope) return { ...scan, status: 'not_applicable', reason: 'not_a_git_checkout' };+ const bySync = await readSyncDeleted(engine, sourceId, tombstones);+ const ordered = [...tombstones.filter(row => bySync.has(Number(row.id))), ...tombstones.filter(row => !bySync.has(Number(row.id)))];+ if (ordered.length > opts.pathLimit) scan.truncated = true;+ const gitRoot = resolve(context.root, ...context.gitScope.map(() => '..'));+ const candidates = ordered.slice(0, Math.max(0, opts.pathLimit)).flatMap(row => {+ const file = canonicalPath(context, row);+ const gitPath = relative(gitRoot, file).split(sep).join('/');+ return gitPath.startsWith('../') ? [] : [{ row, file, gitPath }];+ });+ scan.checked = candidates.length;+ const evidence = candidates.length ? await readOriginEvidence(gitRoot, ['HEAD'], candidates.map(candidate => candidate.gitPath)) : new Map();+ for (const { row, file, gitPath } of candidates) {+ const found = evidence.get(gitPath) ?? 'unknown';+ if (found === 'unknown') { scan.unknown++; continue; }+ if (found === 'committed') { scan.committed++; continue; }+ if (found === 'never_committed' && existsSync(file)) { scan.file_present++; continue; }+ scan.pages.push({ source_id: sourceId, slug: row.slug, page_id: Number(row.id), revision: row.revision, source_path: row.source_path, git_path: gitPath,+ deleted_at: new Date(row.deleted_at).toISOString(), evidence: found, deleted_by: bySync.has(Number(row.id)) ? 'sync' : 'other' });+ }+ return scan;+}diff --git a/test/e2e/repair-uncommitted-deletions-7130-postgres.test.ts b/test/e2e/repair-uncommitted-deletions-7130-postgres.test.tsnew file mode 100644index 0000000000..6f084a93fc--- /dev/null+++ b/test/e2e/repair-uncommitted-deletions-7130-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-uncommitted-deletions-7130.test.ts'));diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex cf2201932c..409c2592aa 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -197,7 +197,8 @@ for (const backend of testBackends()) {'conversation-labels': 'gbrain repair conversation-labels', 'captured-facts': 'gbrain repair captured-facts', 'loop-facts': 'gbrain repair loop-facts', 'ontology-facts': 'gbrain repair ontology-facts', 'facts-rehome': 'gbrain repair facts-rehome', 'consolidate-ties': 'gbrain repair consolidate-ties', 'orphan-children': 'gbrain repair orphan-children', 'failed-writes': 'gbrain repair failed-writes', 'split-facts': 'gbrain repair split-facts',frontmatter: 'gbrain repair frontmatter', 'timeline-comments': 'gbrain repair timeline-comments', 'managed-sync-orphans': 'gbrain repair managed-sync-orphans', 'content-receipt-root': 'gbrain repair content-receipt-root', 'frontmatter-keys': 'gbrain repair frontmatter-keys', 'file-drift': 'gbrain repair file-drift','stuck-recovery': 'gbrain repair stuck-recovery', 'ghost-pages': 'gbrain repair ghost-pages', 'origin-twins': 'gbrain repair origin-twins', 'receipt-compaction': 'gbrain repair receipt-compaction', aliases: 'gbrain repair aliases', 'rename-identity': 'gbrain repair rename-identity',- 'overwritten-edits': 'gbrain repair overwritten-edits', 'legacy-twins': 'gbrain repair legacy-twins', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences', 'segmented-mirror': 'gbrain repair segmented-mirror' };+ 'overwritten-edits': 'gbrain repair overwritten-edits', 'legacy-twins': 'gbrain repair legacy-twins', 'missing-tables': 'gbrain repair missing-tables', 'url-clone-fences': 'gbrain repair url-clone-fences', 'segmented-mirror': 'gbrain repair segmented-mirror',+ 'uncommitted-deletions': 'gbrain repair uncommitted-deletions' };// The post-upgrade banner names both findings with the kind's read-only preview.const banner = await postUpgradeRecoveryBanner(engine, 'host');diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex e2a26987c4..f3dc3f9751 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -3316,6 +3316,54 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "by_source": [+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "default",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ },+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "notes",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ },+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "plain",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ }+ ],+ "count": 0,+ "docs": "docs/guides/repair.md#uncommitted-deletions",+ "exact": true,+ "other_writer_count": 0,+ "purged": "Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create taken before the purge) can bring them back.",+ "samples": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "No soft-deleted page was removed by a sync while Git never held its file (0 tombstone(s) checked).",+ "name": "uncommitted_sync_deletions",+ "status": "ok"+ },{"category": "brain","details": {@@ -7668,6 +7716,54 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "by_source": [+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "default",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ },+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "notes",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ },+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "plain",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ }+ ],+ "count": 0,+ "docs": "docs/guides/repair.md#uncommitted-deletions",+ "exact": true,+ "other_writer_count": 0,+ "purged": "Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create taken before the purge) can bring them back.",+ "samples": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "No soft-deleted page was removed by a sync while Git never held its file (0 tombstone(s) checked).",+ "name": "uncommitted_sync_deletions",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 2405d4d5c9..2fcdbc2148 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2853,6 +2853,34 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "by_source": [+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "default",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ }+ ],+ "count": 0,+ "docs": "docs/guides/repair.md#uncommitted-deletions",+ "exact": true,+ "other_writer_count": 0,+ "purged": "Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create taken before the purge) can bring them back.",+ "samples": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "No soft-deleted page was removed by a sync while Git never held its file (0 tombstone(s) checked).",+ "name": "uncommitted_sync_deletions",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 1b2d41942f..4a82cf6544 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2897,6 +2897,34 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "by_source": [+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "default",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ }+ ],+ "count": 0,+ "docs": "docs/guides/repair.md#uncommitted-deletions",+ "exact": true,+ "other_writer_count": 0,+ "purged": "Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create taken before the purge) can bring them back.",+ "samples": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "No soft-deleted page was removed by a sync while Git never held its file (0 tombstone(s) checked).",+ "name": "uncommitted_sync_deletions",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 2603cc3770..4bd3281e88 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -2900,6 +2900,34 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "by_source": [+ {+ "checked": 0,+ "other_writer": 0,+ "source_id": "default",+ "status": "known",+ "sync_deleted": 0,+ "tombstones": 0,+ "truncated": false,+ "unknown": 0+ }+ ],+ "count": 0,+ "docs": "docs/guides/repair.md#uncommitted-deletions",+ "exact": true,+ "other_writer_count": 0,+ "purged": "Pages already purged cannot be restored by this command; only a backup (pg_dump, or gbrain backup create taken before the purge) can bring them back.",+ "samples": [],+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "No soft-deleted page was removed by a sync while Git never held its file (0 tombstone(s) checked).",+ "name": "uncommitted_sync_deletions",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex d8e4e0317f..3c2de87e0f 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -893,6 +893,10 @@"category": "brain","name": "missing_recorded_files"},+ {+ "category": "brain",+ "name": "uncommitted_sync_deletions"+ },{"category": "brain","name": "unindexed_files"diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex a3ff64838b..d5d958402b 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -359,6 +359,7 @@ test/purge-fact.test.tstest/purge-global-marker.test.tstest/purge-missing-cache-6911.test.tstest/purge-read-surfaces.test.ts+test/purge-sync-tombstone-hold-7130.test.tstest/recall-page-fill.test.tstest/receipt-compaction-newest-sync-gbra130.test.tstest/remediation-manual-only.test.tsdiff --git a/test/purge-sync-tombstone-hold-7130.test.ts b/test/purge-sync-tombstone-hold-7130.test.tsnew file mode 100644index 0000000000..0ae74ea754--- /dev/null+++ b/test/purge-sync-tombstone-hold-7130.test.ts@@ -0,0 +1,154 @@+/**+ * #7130: a managed sync deletion is not a person's decision, so its tombstone never becomes an automatic hard delete.+ *+ * Protects: the `managed_sync_delete` apply records the tombstone it made (op `sync-delete-tombstone`, `deleted_at` equal to+ * the page row's) and the checkpoint sweep keeps the record while that tombstone exists; the automatic purges (the cycle+ * purge phase and the `purge` job) keep an expired sync tombstone that no live page of its source duplicates, report it+ * `held` (blocked `sync_delete_unreviewed`, phase warn), and fall back to the uncompacted committed receipt when the+ * record is missing (a tombstone made before records existed); a sync tombstone with a live twin and a person's delete are+ * still purged; the consented `gbrain pages purge-deleted` names the count in its preview and consent and purges them; the+ * cycle cutoff follows `purge.retention_hours`.+ *+ * PGLite always; Postgres with DATABASE_URL (test/postgres-unit-arms.txt).+ */+import { describe, expect, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { runCycle } from '../src/core/cycle.ts';+import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';+import { purgeConsentRequest, purgeDeletedPagesCoordinated, selectPurgeCandidates } from '../src/core/persistence/purge-deleted.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { SYNC_DELETE_TOMBSTONE_OP } from '../src/core/persistence/sync-delete-tombstones.ts';+import { makePurgeHandler } from '../src/core/minions/handlers/purge.ts';+import { runPages } from '../src/commands/pages.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++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 GONE = 'notes/gone', TWIN = 'notes/twin', COPY = 'notes/twin-copy', USER = 'notes/user';+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, `${GONE}.md`), note('Gone', 'An agent-written page that exists nowhere else.'));+ writeFileSync(join(root, `${TWIN}.md`), note('Twin', 'The same words in two files.'));+ writeFileSync(join(root, `${COPY}.md`), note('Twin', 'The same words in two files.'));+ writeFileSync(join(root, `${USER}.md`), note('User', 'A page a person deletes.'));+ commit(root, 'notes');+};+const CONSENT_ENV = { GBRAIN_CONSENT: undefined };++const page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ id: number | string; deleted_at: string | null; deleted_text: string | null }>(+ 'SELECT id, deleted_at, deleted_at::text AS deleted_text FROM pages WHERE source_id=$1 AND slug=$2', ['default', slug]))[0];+const record = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ r: Record<string, unknown>; same: boolean }>(+ `SELECT c.completed_keys->0 AS r, p.deleted_at = (c.completed_keys->0->>'deleted_at')::timestamptz AS same FROM op_checkpoints c JOIN pages p ON p.id::text = c.fingerprint+ WHERE c.op=$1 AND p.source_id='default' AND p.slug=$2`, [SYNC_DELETE_TOMBSTONE_OP, slug]))[0];++/** git rm GONE and TWIN, sync (the pass soft-deletes both), then a person deletes USER through delete_page. */+async function deleteBoth(engine: BrainEngine, ctx: OperationContext, root: string): Promise<void> {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ git(root, 'rm', '-q', `${GONE}.md`, `${TWIN}.md`); commit(root, 'remove two notes');+ await performManagedSync(engine, OPTS);+ for (const slug of [GONE, TWIN]) expect((await page(engine, slug))?.deleted_at).not.toBeNull();+ const user = await engine.readPageSnapshot(USER, { sourceId: 'default' });+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: USER, expected_revision: user!.revision, request_id: randomUUID() } });+ expect((await page(engine, USER))?.deleted_at).not.toBeNull();+}+/** Ages every tombstone (and its record, which names its deleted_at) by `hours`, as time would. A fixture write, outside coordination. */+async function age(engine: BrainEngine, hours: number): Promise<void> {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw(`UPDATE pages SET deleted_at = deleted_at - ($1 || ' hours')::interval WHERE source_id='default' AND deleted_at IS NOT NULL`, [String(hours)]);+ await engine.executeRaw(`UPDATE op_checkpoints c SET completed_keys = jsonb_set(c.completed_keys, '{0,deleted_at}', to_jsonb(p.deleted_at)) FROM pages p+ WHERE c.op=$1 AND p.id::text = c.fingerprint`, [SYNC_DELETE_TOMBSTONE_OP]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+}+const purgePhase = async (engine: BrainEngine, root: string) =>+ (await withEnv(CONSENT_ENV, () => runCycle(engine, { brainDir: root, phases: ['purge'], sourceId: 'default' }))).phases.find(p => p.phase === 'purge')!;+async function cli(engine: BrainEngine, args: string[]): Promise<string> {+ const out: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { out.push(parts.map(String).join(' ')); });+ const err = spyOn(console, 'error').mockImplementation(() => {});+ try { await withEnv(CONSENT_ENV, () => runPages(engine, args)); }+ finally { log.mockRestore(); err.mockRestore(); }+ return out.join('\n');+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe(`#7130 ${backend}: the automatic purge keeps managed sync tombstones`, () => {+ test('the record matches the tombstone and survives the checkpoint sweep while it exists', () => managedBrain(async ({ engine, ctx, root }) => {+ await deleteBoth(engine, ctx, root);+ const gone = await record(engine, GONE);+ expect(gone?.same).toBe(true);+ expect(gone?.r).toMatchObject({ source_id: 'default', slug: GONE, page_id: Number((await page(engine, GONE))!.id), source_path: `${GONE}.md` });+ expect(typeof gone?.r.pass_id === 'string' || typeof gone?.r.run_id === 'string').toBe(true);+ expect(await record(engine, USER)).toBeUndefined();+ await engine.executeRaw(`UPDATE op_checkpoints SET updated_at = now() - interval '30 days' WHERE op=$1`, [SYNC_DELETE_TOMBSTONE_OP]);+ await purgeStaleCheckpoints(engine, 7);+ expect((await record(engine, GONE))?.same).toBe(true);+ }, { setup, databaseUrl }), 300_000);++ test('cycle: a unique sync tombstone is held and reported, a twin and a person\'s delete are purged; the consented manual purge removes the held one', () => managedBrain(async ({ engine, ctx, root }) => {+ await deleteBoth(engine, ctx, root);+ await age(engine, 100);+ const phase = await purgePhase(engine, root);+ expect(phase.status).toBe('warn');+ expect(phase.summary).toContain('1 deleted by a managed sync held for review');+ expect(phase.details.purged_pages_blocked).toEqual([expect.objectContaining({ slug: GONE, code: 'sync_delete_unreviewed' })]);+ expect([...phase.details.purged_page_slugs as string[]].sort()).toEqual([TWIN, USER]);+ expect(await page(engine, GONE)).toBeDefined();+ expect(await page(engine, TWIN)).toBeUndefined();+ expect(await page(engine, USER)).toBeUndefined();+ // The purge job runs without consent too.+ expect(await makePurgeHandler(engine)({ data: { scope: 'pages' } } as never)).toMatchObject({ pagesPurged: 0, pagesBlocked: [expect.objectContaining({ slug: GONE, code: 'sync_delete_unreviewed' })] });++ const preview = JSON.parse(await cli(engine, ['purge-deleted', '--dry-run', '--json']));+ expect(preview).toMatchObject({ dry_run: true, count: 1, slugs: [GONE], sync_unreviewed: 1 });+ const consent = purgeConsentRequest(preview.count, 72, true, [], false, 0, preview.sync_unreviewed);+ expect(consent.user_message).toContain('1 of them were deleted by a managed sync');+ expect(consent.risk).toContain('only come back from a backup');+ await cli(engine, ['purge-deleted', '--json', '--yes']);+ expect(await page(engine, GONE)).toBeUndefined();+ await purgeStaleCheckpoints(engine, 0);+ expect((await engine.executeRaw('SELECT 1 FROM op_checkpoints WHERE op=$1', [SYNC_DELETE_TOMBSTONE_OP])).length).toBe(0);+ }, { setup, databaseUrl }), 300_000);++ test('a sync tombstone with no record is held by its uncompacted receipt', () => managedBrain(async ({ engine, ctx, root }) => {+ await deleteBoth(engine, ctx, root);+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1', [SYNC_DELETE_TOMBSTONE_OP]);+ await age(engine, 100);+ const result = await withEnv(CONSENT_ENV, () => purgeDeletedPagesCoordinated(engine, 72, { automatic: true }));+ expect(result).toMatchObject({ held: 1, failed: 0 });+ expect(result.blocked).toEqual([expect.objectContaining({ slug: GONE, code: 'sync_delete_unreviewed' })]);+ expect(await page(engine, GONE)).toBeDefined();+ }, { setup, databaseUrl }), 300_000);++ test('a brain deactivated after managed syncs still holds them (unmanaged purge)', () => managedBrain(async ({ engine, ctx, root }) => {+ await deleteBoth(engine, ctx, root);+ await age(engine, 100);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ expect(await selectPurgeCandidates(engine, 72)).toMatchObject({ managed: false, count: 3, sync_unreviewed: 1 });+ const result = await purgeDeletedPagesCoordinated(engine, 72, { automatic: true });+ expect(result).toMatchObject({ held: 1, count: 2 });+ expect(await page(engine, GONE)).toBeDefined();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }, { setup, databaseUrl }), 300_000);++ test('purge.retention_hours sets the cycle cutoff', () => managedBrain(async ({ engine, ctx, root }) => {+ await deleteBoth(engine, ctx, root);+ await age(engine, 100);+ await engine.setConfig('purge.retention_hours', '200');+ expect((await purgePhase(engine, root)).details.purged_pages_count).toBe(0);+ expect(await page(engine, USER)).toBeDefined();+ await engine.setConfig('purge.retention_hours', '96');+ expect([...(await purgePhase(engine, root)).details.purged_page_slugs as string[]].sort()).toEqual([TWIN, USER]);+ }, { setup, databaseUrl }), 300_000);+ });+}diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 074b1860ba..c6190d9a6c 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'uncommitted-deletions'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));diff --git a/test/repair-uncommitted-deletions-7130.test.ts b/test/repair-uncommitted-deletions-7130.test.tsnew file mode 100644index 0000000000..8b7a0bbbbf--- /dev/null+++ b/test/repair-uncommitted-deletions-7130.test.ts@@ -0,0 +1,169 @@+/**+ * #7130 (reported by @liuwenyong1985): before the fix a managed sync soft-deleted pages whose recorded file Git never+ * held (a write-through file in a .gitignore'd directory, an untracked file removed before any commit), and the purge+ * removed them for good after 72 h. For brains already hit, on a real managed brain (PGLite, and Postgres through the+ * E2E wrapper), this protects:+ * - doctor `uncommitted_sync_deletions` warns about exactly the sync-deleted tombstones whose file is ignored or never+ * committed (a committed then git-rm'd control, and a page another writer deleted, never warn; a+ * `sync-delete-tombstone` marker naming the page counts as a sync deletion);+ * - `gbrain repair uncommitted-deletions --source <id>` previews them with a hash and the purge caveat, refuses a wrong+ * hash (preview_changed), exits 3 without --yes, and with the right hash restores each live and detached+ * (database-only, no file written); the next sync, incremental and full, keeps them live and the control deleted;+ * - off the owner host the doctor check is not_applicable and the repair refuses not_owner_host.+ */+import { beforeEach, afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { resolveRepairScope, type RepairKind } from '../src/core/repair/core.ts';+import { EXPLICIT_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { uncommittedSyncDeletionsEntry } from '../src/commands/doctor/checks/uncommitted-sync-deletions.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { waitFor } from './helpers/wait-for.ts';+import { withEnv } from './helpers/with-env.ts';++const KIND = 'uncommitted-deletions' as RepairKind;+const logger = { info() {}, warn() {}, error() {} };+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 setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${name}.md`), note(`notes/${name}`, `The committed body of notes/${name}.`));+ commit(root, 'notes');+};++async function capture(fn: () => Promise<void>): Promise<string> {+ let printed = '';+ const original = console.log, write = process.stdout.write;+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;+ try { await fn(); } finally { console.log = original; process.stdout.write = write; }+ return printed;+}++async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {+ try { await fn(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++const pageRow = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ live: boolean; source_path: string | null; database_only_reason: string | null }>(+ "SELECT deleted_at IS NULL AS live, source_path, database_only_reason FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];+const doctor = async (engine: BrainEngine) => (await uncommittedSyncDeletionsEntry.run({ engine } as never) as Array<Record<string, any>>)[0]!;+const repair = async (engine: BrainEngine, opts: { apply?: boolean; expect?: string; includeAmbiguous?: boolean } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))+ .run(KIND, await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', expect: opts.expect, includeAmbiguous: opts.includeAmbiguous });++/** Imports untracked files from the working tree (working mode), then returns to committed mode. */+async function importUntracked(engine: BrainEngine, root: string, files: Record<string, string>) {+ for (const [path, body] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), note(path.replace(/\.md$/, ''), body)); }+ await engine.setConfig('sync.include_working_tree', 'true');+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');+ await engine.setConfig('sync.include_working_tree', 'false');+}++/** A coordinated delete_page; `asSync` stamps its committed receipt as the pre-#7130 sync's managed_sync_delete (the deletion this repair undoes). */+async function softDelete(engine: BrainEngine, ctx: OperationContext, slug: string, asSync: boolean) {+ const requestId = randomUUID();+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug, expected_revision: snapshot!.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 ${slug} commits` });+ if (asSync) await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_requests SET intent=jsonb_set(intent, '{kind}', '"managed_sync_delete"') WHERE request_id=$1::uuid`, [requestId]);+ });+}++/**+ * notes/draft (untracked, never committed) and scratch/agent (its directory later .gitignore'd) are sync-deleted the+ * pre-fix way; notes/hand (untracked) is deleted by hand; notes/c is committed, then git rm'd and deleted by a real sync.+ */+async function hitBrain(engine: BrainEngine, ctx: OperationContext, root: string) {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await importUntracked(engine, root, { 'notes/draft.md': 'An untracked draft only the brain holds.', 'notes/hand.md': 'An untracked note deleted by hand.',+ 'scratch/agent.md': 'An agent page written to scratch/.' });+ writeFileSync(join(root, '.gitignore'), 'scratch/\n');+ git(root, 'add', '.gitignore'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'ignore scratch');+ await softDelete(engine, ctx, 'notes/draft', true);+ await softDelete(engine, ctx, 'scratch/agent', true);+ await softDelete(engine, ctx, 'notes/hand', false);+ rmSync(join(root, 'notes/draft.md'), { force: true }); rmSync(join(root, 'notes/hand.md'), { force: true }); rmSync(join(root, 'scratch'), { recursive: true, force: true });+ git(root, 'rm', '-q', 'notes/c.md'); commit(root, 'remove c');+ await performManagedSync(engine, OPTS);+ expect((await pageRow(engine, 'notes/c'))!.live).toBe(false);+ for (const slug of ['notes/draft', 'scratch/agent', 'notes/hand']) expect((await pageRow(engine, slug))!.live).toBe(false);+}++for (const backend of testBackends()) describe(`[${backend}] #7130: restoring pages a sync deleted although Git never held their file`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ beforeEach(() => _resetCliExitVerdictForTests());+ afterEach(() => _resetCliExitVerdictForTests());++ test('doctor lists only the uncommitted sync deletions; preview, wrong hash, consent, apply; the next sync keeps them live', () => managedBrain(async ({ engine, ctx, root }) => {+ await hitBrain(engine, ctx, root);+ expect(categorizeCheck('uncommitted_sync_deletions')).toBeDefined();+ const found = await doctor(engine);+ expect(found).toMatchObject({ name: 'uncommitted_sync_deletions', status: 'warn', details: { count: 2, other_writer_count: 1, exact: true } });+ expect(found.details.samples.map((page: { slug: string; evidence: string }) => [page.slug, page.evidence]).sort()).toEqual([['notes/draft', 'never_committed'], ['scratch/agent', 'ignored']]);+ expect(found.message).toContain('gbrain repair uncommitted-deletions --source default');+ expect(found.message).toContain('only a backup');+ expect(found.fix.argv).toEqual(['gbrain', 'repair', 'uncommitted-deletions', '--source', 'default', '--json']);++ expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toContain(KIND);+ const preview = JSON.parse(await capture(() => runRepairCommand(engine, ['uncommitted-deletions', '--source', 'default', '--json']))).results[0];+ expect(preview.listing.map((entry: { item: string; class: string }) => [entry.item, entry.class]).sort()).toEqual([+ ['default:notes/draft', 'restore:never_committed'], ['default:notes/hand', 'excluded:deleted_by_other'], ['default:scratch/agent', 'restore:ignored']]);+ expect(preview.affected).toBe(2);+ expect(preview.warnings[0]).toContain('Pages already purged cannot be restored by this command');+ expect(preview.apply_command).toBe(`gbrain repair uncommitted-deletions --source default --apply --expect ${preview.preview_hash} --yes`);+ expect((await repair(engine, { includeAmbiguous: true })).affected).toBe(3);++ expect((await refusal(() => repair(engine, { apply: true, expect: 'f'.repeat(64) }))).code).toBe('preview_changed');+ const priorExitCode = process.exitCode;+ await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() =>+ runRepairCommand(engine, ['uncommitted-deletions', '--source', 'default', '--apply', '--expect', preview.preview_hash, '--json'])));+ expect(currentExitCode()).toBe(3);+ process.exitCode = priorExitCode ?? 0;+ _resetCliExitVerdictForTests();+ expect((await pageRow(engine, 'notes/draft'))!.live).toBe(false);++ const applied = JSON.parse(await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() =>+ runRepairCommand(engine, ['uncommitted-deletions', '--source', 'default', '--apply', '--expect', preview.preview_hash, '--yes', '--json'])))).results[0];+ expect(applied).toMatchObject({ mode: 'apply', applied: 2, skipped: 0, failed: [], complete: true, outcomes: { restored_detached: 2 } });+ for (const slug of ['notes/draft', 'scratch/agent']) expect(await pageRow(engine, slug)).toEqual({ live: true, source_path: null, database_only_reason: 'detached' });+ expect(existsSync(join(root, 'notes/draft.md')) || existsSync(join(root, 'scratch/agent.md'))).toBe(false);++ // The next sync, incremental and full, keeps them live; the committed-then-removed control and the hand delete stay deleted.+ await performManagedSync(engine, OPTS);+ await performManagedSync(engine, { ...OPTS, full: true });+ for (const slug of ['notes/draft', 'scratch/agent']) expect(await pageRow(engine, slug)).toEqual({ live: true, source_path: null, database_only_reason: 'detached' });+ expect((await pageRow(engine, 'notes/c'))!.live).toBe(false);+ expect((await pageRow(engine, 'notes/hand'))!.live).toBe(false);+ expect(await doctor(engine)).toMatchObject({ status: 'ok', details: { count: 0, other_writer_count: 1 } });+ }, { databaseUrl, setup }), 240_000);++ test('a sync tombstone marker counts as a sync deletion; off the owner host the doctor check is not applicable and the repair refuses not_owner_host', () => managedBrain(async ({ engine, ctx, root }) => {+ await hitBrain(engine, ctx, root);+ const [hand] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug='notes/hand'");+ await engine.executeRaw("INSERT INTO op_checkpoints(op, fingerprint, completed_keys) VALUES ('sync-delete-tombstone', $1, '[]'::jsonb)", [String(hand!.id)]);+ expect(await doctor(engine)).toMatchObject({ status: 'warn', details: { count: 3, other_writer_count: 0 } });+ const hash = (await repair(engine)).preview_hash!;+ await withEnv({ GBRAIN_HOME: join(dirname(root), 'other-host') }, async () => {+ expect(await doctor(engine)).toMatchObject({ status: 'ok', readiness_state: 'not_applicable', details: { reason: 'not_owner_host' } });+ expect((await refusal(() => repair(engine))).code).toBe('not_owner_host');+ expect((await refusal(() => repair(engine, { apply: true, expect: hash }))).code).toBe('not_owner_host');+ });+ expect((await pageRow(engine, 'notes/draft'))!.live).toBe(false);+ }, { databaseUrl, setup }), 240_000);+});