Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): never soft-delete a page written after its file for the file's deletion

garrytan143138a8bef9
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index d1a6fc59d8..eaaaa76f0e 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2231,6 +2231,16 @@ gbrain repair file-drift --source <id> --held --side deleted --state file_gone -
gbrain repair file-drift --source <id> --held --side deleted --state file_gone --provenance deleted_by_commit --prefer file
```
+A `deleted_by_commit` page whose revision is not file-backed (written in the
+database after its file last held it: not the revision sync last imported from
+the file, and not one a committed sync or Git-published write produced; for a
+page no import record covers, written after the commit that deleted its file) is
+listed apart as `database_ahead_of_file` and not soft-deleted, since it holds
+the only copy of that content. Recreate its file with
+`gbrain repair file-drift --source <id> --slug <slug> --prefer database`, or
+keep it. `gbrain repair ghost-pages` lists such a page apart the same way, and
+the soft-delete itself refuses one (`refused`, `database_ahead_of_file`).
+
`--provenance never_committed --prefer file` is refused: it would soft-delete
the only copy of each page. A database-only page is no longer screened against
a file; a file synced back at its old path binds it again. The apply re-checks
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index c99b70baa9..6fdbf282da 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1131,6 +1131,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.372.0', text: '`gbrain sources status --json` no longer prints every held file of a source by default: `git_holds` now carries `count`, `by_code` (each hold code with its count and one example item, whose `fix` applies to the rest), and the first 10 items with `items_complete: false` and an `items_command`. `--holds` lists every held file read, as before, and `--limit <n> [--cursor <c>]` pages them by path (the cursor needs the source id). The text output is unchanged.' },
// #7355: a level read reports progress; pass_abandoned; racy floor
{ since: '0.60.377.0', text: 'A managed `gbrain sync` pass no longer stops `drain_stalled` / `no_progress` on a large source while it is still reading and classifying the level before its first commit: the level read reports progress to the drain as it works (its loops and the history walk for the origin evidence of files a page lost), writes the open pass row every 30 s so a follower and `gbrain sync status` see it working, and a pass that asks for a history walk already running joins it. A hung read still stops after 5 minutes. When two passes in a row never end (abandoned by the drain or killed; the newest open one counts after 5 quiet minutes), `gbrain sync status` reads `blocked` with the new reason `pass_abandoned` and `next` is `gbrain doctor --json` and a report, instead of the plain sync. The stat caches of the dirtiness probe and the working level now take the racy window from the earlier of the process clock and the filesystem clock (a file written in the Git directory), so a mount whose clock lags the process no longer keeps a stale `clean` verdict.' },
+ // GBRA-133: a page written after its file is never soft-deleted for the file's deletion
+ { since: 'TBD', text: '`gbrain repair file-drift --held --side deleted --state file_gone --prefer file` (including `--provenance deleted_by_commit`) and `gbrain repair ghost-pages` no longer soft-delete a page whose revision was written in the database after its file last held it (neither the revision sync last imported from the file nor one a committed sync or Git-published write produced; for a page no import record covers, written after the commit that deleted its file): the preview lists it apart as `database_ahead_of_file` with how to recreate its file (`--slug <slug> --prefer database`), and the apply refuses it (`refused`, `database_ahead_of_file`), also for an approval saved before this release. Before, a commit that deleted the file was taken as the page\'s deletion, so content no commit held was soft-deleted.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index e9c994aa73..b348c66514 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -464,17 +464,24 @@ async function readAttestations(exec: Exec, kind: 'postgres' | 'pglite', sourceI
for (let i = 0; i < rows.length; i += size) {
const chunk = rows.slice(i, i + size);
statements++;
- const found = await exec.executeRaw<{ page_id: number; arm1: boolean; attested_hash: string | null }>(`SELECT x.page_id,
+ const found = await readRevisionAttestations(exec, sourceId, incarnation, chunk.map(row => ({ pageId: Number(pages.id[row]), requestId: pages.requestId[row] ?? null,
+ revision: pages.revision[row]!, sourcePath: pages.sourcePath[row] ?? null })));
+ for (const hit of found) pages.attested.set(byId.get(Number(hit.page_id))!, { arm1: hit.arm1, hash: hit.attested_hash });
+ }
+ return statements;
+}
+
+/** `A` for one statement's pages, by the request that wrote each page's current revision (see `readAttestations`); a page with no committed request has no row. */
+export async function readRevisionAttestations(exec: Exec, sourceId: string, incarnation: string,
+ rows: ReadonlyArray<{ pageId: number; requestId: string | null; revision: string; sourcePath: string | null }>): Promise<Array<{ page_id: number; arm1: boolean; attested_hash: string | null }>> {
+ return exec.executeRaw<{ page_id: number; arm1: boolean; attested_hash: string | null }>(`SELECT x.page_id,
(r.intent->>'kind' = ANY($3::text[]) AND r.source_incarnation::text=$2 AND (r.page_id IS NULL OR r.page_id=x.page_id)) AS arm1,
COALESCE((SELECT e.data->>'expected_hash' FROM persistence_effects e WHERE e.request_id=r.id AND e.kind='git' AND e.revision=x.revision
AND e.data->>'expected_hash' IS NOT NULL AND (e.data->>'relative_path'=x.source_path OR right(e.data->>'relative_path', length(x.source_path)+1)='/'||x.source_path) LIMIT 1),
CASE WHEN r.intent->>'kind'='managed_file_import' AND r.intent->>'sourcePath'=x.source_path AND r.intent->>'inputHash'=r.intent->>'targetHash' THEN r.intent->>'targetHash' END) AS attested_hash
FROM unnest($4::int[], $5::uuid[], $6::uuid[], $7::text[]) AS x(page_id, request_id, revision, source_path)
JOIN persistence_requests r ON r.id=x.request_id AND r.state='committed' AND r.source_id=$1`,
- [sourceId, incarnation, SYNC_WRITE_KINDS, chunk.map(row => Number(pages.id[row])), chunk.map(row => pages.requestId[row]), chunk.map(row => pages.revision[row]), chunk.map(row => pages.sourcePath[row])]);
- for (const hit of found) pages.attested.set(byId.get(Number(hit.page_id))!, { arm1: hit.arm1, hash: hit.attested_hash });
- }
- return statements;
+ [sourceId, incarnation, SYNC_WRITE_KINDS, rows.map(row => row.pageId), rows.map(row => row.requestId), rows.map(row => row.revision), rows.map(row => row.sourcePath)]);
}
/** `U_db`: open requests of the worktree (the `persistence_requests_pending` index) and pending Git effects of the source. */
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index da3ba97310..bd2b517ec0 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -83,7 +83,7 @@ import { DETACHED_REASON } from '../persistence/detached-pages.ts';
import { DELETION_PROVENANCES, readDeletionProvenance, type DeletionProvenance } from '../persistence/sync-origin-evidence.ts';
import { ghostPageNow, scanGhostSource, type GhostOwner, type GhostPage } from '../ghost-pages.ts';
import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';
-import { GHOST_PURGE_FUSE_HOURS, GHOST_REPAIR_LIMIT, ghostScanRefusal, massGhosts, massRefusal, retireGhost } from './ghost-pages.ts';
+import { DATABASE_AHEAD_CODE, databaseAheadDetail, ghostFileBacked, GHOST_PURGE_FUSE_HOURS, GHOST_REPAIR_LIMIT, ghostScanRefusal, massGhosts, massRefusal, retireGhost } from './ghost-pages.ts';
import { prepareReconcileResult } from '../persistence/reconcile-prepare.ts';
import { canonicalOriginPage, originConflictMessage, originTwinsFix } from '../persistence/origin-guard.ts';
import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/reconcile-backup.ts';
@@ -517,6 +517,7 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,
return { page: { slug, prefer: 'database', exceptions: [], detach_page: { path: now.ghost.path, page_id: now.ghost.page_id, revision: now.ghost.revision, observed_at: target.hold.observed_at } },
detail: `keeps the page database-only: no commit ever held ${now.ghost.path}, so the page holds the only copy; no file is written and the page forgets that path` };
}
+ if (opts.prefer === 'file' && !await ghostFileBacked(engine, now.ghost, now.owner)) return { skip: DATABASE_AHEAD_CODE, detail: databaseAheadDetail(now.ghost) };
if (opts.prefer === 'file') return { page: { slug, prefer: 'file', exceptions: [], soft_delete: { ghost: now.ghost, owner: now.owner } },
detail: `soft-deletes the page: its file ${now.ghost.path} is gone from the last commit (purged after ${GHOST_PURGE_FUSE_HOURS} h; gbrain restore ${slug} --force undoes it until then)` };
const page = await prepareDriftPage(engine, sourceId, slug, 'database', assessmentAt, { fileGone: true });
diff --git a/src/core/repair/ghost-pages.ts b/src/core/repair/ghost-pages.ts
index 9b3345f068..d82b7f7a12 100644
--- a/src/core/repair/ghost-pages.ts
+++ b/src/core/repair/ghost-pages.ts
@@ -47,6 +47,9 @@ import { authorizeWrite } from '../persistence/authority.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
+import { readSyncImportProvenance } from '../persistence/sync-holds.ts';
+import { readRevisionAttestations } from '../persistence/sync-pass.ts';
+import { readDeletionProvenance } from '../persistence/sync-origin-evidence.ts';
import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';
@@ -158,20 +161,24 @@ export const ghostPagesRepair: RepairHandler = {
const mass = massGhosts(scan.ghosts.length, scan.file_backed);
if (!opts?.apply) {
const skillPaths = scan.skill_paths.length;
- const hash = previewHash(hashParts(scope, scan.owner, scan.ghosts));
- if (scan.ghosts.length) await saveApprovedSet<ApprovedGhost>(engine, { command: 'ghost-pages', hash },
- scan.ghosts.map(ghost => ({ ...ghost, owner: scan.owner!, selection: scope.source_ids })));
+ const ahead: GhostPage[] = [], ghosts: GhostPage[] = [];
+ for (const ghost of scan.ghosts) (await ghostFileBacked(engine, ghost, scan.owner!) ? ghosts : ahead).push(ghost);
+ const hash = previewHash(hashParts(scope, scan.owner, ghosts));
+ if (ghosts.length) await saveApprovedSet<ApprovedGhost>(engine, { command: 'ghost-pages', hash },
+ ghosts.map(ghost => ({ ...ghost, owner: scan.owner!, selection: scope.source_ids })));
const warnings = [
...(mass ? [`${scan.ghosts.length} of ${scan.file_backed} file-backed page(s) are ghosts (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%): the apply refuses (ghost_mass_delete_refused) unless GBRAIN_ALLOW_MASS_RECONCILE=1; check the checkout first.`] : []),
...(scan.truncated ? [`More ghosts may exist past the first ${GHOST_REPAIR_LIMIT} checked; apply this set, then preview again.`] : []),
...(skillPaths ? [`${skillPaths} ghost page(s) on files of the shared skillpack are listed apart (${SKILL_PACK_MEMBER_CODE}) and not applied: ${SKILL_PATH_NOTE}`] : []),
+ ...(ahead.length ? [`${ahead.length} ghost page(s) were written in the database after their file last held them, so each holds the only copy of that content; they are listed apart (${DATABASE_AHEAD_CODE}) and not applied.`] : []),
...(scan.reason === 'mirror_read_only' ? [`Source ${sourceId} is a read-only mirror: its pages publish no file, so none is a ghost.`] : []),
- ...(scan.ghosts.length ? Object.values(GHOST_CONSEQUENCES) : []),
+ ...(ghosts.length ? Object.values(GHOST_CONSEQUENCES) : []),
];
- return { warnings, items: scan.ghosts.map((ghost, index) => item(ghost, scan.owner!, hash, index === scan.ghosts.length - 1)), preview_hash: hash,
- residuals: { ghosts: scan.ghosts.length, file_backed: scan.file_backed, inspected: scan.inspected, ...(skillPaths ? { skill_paths: skillPaths } : {}) },
- listing: [...scan.ghosts.map(ghost => ({ item: `${ghost.source_id}:${ghost.slug}`, class: 'canonical_file_missing',
+ return { warnings, items: ghosts.map((ghost, index) => item(ghost, scan.owner!, hash, index === ghosts.length - 1)), preview_hash: hash,
+ residuals: { ghosts: ghosts.length, file_backed: scan.file_backed, inspected: scan.inspected, ...(skillPaths ? { skill_paths: skillPaths } : {}), ...(ahead.length ? { database_ahead: ahead.length } : {}) },
+ listing: [...ghosts.map(ghost => ({ item: `${ghost.source_id}:${ghost.slug}`, class: 'canonical_file_missing',
detail: `file ${ghost.path} is missing; revision ${ghost.revision}` })),
+ ...ahead.map(ghost => ({ item: `${ghost.source_id}:${ghost.slug}`, class: DATABASE_AHEAD_CODE, detail: databaseAheadDetail(ghost) })),
...scan.skill_paths.map(ghost => ({ item: `${ghost.source_id}:${ghost.slug}`, class: SKILL_PACK_MEMBER_CODE,
detail: `shared skillpack file ${ghost.path} is missing; not applied. Restore it: ${skillPathRestore(scan.root, ghost)}` }))],
details: { purge_fuse_hours: GHOST_PURGE_FUSE_HOURS, undo: 'gbrain restore <slug> --force', keep: GHOST_CONSEQUENCES.keep, mass_delete: mass, truncated: scan.truncated, docs: DOCS,
@@ -215,12 +222,40 @@ const restored = (ghost: GhostPage): RepairItemOutcome => ({ applied: false, out
reason: `The canonical file ${ghost.path} exists again, so ${ghost.slug} was kept; run ${ghostPreviewCommand(ghost.source_id)} again for a new preview.` });
const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
-/** Whether the live page is still the approved ghost under the approved owner; otherwise the outcome that skips it. */
+/**
+ * Whether a ghost's live revision is file-backed: the revision sync last imported from its file (the import record), or
+ * one a committed sync write or a Git-published write produced (the attestation sync's own deletion proof reads). Any
+ * other revision of a recorded page was written in the database after its file last held it, so the file's absence,
+ * even a committed deletion, says nothing about that content and soft-deleting the page would drop the only copy of it.
+ * A page with no import record is judged against the date of the commit that deleted its file, when one did.
+ */
+export async function ghostFileBacked(engine: BrainEngine, ghost: GhostPage, owner: GhostOwner): Promise<boolean> {
+ const recorded = (await readSyncImportProvenance(engine, ghost.source_id, owner.source_incarnation, ghost.page_id))?.revision;
+ if (recorded === ghost.revision) return true;
+ const [page] = await engine.executeRaw<{ request_id: string | null; source_path: string | null; updated_ms: number }>(
+ 'SELECT revision_write_request_id::text AS request_id, source_path, (extract(epoch FROM updated_at) * 1000)::float8 AS updated_ms FROM pages WHERE id=$1 AND knowledge_revision::text=$2', [ghost.page_id, ghost.revision]);
+ if (!page) return false;
+ const [hit] = page.request_id ? await readRevisionAttestations(engine, ghost.source_id, owner.source_incarnation,
+ [{ pageId: ghost.page_id, requestId: page.request_id, revision: ghost.revision, sourcePath: page.source_path ?? ghost.path }]) : [];
+ if (hit && (hit.arm1 || hit.attested_hash !== null)) return true;
+ if (recorded !== undefined) return false;
+ // A page no import record covers (an older or unmanaged import) is ahead only when it was written after the commit that deleted its file.
+ const binding = await getWorktreeBinding(engine, ghost.source_id, owner.host_id);
+ if (!binding?.local_path) return true;
+ const deletion = (await readDeletionProvenance(join(binding.local_path, binding.relative_path), [ghost.path])).get(ghost.path);
+ return deletion?.kind !== 'deleted_by_commit' || Number(page.updated_ms) <= Date.parse(deletion.date);
+}
+
+export const DATABASE_AHEAD_CODE = 'database_ahead_of_file';
+export const databaseAheadDetail = (ghost: GhostPage) => `file ${ghost.path} is gone, but page ${ghost.slug} was written in the database after the file last held it, so it holds the only copy of that content; not soft-deleted. Recreate the file from the page with gbrain repair file-drift --source ${ghost.source_id} --slug ${ghost.slug} --prefer database, or keep the page as it is`;
+
+/** Whether the live page is still the approved ghost under the approved owner, with a file-backed revision; otherwise the outcome that skips it. */
async function stillApproved(engine: BrainEngine, ghost: GhostPage, owner: GhostOwner): Promise<RepairItemOutcome | null> {
const now = await ghostPageNow(engine, ghost.source_id, ghost.slug);
if (!now.ghost) return now.reason === 'agrees' || now.reason === 'file_database_drift' ? restored(ghost) : changed(`the page is no longer a ghost (${now.reason})`);
if (!sameOwner(now.owner, owner)) return changed('the source\'s canonical owner changed since the preview');
if (now.ghost.revision !== ghost.revision || now.ghost.page_id !== ghost.page_id || now.ghost.path !== ghost.path) return changed('the page or its recorded canonical path changed since the preview');
+ if (!await ghostFileBacked(engine, ghost, owner)) return { applied: false, outcome: 'refused', reason: DATABASE_AHEAD_CODE, detail: { message: databaseAheadDetail(ghost) } };
return null;
}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 8a7ebab6a5..678c25f3f6 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -391,6 +391,7 @@ test/repair-file-drift-held-window-gbra133.test.ts
test/repair-file-drift-provenance-gbra133.test.ts
test/repair-frontmatter-keys-sweep-6454.test.ts
test/repair-frontmatter.test.ts
+test/repair-ghost-database-ahead-gbra133.test.ts
test/repair-receipt-compaction.test.ts
test/repair-rename-identity-6729.test.ts
test/retrieval-coverage-notices.test.ts
diff --git a/test/repair-ghost-database-ahead-gbra133.test.ts b/test/repair-ghost-database-ahead-gbra133.test.ts
new file mode 100644
index 0000000000..1303c9818d
--- /dev/null
+++ b/test/repair-ghost-database-ahead-gbra133.test.ts
@@ -0,0 +1,97 @@
+/**
+ * GBRA-133 (data loss): a page written in the database after its file last held it is never soft-deleted because that
+ * file is gone, even when a commit deleted the file.
+ * - `gbrain repair file-drift --held --side deleted --state file_gone --provenance deleted_by_commit --prefer file` lists
+ * such a page apart (`database_ahead_of_file`) and soft-deletes only pages whose revision is file-backed (the
+ * revision sync last imported from the file);
+ * - `gbrain repair ghost-pages` lists it apart the same way and never approves it;
+ * - the soft-delete itself refuses it (`refused`, `database_ahead_of_file`), so an approval saved before this check, or
+ * a page written between the preview and the apply, still keeps its content.
+ * Before: the file's deleting commit was taken as the page's deletion, so the soft-delete dropped content no commit held.
+ * Real PGLite (and Postgres when DATABASE_URL is set), a real managed sync and real Git; the later database write is
+ * modelled as a new revision with new text and no write request (what a database-only write leaves).
+ */
+import { describe, expect, 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 { ghostPageNow } from '../src/core/ghost-pages.ts';
+import { RECOVERY_VERSION } from '../src/core/markdown.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { retireGhost } from '../src/core/repair/ghost-pages.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const logger = { info() {}, warn() {}, error() {} };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+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 deletedAt = async (engine: BrainEngine, slug: string) =>
+ (await engine.executeRaw<{ deleted_at: unknown }>("SELECT deleted_at FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.deleted_at;
+
+/** Holds `slug`'s gone file as sync holds a committed deletion it cannot prove (file_drift, deleted, file_gone). */
+async function holdGone(engine: BrainEngine, slug: string) {
+ const page = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");
+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation: source!.incarnation, path: `${slug}.md`, source_path: `${slug}.md`, slug,
+ page_id: Number(page.page.id), code: 'file_drift', message: `${slug}.md is held: file drift (deleted file_gone)`, upstream_version: null,
+ observed_at: new Date().toISOString(), run_id: null, mode: 'managed', meta: { recovery_version: RECOVERY_VERSION, side: 'deleted', state: 'file_gone', page_revision: page.revision } }));
+}
+
+for (const backend of testBackends()) describe(`[${backend}] GBRA-133: a page written after its file is never soft-deleted for the file's deletion`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(root, `notes/${name}.md`), note(`notes/${name}`, `The committed body of notes/${name}.`));
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');
+ };
+
+ test('file-drift and ghost-pages list it apart, and the soft-delete refuses it', () => managedBrain(async ({ engine, ctx, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ // notes/b moves on in the database after its import; then a commit deletes both files.
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`UPDATE pages SET compiled_truth = compiled_truth || ' Written later, in the database only.',
+ knowledge_revision = $1::uuid, revision_write_request_id = NULL WHERE source_id='default' AND slug='notes/b'`, [randomUUID()]), TEST_WRITE_ATTRIBUTION));
+ // notes/c and notes/d are older imports: no import record and no write request. notes/c is written after the deleting commit, notes/d is not.
+ const coordinated = (sql: string, params: unknown[] = []) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));
+ await coordinated(`DELETE FROM op_checkpoints WHERE op='sync-import-provenance'
+ AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug IN ('notes/c', 'notes/d'))`);
+ await coordinated("UPDATE pages SET revision_write_request_id = NULL WHERE source_id='default' AND slug IN ('notes/c', 'notes/d')");
+ git(root, 'rm', '-q', 'notes/a.md', 'notes/b.md', 'notes/c.md', 'notes/d.md'); git(root, 'commit', '-qm', 'cull a, b, c and d');
+ await coordinated(`UPDATE pages SET compiled_truth = compiled_truth || ' Written after the cull.', knowledge_revision = $1::uuid, updated_at = now() + interval '1 hour'
+ WHERE source_id='default' AND slug='notes/c'`, [randomUUID()]);
+ for (const slug of ['notes/a', 'notes/b', 'notes/c', 'notes/d']) await holdGone(engine, slug);
+
+ const drift = async (expect?: string) => (await repairRunner(engine, { apply: expect !== undefined, logger })).run('file-drift', await resolveRepairScope(engine, 'default'),
+ { explicit: true, sourceFlag: 'default', prefer: 'file', held: true, side: 'deleted', state: 'file_gone', provenance: 'deleted_by_commit', ...(expect ? { expect } : {}) });
+ const preview = await drift();
+ expect((preview.details!.pages as Array<{ slug: string; action?: string }>).map(page => [page.slug, page.action])).toEqual([['notes/a', 'soft_delete'], ['notes/d', 'soft_delete']]);
+ for (const slug of ['notes/b', 'notes/c']) {
+ const apart = preview.listing!.find(entry => entry.item === `default:${slug}`)!;
+ expect(apart.class).toBe('database_ahead_of_file');
+ expect(apart.detail).toContain('holds the only copy');
+ }
+ expect((await drift(preview.preview_hash!)).outcomes).toEqual({ repaired: 2 });
+ expect([await deletedAt(engine, 'notes/a'), await deletedAt(engine, 'notes/d')]).not.toContain(null);
+ expect([await deletedAt(engine, 'notes/b'), await deletedAt(engine, 'notes/c')]).toEqual([null, null]);
+
+ const ghosts = await (await repairRunner(engine, { apply: false, logger })).run('ghost-pages', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default' });
+ expect(ghosts.affected).toBe(0);
+ expect(ghosts.residuals).toMatchObject({ ghosts: 0, database_ahead: 2 });
+ expect(ghosts.listing!.map(entry => [entry.item, entry.class])).toEqual([['default:notes/b', 'database_ahead_of_file'], ['default:notes/c', 'database_ahead_of_file']]);
+
+ // The soft-delete itself refuses it, whatever approved it.
+ const now = await ghostPageNow(engine, 'default', 'notes/b');
+ expect(now.ghost).not.toBeNull();
+ const refused = await retireGhost(ctx, now.ghost!, now.owner!, async () => randomUUID());
+ expect(refused).toMatchObject({ applied: false, outcome: 'refused', reason: 'database_ahead_of_file' });
+ expect(await deletedAt(engine, 'notes/b')).toBeNull();
+ }, { databaseUrl, setup }), 300_000);
+});