Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712: detect and restore database edits a managed sync import overwrote
garrytan0e094b823e22
diff --git a/src/commands/doctor/checks/overwritten-edits.ts b/src/commands/doctor/checks/overwritten-edits.tsnew file mode 100644index 0000000000..d48ab3c5d5--- /dev/null+++ b/src/commands/doctor/checks/overwritten-edits.ts@@ -0,0 +1,57 @@+/**+ * #6712 follow-up `sync_overwritten_db_edits` (BRAIN): live pages whose database-only edit an incremental managed sync+ * replaced with a committed file edit and no `file_drift` hold (the #6887 bug, and managed sync before #6788). Read-only;+ * per source it runs `scanOverwrittenEdits` (`persistence/overwritten-edits.ts`, at most `OVERWRITE_SCAN_LIMIT` candidate+ * versions, newest first) and reports each source's count and first slugs. `warn` only for `high` findings; `unknown`+ * ones (no persistence outcome on the writer's receipt, the import's content no longer readable, a segmented version)+ * are counted separately and never warn. The fix previews `gbrain repair overwritten-edits`, which writes nothing.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { scanOverwrittenEdits, type OverwriteSourceScan } from '../../../core/persistence/overwritten-edits.ts';++const DOCS = 'docs/guides/repair.md#overwritten-edits';+/** Slugs listed per source. */+const SLUGS_SHOWN = 10;++async function runOverwrittenEdits(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const engine = connectedEngine(ctx);+ const sourceIds = ctx.sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const scans: OverwriteSourceScan[] = [];+ for (const sourceId of sourceIds) scans.push(await scanOverwrittenEdits(engine, sourceId));+ const high = scans.reduce((sum, scan) => sum + scan.high, 0);+ const unknown = scans.reduce((sum, scan) => sum + scan.unknown, 0);+ const details = { count: high, unknown, truncated: scans.some(scan => scan.truncated), docs: DOCS,+ sources: scans.filter(scan => scan.edits.length || scan.truncated).map(scan => ({ source_id: scan.source_id, count: scan.high, unknown: scan.unknown, truncated: scan.truncated,+ slugs: scan.edits.filter(edit => edit.confidence === 'high').slice(0, SLUGS_SHOWN).map(edit => edit.slug),+ unknown_slugs: scan.edits.filter(edit => edit.confidence === 'unknown').slice(0, SLUGS_SHOWN).map(edit => ({ slug: edit.slug, reason: edit.reason })) })) };+ const bounded = details.truncated ? ' (bounded scan: more candidate versions were not read)' : '';+ if (!high) {+ checks.push({ name: 'sync_overwritten_db_edits', status: 'ok', details,+ message: unknown ? `No page shows a database edit that a sync import provably overwrote; ${unknown} page(s) could not be classified (unknown, listed in details.sources[].unknown_slugs)${bounded}.`+ : `No page shows a database edit that a sync import overwrote${bounded}.` });+ return checks;+ }+ const found = scans.filter(scan => scan.high);+ const first = found[0]!;+ const sample = first.edits.find(edit => edit.confidence === 'high')!;+ const preview = ['gbrain', 'repair', 'overwritten-edits', '--source', first.source_id, '--json'];+ checks.push({ name: 'sync_overwritten_db_edits', status: 'warn', details,+ message: `${high} page(s) lost a database edit to an incremental sync that published a committed file edit over it without a file_drift hold `+ + `(${found.map(scan => `${scan.source_id}: ${scan.high}`).join('; ')}; e.g. ${found.flatMap(scan => scan.edits.filter(edit => edit.confidence === 'high').slice(0, 3).map(edit => `${scan.source_id}:${edit.slug}`)).slice(0, 5).join(', ')})`+ + `${unknown ? `; ${unknown} more could not be classified (unknown)` : ''}${bounded}. Each edit is still in the page's history. Preview the restore with `+ + `gbrain repair overwritten-edits --source ${first.source_id}; it shows both versions and writes nothing.`,+ fix: agentFix(preview, 'Lists each page with the database edit, the sync import that replaced it and a diff; it writes nothing. Restoring is the user\'s call.',+ 'sync_overwritten_db_edits', { ask_user: true, docs: DOCS,+ user_message: `${high} page(s) (for example ${sample.slug}) had a database edit replaced by a later file edit during sync, with no warning. `+ + 'The edit is still in history. Should I show you both versions and restore the ones you want? A restored page keeps its committed file unchanged and that file is held until you choose a side.' }) });+ } catch (error) {+ checks.push(checkError('sync_overwritten_db_edits', 'check page history for database edits a sync import overwrote', error, { details: { count: 'unknown', docs: DOCS } }));+ }+ return checks;+}++export const overwrittenEditsEntry: DoctorEntry = { name: 'sync_overwritten_db_edits', emits: ['sync_overwritten_db_edits'], run: runOverwrittenEdits };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex ddd45dfba6..3ccc21acbe 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -120,6 +120,7 @@ import { ghostPagesEntry } from './checks/ghost-pages.ts';import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';import { purgeParkedPagesEntry } from './checks/purge-parks.ts';import { missingRecordedFilesEntry } from './checks/missing-recorded-files.ts';+import { overwrittenEditsEntry } from './checks/overwritten-edits.ts';import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';import { managedSyncBlockedEntry } from './checks/managed-sync-blocked.ts';import { atomHeldFailedEntry } from './checks/atom-holds.ts';@@ -241,6 +242,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [renameIdentityDowngradesEntry,purgeParkedPagesEntry,missingRecordedFilesEntry,+ overwrittenEditsEntry,syncConfigKeysEntry,fenceIntegrityEntry,searchModeEntry,diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 8468a9aa57..1110faea73 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -135,7 +135,7 @@ const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--ski/** Flags only some kinds accept, with the kinds that do. */const KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages'],- '--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],+ '--slug': ['fences', 'file-drift', 'overwritten-edits'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],};diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 458875bdd1..3a04fedd45 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -202,6 +202,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',+ // #6712: live pages whose database-only edit an incremental sync overwrote without a hold (doctor/checks/overwritten-edits.ts).+ 'sync_overwritten_db_edits','unified_multimodal_coverage','unverified_extractions','voice_gate_health',diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex cc229fa2fa..62fdd0ea1a 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -8,7 +8,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';+ databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore';autoLinkTrusted?: boolean;restrictedNamespace?: boolean;sourceId: string;diff --git a/src/core/persistence/overwritten-edits.ts b/src/core/persistence/overwritten-edits.tsnew file mode 100644index 0000000000..c70c3152c7--- /dev/null+++ b/src/core/persistence/overwritten-edits.ts@@ -0,0 +1,138 @@+/**+ * #6712 follow-up: pages an incremental managed sync silently overwrote. Before #6887, `classifyBaseline`+ * (sync-prescreen.ts) guarded a page that moved in both the database and Git only in a tree walk, so a plain delta sync+ * published a committed file edit over a database-only edit (a `put_page` with `sync.write_through` off) with no+ * `file_drift` hold and no backup. Managed sync before #6788 had no drift guard at all. The edit survives as the page+ * version the import archived. This module finds it from durable rows only, so it finds damage done before the fix too:+ *+ * - `page_versions.write_request_id` names the request that wrote the lost revision and `archived_write_request_id` the+ * request whose write archived it (attribution-schema.ts, `STAMP_VERSION_FUNCTION`);+ * - the archiving request is a managed-sync import: intent kind `managed_sync_import`, or, once receipt compaction nulled+ * the intent, operation `submit_job` with `outcome.imported_file` and no `outcome.connector_database`;+ * - the lost revision's writer published no file: its committed receipt says `outcome.persistence.mode = 'database'`+ * (coordinator.ts `decoratePublicationOutcome`), it is not itself an import, no `git` effect carries that revision, and+ * it was not a read-only mirror write (upstream wins there by design);+ * - the import replaced it with different content: the import's own revision (its version row, or the live page) differs+ * from the lost one (`reconcileCanonical` digest), and no later revision of the page holds the lost content again.+ *+ * `high`: every condition holds and every version involved is inline. `unknown`: the writer receipt carries no+ * `persistence` outcome, the import's content is no longer readable, or a version is segmented. A lost revision with no+ * recorded writer (pre-attribution, classic sync, unattributed maintenance) is not reported: it cannot be told apart from+ * ordinary sync history. Read-only and bounded (`OVERWRITE_SCAN_LIMIT` candidate versions per source, newest first).+ */+import type { BrainEngine } from '../engine.ts';+import type { PageType } from '../types.ts';+import { digest } from './digest.ts';+import { reconcileCanonical } from './reconcile-merge.ts';++/** Candidate versions read per source, newest first. */+export const OVERWRITE_SCAN_LIMIT = 500;++export type OverwriteConfidence = 'high' | 'unknown';+export type OverwriteUnknownReason = 'no_persistence_outcome' | 'import_content_unreadable' | 'segmented';++/** The content fields of a page or page version that a restore brings back. */+export interface OverwriteContent { title: string; type: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown>; tags: string[] }++export interface OverwrittenEdit {+ source_id: string; slug: string; page_id: number;+ /** The archived version holding the database edit; a restore reverts to it. */+ version_id: number; lost_revision: string;+ db_request_id: string; db_operation: string; import_request_id: string; imported_at: string | null;+ confidence: OverwriteConfidence; reason?: OverwriteUnknownReason;+ /** The page's live revision when scanned (a restore is bound to it). */+ page_revision: string;+ /** Digest of the lost content; null for a segmented version. */+ lost_digest: string | null;+ /** Older open overwrites of the same page (the newest one is the reported edit). */+ earlier: number;+}++export interface OverwriteSourceScan { source_id: string; high: number; unknown: number; edits: OverwrittenEdit[]; truncated: boolean }++interface ContentRow {+ body_storage: string | null; title: string | null; type: string | null; compiled_truth: string | null; timeline: string | null;+ frontmatter: Record<string, unknown> | string | null; tags: unknown;+}+interface CandidateRow extends ContentRow {+ version_id: number | string; page_id: number | string; slug: string; lost_revision: string; db_request_id: string; db_operation: string;+ import_request_id: string; imported_at: string | Date | null; db_outcome_known: boolean;+}+interface VersionRow extends ContentRow { id: number | string; page_id: number | string; write_request_id: string | null }+interface LiveRow extends ContentRow { page_id: number | string; revision: string; revision_write_request_id: string | null }++const MANAGED_IMPORT = (r: string) => `(${r}.intent->>'kind' = 'managed_sync_import'+ OR (${r}.intent IS NULL AND ${r}.outcome->>'imported_file' = 'true' AND NOT (${r}.outcome ? 'connector_database')))`;+const CONTENT_COLUMNS = (v: string) => `${v}.body_storage, ${v}.title, ${v}.type, ${v}.compiled_truth, ${v}.timeline, ${v}.frontmatter`;++const parsed = (value: unknown) => typeof value === 'string' ? JSON.parse(value) as unknown : value;++/** The comparable content of an inline page or version row; null when it is segmented (its body lives in segments). */+export function overwriteContent(row: ContentRow): OverwriteContent | null {+ if (row.body_storage === 'segmented' || row.compiled_truth === null) return null;+ const tags = parsed(row.tags);+ return { title: row.title ?? '', type: row.type ?? '', compiled_truth: row.compiled_truth, timeline: row.timeline ?? '',+ frontmatter: (parsed(row.frontmatter) ?? {}) as Record<string, unknown>, tags: Array.isArray(tags) ? [...new Set(tags.map(String))].sort() : [] };+}++export const overwriteDigest = (content: OverwriteContent) => digest(reconcileCanonical({ title: content.title, type: content.type as PageType,+ compiled_truth: content.compiled_truth, timeline: content.timeline, frontmatter: content.frontmatter }, content.tags));++const sameContent = (row: ContentRow, lostDigest: string) => {+ const content = overwriteContent(row);+ return content !== null && overwriteDigest(content) === lostDigest;+};++/** The source's open overwrites of live pages (the newest per page), from at most `limit` candidate versions; `slugs` narrows it. */+export async function scanOverwrittenEdits(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string,+ opts: { limit?: number; slugs?: readonly string[] } = {}): Promise<OverwriteSourceScan> {+ const limit = opts.limit ?? OVERWRITE_SCAN_LIMIT;+ const candidates = await engine.executeRaw<CandidateRow>(`SELECT v.id AS version_id, v.page_id, p.slug, v.knowledge_revision::text AS lost_revision,+ w.id::text AS db_request_id, w.operation AS db_operation, s.id::text AS import_request_id, s.completed_at AS imported_at,+ COALESCE(w.outcome->'persistence'->>'mode' = 'database', false) AS db_outcome_known, ${CONTENT_COLUMNS('v')}, v.tags+ FROM pages p+ JOIN page_versions v ON v.page_id = p.id+ JOIN persistence_requests s ON s.id = v.archived_write_request_id+ JOIN persistence_requests w ON w.id = v.write_request_id+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND ($3::text[] IS NULL OR p.slug = ANY($3::text[]))+ AND s.state = 'committed' AND s.operation = 'submit_job' AND s.source_id = p.source_id AND ${MANAGED_IMPORT('s')}+ AND w.state = 'committed' AND w.source_id = p.source_id AND NOT (w.operation = 'submit_job' AND COALESCE(w.outcome->>'imported_file', '') = 'true')+ AND (w.outcome->'persistence'->>'mode' = 'database'+ OR (NOT (COALESCE(w.outcome, '{}'::jsonb) ? 'persistence') AND COALESCE(w.outcome->'write_through'->>'written', 'false') <> 'true'))+ AND COALESCE(w.outcome->'write_through'->>'skipped', '') <> 'mirror_read_only' AND COALESCE(w.outcome->>'storage', '') <> 'database_only'+ AND NOT EXISTS (SELECT 1 FROM persistence_effects e WHERE e.kind = 'git' AND e.revision = v.knowledge_revision)+ ORDER BY v.id DESC LIMIT $2`, [sourceId, limit + 1, opts.slugs?.length ? [...opts.slugs] : null]);+ const truncated = candidates.length > limit;+ const rows = candidates.slice(0, limit);+ if (!rows.length) return { source_id: sourceId, high: 0, unknown: 0, edits: [], truncated };+ const pageIds = [...new Set(rows.map(row => Number(row.page_id)))];+ const later = await engine.executeRaw<VersionRow>(`SELECT v.id, v.page_id, v.write_request_id::text AS write_request_id, ${CONTENT_COLUMNS('v')}, v.tags+ FROM page_versions v WHERE v.page_id = ANY($1::int[]) AND v.id > $2 ORDER BY v.id`, [pageIds, Math.min(...rows.map(row => Number(row.version_id)))]);+ const live = await engine.executeRaw<LiveRow>(`SELECT p.id AS page_id, p.knowledge_revision::text AS revision, p.revision_write_request_id::text AS revision_write_request_id,+ ${CONTENT_COLUMNS('p')}, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id = p.id), '[]'::jsonb) AS tags+ FROM pages p WHERE p.id = ANY($1::int[])`, [pageIds]);+ const pages = new Map(live.map(row => [Number(row.page_id), row]));+ const newest = new Map<number, OverwrittenEdit>();+ for (const row of rows) {+ const pageId = Number(row.page_id), versionId = Number(row.version_id);+ const page = pages.get(pageId);+ if (!page) continue;+ const after = later.filter(entry => Number(entry.page_id) === pageId && Number(entry.id) > versionId);+ const imported: ContentRow | undefined = after.find(entry => entry.write_request_id === row.import_request_id)+ ?? (page.revision_write_request_id === row.import_request_id ? page : undefined);+ const lost = overwriteContent(row);+ const lostDigest = lost ? overwriteDigest(lost) : null;+ if (lostDigest !== null && imported && sameContent(imported, lostDigest)) continue;+ if (lostDigest !== null && [...after, page].some(entry => entry !== imported && sameContent(entry, lostDigest))) continue;+ const reason: OverwriteUnknownReason | undefined = !lost || (imported && !overwriteContent(imported)) || !overwriteContent(page) ? 'segmented'+ : !imported ? 'import_content_unreadable' : !row.db_outcome_known ? 'no_persistence_outcome' : undefined;+ const kept = newest.get(pageId);+ if (kept) { kept.earlier++; continue; }+ newest.set(pageId, { source_id: sourceId, slug: row.slug, page_id: pageId, version_id: versionId, lost_revision: row.lost_revision,+ db_request_id: row.db_request_id, db_operation: row.db_operation, import_request_id: row.import_request_id,+ imported_at: row.imported_at === null ? null : new Date(row.imported_at).toISOString(),+ confidence: reason ? 'unknown' : 'high', ...(reason ? { reason } : {}), page_revision: page.revision, lost_digest: lostDigest, earlier: 0 });+ }+ const edits = [...newest.values()];+ return { source_id: sourceId, high: edits.filter(edit => edit.confidence === 'high').length, unknown: edits.filter(edit => edit.confidence === 'unknown').length, edits, truncated };+}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 8fca85d5e4..6f7ec00ab6 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -198,7 +198,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 }): Promise<Record<string, unknown>> {+ input: { operation: string; params: Record<string, unknown>; waitMs?: number; managedFileImport?: true; timelineSection?: TimelineSection; databaseOnly?: 'overwrite_restore' }): Promise<Record<string, unknown>> {assertPersistenceAccepting(ctx.engine);// #6007: wait_ms is a reply deadline from arrival, never part of the write's identity.const arrived = performance.now();@@ -234,7 +234,9 @@ export async function submitPageMutation(ctx: OperationContext,* the admission to submit. `put_pages` admits several of these together.*/export async function preparePageAdmission(ctx: OperationContext,- input: { operation: string; params: Record<string, unknown>; managedFileImport?: true; batch?: PageBatchMember; timelineSection?: TimelineSection }+ 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' }): 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)) ||@@ -355,9 +357,10 @@ export async function preparePageAdmission(ctx: OperationContext,let binding = boundAtStart;const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);const configuredWriteThrough = !/^(false|0|off|no)$/i.test(writeThroughSetting ?? 'true');- const writeThrough = configuredWriteThrough && !sandbox;+ const writeThrough = configuredWriteThrough && !sandbox && !input.databaseOnly;const root = source.local_path || repoPath;if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';+ else if (input.databaseOnly) authority.databaseOnlyReason = input.databaseOnly;else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';else if (!root && !binding) authority.databaseOnlyReason = 'no_repo_configured';if (p.local_dir !== undefined) {diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex f4f2b3db63..fe6c3e9669 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' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes' | 'overwritten-edits';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 6b63c6a6d5..9308cb72a5 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -37,7 +37,7 @@ import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.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', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'] 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', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'overwritten-edits'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/overwritten-edits.ts b/src/core/repair/overwritten-edits.tsnew file mode 100644index 0000000000..c536fe673a--- /dev/null+++ b/src/core/repair/overwritten-edits.ts@@ -0,0 +1,191 @@+/**+ * `gbrain repair overwritten-edits [--source <id>] [--slug <slug>...]` (#6712 follow-up): restore database edits an+ * incremental managed sync published a committed file edit over, with no `file_drift` hold (the #6887 bug, and managed+ * sync before #6788). Detection is `persistence/overwritten-edits.ts`; only its `high` findings are restorable, and+ * `unknown` ones are listed with their reason.+ *+ * Explicit-only and preview-bound: the preview lists each page with the database edit's version, the request that wrote+ * it, the import that replaced it and a diff of the live page against the restored edit, and saves the set under its+ * hash. `--apply --expect <hash>` restores exactly that set: each page goes through `revert_version` of the archived+ * version (the normal coordinated write), bound to the page revision the preview saw (`expected_revision`), so a page+ * that moved since is `changed_since_preview`. The restore publishes to the database only (`databaseOnly:+ * 'overwrite_restore'`), so it never rewrites the committed file. When the committed file then differs from the restored+ * page, the file is held `file_drift` (sync never publishes it over the restored edit; `gbrain repair file-drift` is how a+ * person picks the winner).+ */+import { join, relative, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { resolveSourceLocalFilePath, serializePageToMarkdown } from '../markdown.ts';+import { OperationError, opError, type OperationContext } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { unifiedDiff } from '../skillpack/diff-text.ts';+import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';+import { localHostId } from '../persistence/identity.ts';+import { getWorktreeBinding } from '../persistence/ownership.ts';+import { fileMatchesSnapshot } from '../persistence/page-prepare.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { clearApprovedSet, loadApprovedSet, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { overwriteContent, overwriteDigest, scanOverwrittenEdits, type OverwrittenEdit } from '../persistence/overwritten-edits.ts';+import { readTreeBlobs, readBlobContents } from '../persistence/sync-blobs.ts';+import { syncGit, syncGitPath } from '../persistence/sync-discovery.ts';+import { readSyncImportProvenances, writeGitHold } from '../persistence/sync-holds.ts';+import { fileDriftHold } from '../persistence/sync-page-fault.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairScope } from './core.ts';++const DOCS = 'docs/guides/repair.md#overwritten-edits';+const COMMAND = 'gbrain repair overwritten-edits';+/** Diff lines kept per page in the preview details. */+const DIFF_LINES = 200;++type ApprovedEdit = Pick<OverwrittenEdit, 'source_id' | 'slug' | 'page_id' | 'version_id' | 'page_revision' | 'lost_digest' | 'db_request_id' | 'import_request_id'> & { selection: string[] };+interface EditItem extends RepairItem { edit: ApprovedEdit; hash: string; last: boolean }+interface PreviewEdit { source_id: string; slug: string; version_id: number; db_request_id: string; db_operation: string; import_request_id: string;+ imported_at: string | null; earlier: number; added: number; removed: number; diff: string }++const previewCommand = (scope: RepairScope, slugs: readonly string[]) =>+ [COMMAND, ...(scope.source_ids.length === 1 ? ['--source', scope.source_ids[0]!] : []), ...slugs.flatMap(slug => ['--slug', slug])].join(' ');+const selectionOf = (scope: RepairScope, slugs: readonly string[]) => [...scope.source_ids, '--', ...[...new Set(slugs)].sort()];+const hashOf = (scope: RepairScope, selection: string[], edits: Array<Pick<OverwrittenEdit, 'source_id' | 'slug' | 'version_id' | 'page_revision' | 'lost_digest'>>) =>+ previewHash({ kind: 'overwritten-edits-v1', brain_id: scope.brain_id, selection, edits: edits.map(edit => [edit.source_id, edit.slug, edit.version_id, edit.page_revision, edit.lost_digest]) });++async function scanScope(engine: BrainEngine, scope: RepairScope, slugs: readonly string[]) {+ const scans = [];+ for (const sourceId of scope.source_ids) scans.push(await scanOverwrittenEdits(engine, sourceId, { slugs }));+ return scans;+}++/** The archived version's content rendered as `revert_version` renders it, or null when it is no longer the previewed edit. */+async function versionMarkdown(engine: BrainEngine, edit: Pick<OverwrittenEdit, 'page_id' | 'version_id' | 'lost_digest'>, page: Parameters<typeof serializePageToMarkdown>[0]): Promise<string | null> {+ const [row] = await engine.executeRaw<{ body_storage: string | null; title: string | null; type: string | null; compiled_truth: string | null; timeline: string | null; frontmatter: Record<string, unknown> | null; tags: unknown }>(+ 'SELECT body_storage, title, type, compiled_truth, timeline, frontmatter, tags FROM page_versions WHERE id=$1 AND page_id=$2', [edit.version_id, edit.page_id]);+ const content = row ? overwriteContent(row) : null;+ if (!content || overwriteDigest(content) !== edit.lost_digest) return null;+ return serializePageToMarkdown({ ...page, title: content.title, type: content.type, compiled_truth: content.compiled_truth, timeline: content.timeline, frontmatter: content.frontmatter }, content.tags);+}++async function previewEdit(engine: BrainEngine, edit: OverwrittenEdit): Promise<PreviewEdit | null> {+ const snapshot = await engine.readPageSnapshot(edit.slug, { sourceId: edit.source_id });+ if (!snapshot || snapshot.revision !== edit.page_revision) return null;+ const restored = await versionMarkdown(engine, edit, snapshot.page);+ if (restored === null) return null;+ const diff = unifiedDiff(serializePageToMarkdown(snapshot.page, snapshot.tags), restored, { oldPath: `${edit.slug} (live page, from the sync import)`, newPath: `${edit.slug} (database edit, version ${edit.version_id})` });+ const lines = diff.split('\n');+ return { source_id: edit.source_id, slug: edit.slug, version_id: edit.version_id, db_request_id: edit.db_request_id, db_operation: edit.db_operation,+ import_request_id: edit.import_request_id, imported_at: edit.imported_at, earlier: edit.earlier,+ added: lines.filter(line => line.startsWith('+') && !line.startsWith('+++')).length, removed: lines.filter(line => line.startsWith('-') && !line.startsWith('---')).length,+ diff: lines.length > DIFF_LINES ? [...lines.slice(0, DIFF_LINES), `... ${lines.length - DIFF_LINES} more diff line(s)`].join('\n') : diff };+}++const item = (edit: ApprovedEdit, index: number, hash: string, last: boolean): EditItem => ({ cursor: { phase: 0, id: index + 1 }, source_id: edit.source_id,+ slug: edit.slug, chars: 0, action: `restore_version:${edit.version_id}`, edit, hash, last });++export const overwrittenEditsRepair: RepairHandler = {+ kind: 'overwritten-edits',+ outcomeItemsLimit: 1000,+ async plan(engine, scope, after, opts) {+ const slugs = opts?.slugs ?? [];+ const command = previewCommand(scope, slugs);+ const selection = selectionOf(scope, slugs);+ if (!opts?.apply) {+ const scans = await scanScope(engine, scope, slugs);+ const previews: PreviewEdit[] = [], approved: ApprovedEdit[] = [], unknown: OverwrittenEdit[] = [];+ const residuals: Record<string, number> = {};+ for (const edit of scans.flatMap(scan => scan.edits)) {+ if (edit.confidence !== 'high') { unknown.push(edit); residuals[`unknown_${edit.reason}`] = (residuals[`unknown_${edit.reason}`] ?? 0) + 1; continue; }+ const preview = await previewEdit(engine, edit);+ if (!preview) { residuals.changed_during_preview = (residuals.changed_during_preview ?? 0) + 1; continue; }+ previews.push(preview);+ approved.push({ source_id: edit.source_id, slug: edit.slug, page_id: edit.page_id, version_id: edit.version_id, page_revision: edit.page_revision,+ lost_digest: edit.lost_digest, db_request_id: edit.db_request_id, import_request_id: edit.import_request_id, selection });+ }+ for (const scan of scans) if (scan.truncated) residuals.scan_truncated = (residuals.scan_truncated ?? 0) + 1;+ const hash = hashOf(scope, selection, approved);+ if (approved.length) await saveApprovedSet<ApprovedEdit>(engine, { command: 'overwritten-edits', hash }, approved);+ return { items: approved.map((edit, index) => item(edit, index, hash, index === approved.length - 1)), preview_hash: hash, residuals,+ listing: [...previews.map(edit => ({ item: `${edit.source_id}:${edit.slug}`, class: 'restore_database_edit',+ detail: `version ${edit.version_id} (${edit.db_operation} request ${edit.db_request_id}) was replaced by sync import ${edit.import_request_id}${edit.imported_at ? ` at ${edit.imported_at}` : ''}; restoring it changes +${edit.added}/-${edit.removed} line(s)${edit.earlier ? `; ${edit.earlier} earlier overwrite(s) of this page are not restored` : ''}` })),+ ...unknown.map(edit => ({ item: `${edit.source_id}:${edit.slug}`, class: 'unknown', detail: `${edit.reason}: version ${edit.version_id}, replaced by sync import ${edit.import_request_id}; not restored automatically` }))],+ ...(approved.length ? { warnings: ['Each restore writes the database edit as a new page revision without touching the committed file; a file that then differs from the page is held file_drift until you pick a side with gbrain repair file-drift.'] } : {}),+ details: { docs: DOCS, edits: previews, unknown: unknown.map(edit => ({ source_id: edit.source_id, slug: edit.slug, version_id: edit.version_id, reason: edit.reason })) } };+ }+ if (!opts.expect) {+ throw opError('invalid_params', `${COMMAND} --apply restores only the set a preview printed.`,+ `Preview first: ${command} — show the user both versions, then run the apply command it prints: ${command} --apply --expect <preview-hash>`,+ { fix: readFix('Previews the database edits a sync import overwrote; writes nothing.', { argv: command.split(' ').concat('--json') }), docs: DOCS });+ }+ const loaded = await loadApprovedSet<ApprovedEdit>(engine, { command: 'overwritten-edits', hash: opts.expect, previewCommand: command,+ emptyHash: async () => hashOf(scope, selection, (await scanScope(engine, scope, slugs)).flatMap(scan => scan.edits).filter(edit => edit.confidence === 'high')) });+ if (loaded.items.some(edit => JSON.stringify(edit.selection) !== JSON.stringify(selection))) {+ throw opError('preview_changed', `The preview ${opts.expect} was made for another selection.`, `Re-run the preview: ${command}`);+ }+ const items = loaded.items.map((edit, index) => item(edit, index, opts.expect!, index === loaded.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { edit, hash, last } = entry as EditItem;+ try {+ return await restoreEdit(ctx, entry, edit);+ } finally {+ if (last) await clearApprovedSet(ctx.engine, { command: 'overwritten-edits', hash });+ }+ },+ render(details) {+ const lines: string[] = [];+ for (const edit of (details.edits ?? []) as PreviewEdit[]) lines.push(` ${edit.source_id}:${edit.slug}: live page (-) against the database edit it restores (+):`, ...edit.diff.split('\n').map(line => ` ${line}`));+ for (const edit of (details.unknown ?? []) as Array<{ source_id: string; slug: string; version_id: number; reason: string }>) {+ lines.push(` unknown ${edit.source_id}:${edit.slug} (version ${edit.version_id}): ${edit.reason}; compare it with gbrain history ${edit.slug} --source-id ${edit.source_id} before restoring it by hand`);+ }+ lines.push(` guide: ${details.docs}`);+ return lines;+ },+};++const changed = (reason: string, detail: Record<string, unknown> = {}): RepairItemOutcome =>+ ({ applied: false, outcome: 'changed_since_preview', reason, detail: { ...detail, next: `run ${COMMAND} again for a new preview` } });++async function restoreEdit(ctx: OperationContext, entry: RepairItem, edit: ApprovedEdit): Promise<RepairItemOutcome> {+ const engine = ctx.engine;+ const snapshot = await engine.readPageSnapshot(edit.slug, { sourceId: edit.source_id });+ if (!snapshot || Number(snapshot.page.id) !== edit.page_id || snapshot.revision !== edit.page_revision) return changed('page_moved', { page_revision: snapshot?.revision ?? null });+ if (await versionMarkdown(engine, edit, snapshot.page) === null) return changed('version_changed');+ const requestId = await repairRequestId(ctx, 'overwritten-edits', entry, edit.page_revision);+ try {+ await submitPageMutation({ ...ctx, sourceId: edit.source_id }, { operation: 'revert_version', databaseOnly: 'overwrite_restore',+ params: { slug: edit.slug, source_id: edit.source_id, version_id: edit.version_id, expected_revision: edit.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.code, { request_id: requestId });+ throw error;+ }+ const hold = await holdDivergentFile(engine, edit, requestId);+ return { applied: true, outcome: hold.held ? 'restored_file_held' : 'restored', detail: { request_id: requestId, version_id: edit.version_id, ...hold } };+}++/**+ * After a restore: when this host owns the source's checkout and the committed file at HEAD differs from the restored+ * page, hold it `file_drift` so no sync publishes it over the edit again. Identifiers and revisions only.+ */+async function holdDivergentFile(engine: BrainEngine, edit: ApprovedEdit, requestId: string): Promise<{ held: boolean; file?: string; why?: string; sides?: 'database' | 'both' }> {+ const snapshot = await engine.readPageSnapshot(edit.slug, { sourceId: edit.source_id });+ if (!snapshot?.page.source_path) return { held: false, why: 'no_recorded_file' };+ const binding = await getWorktreeBinding(engine, edit.source_id);+ if (!binding?.local_path || binding.owner_host_id !== localHostId()) return { held: false, why: 'checkout_not_on_this_host' };+ const root = join(binding.local_path, binding.relative_path);+ const mode = await scannerSlugRootMode(engine, edit.source_id, root);+ const target = resolveSourceLocalFilePath(root, snapshot.page.source_path, edit.slug, mode);+ if (!target) return { held: false, why: 'no_recorded_file' };+ const gitRoot = syncGit(root, ['rev-parse', '--show-toplevel']).trim();+ const relativePath = relative(root, target).split(sep).join('/');+ const gitPath = syncGitPath({ root, gitRoot }, relativePath);+ const blob = readTreeBlobs(gitRoot, 'HEAD', [gitPath]).get(gitPath);+ if (!blob) return { held: false, file: relativePath, why: 'file_not_committed' };+ const bytes = readBlobContents(gitRoot, [blob]).get(blob.oid);+ if (bytes === undefined) return { held: false, file: relativePath, why: 'file_over_read_bound' };+ if (await fileMatchesSnapshot(engine, edit.slug, bytes, snapshot, scannerSourcePath(root, target, mode))) return { held: false, file: relativePath, why: 'file_matches' };+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [edit.source_id]);+ const record = (await readSyncImportProvenances(engine, edit.source_id, source!.incarnation, [edit.page_id])).get(edit.page_id);+ const sides = record?.disk_blob_oid === blob.oid ? 'database' as const : 'both' as const;+ const held = fileDriftHold({ path: relativePath, sourcePath: snapshot.page.source_path, action: 'import', working: false }, edit.slug, edit.page_id,+ { content: bytes, blobOid: blob.oid }, { sides, revision: snapshot.revision, proof: { request_id: requestId, operation: 'revert_version', revision: snapshot.revision }, sharedOrigin: false });+ await engine.transaction(tx => writeGitHold(tx, { ...held, source_id: edit.source_id, incarnation: source!.incarnation, observed_at: new Date().toISOString(), run_id: null, mode: 'managed' }));+ return { held: true, file: relativePath, sides };+}diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 3426357cd0..f8770580da 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -68,6 +68,7 @@ import { stuckRecoveryRepair } from './stuck-recovery.ts';import { ghostPagesRepair, GHOST_CONSENT_TEXT, GHOST_CONSEQUENCES, GHOST_PURGE_FUSE_HOURS } from './ghost-pages.ts';import { receiptCompactionRepair } from './receipt-compaction.ts';import { aliasesRepair } from './aliases.ts';+import { overwrittenEditsRepair } from './overwritten-edits.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -354,6 +355,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'of a page that still exists is never touched. Each target slug is rechecked under its page lock; coordinated maintenance write on a managed '+ 'brain, no journal admission. Runs only when named.',},+ 'overwritten-edits': {+ handler: overwrittenEditsRepair, embeds: 'effect', checks: ['sync_overwritten_db_edits'], explicit_only: true, preview_bound: true,+ summary: 'Restore database edits an incremental managed sync overwrote with a committed file edit and no file_drift hold (#6712, fixed by #6887). '+ + 'Only what the records prove: a database-only revision (its receipt published no file) archived by a managed-sync import that wrote different '+ + 'content, with no later revision holding the edit again. The preview shows a diff of the live page against the edit; --apply --expect <hash> '+ + 'reverts each page to that version through a revision-bound, database-only revert_version, then holds the committed file file_drift when it '+ + 'differs, so sync never publishes it over the edit. Narrow with --slug. Runs only when named.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --git a/test/overwritten-edits-6712.test.ts b/test/overwritten-edits-6712.test.tsnew file mode 100644index 0000000000..c8d7fd171b--- /dev/null+++ b/test/overwritten-edits-6712.test.ts@@ -0,0 +1,144 @@+/**+ * #6712 follow-up: find and restore database edits an incremental managed sync silently overwrote.+ *+ * The overwrite is seeded the way it happens on a released brain: a database-only `put_page` (`sync.write_through`+ * off), then a committed edit of the same file, then an incremental sync that publishes the file over the edit with no+ * hold. On a base without #6887 any page reproduces it; the seed also drops the page's import provenance record (a page+ * last imported before PR 0 recorded one), which no released classifier guards in a delta sync, so the seed reproduces+ * with or without #6887 and these tests never depend on that fix.+ *+ * Protects:+ * - a seeded overwrite is detected `high` (also after receipt compaction nulled every intent), and `repair+ * overwritten-edits` restores the edit through a database-only revert bound to the preview, leaves the committed file+ * as it is, holds that file `file_drift`, and the next sync keeps the edit; the restored page is no longer reported;+ * - a normal sync-written history is not flagged: a file-only edit, a write-through edit later edited in Git, and a+ * database-only edit no import replaced;+ * - a page that moved after the preview is `changed_since_preview`: nothing is restored and no hold is written.+ *+ * PGLite always; Postgres too when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync, 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 { compactWriteReceipts } from '../src/core/persistence/journal.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 { scanOverwrittenEdits } from '../src/core/persistence/overwritten-edits.ts';+import { readGitHold, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { waitFor } from './helpers/wait-for.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 = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const logger = { info() {}, warn() {}, error() {} };+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const slug of ['notes/a', 'notes/b', 'notes/c', 'notes/d']) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));+ commit(root, 'notes');+};+const incarnationOf = async (engine: BrainEngine) => (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text FROM sources WHERE id='default'"))[0]!.incarnation;+const holdOf = async (engine: BrainEngine, path: string) => readGitHold(engine, 'default', await incarnationOf(engine), path);+const bodyOf = async (engine: BrainEngine, slug: string) => (await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth ?? '';+const revisionOf = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision;+async function putPage(engine: BrainEngine, ctx: OperationContext, slug: string, body: string): Promise<void> {+ const requestId = randomUUID();+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: requestId, expected_revision: await revisionOf(engine, slug), content: note(slug, body) } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed', { timeoutMs: 30_000 });+}+/** A database-only edit of `slug`, then a committed edit of its file and an incremental sync that publishes it over the edit. */+async function seedOverwrite(engine: BrainEngine, ctx: OperationContext, root: string, slug: string): Promise<void> {+ await engine.setConfig('sync.write_through', 'false');+ await putPage(engine, ctx, slug, 'DBONLYMARKER the agent edit.');+ await engine.setConfig('sync.write_through', 'true');+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `default:${await incarnationOf(engine)}:${page!.id}`]);+ writeFileSync(join(root, `${slug}.md`), note(slug, 'The second committed body.'));+ commit(root, `edit ${slug}`);+ await performManagedSync(engine, OPTS);+ expect(await bodyOf(engine, slug)).toContain('The second committed body.');+}+const repair = async (engine: BrainEngine, opts: { expect?: string; slugs?: string[] } = {}) =>+ (await repairRunner(engine, { apply: opts.expect !== undefined, logger })).run('overwritten-edits', await resolveRepairScope(engine, 'default'),+ { explicit: true, sourceFlag: 'default', ...(opts.slugs ? { slugs: opts.slugs } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });++for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATABASE_URL] : [undefined]) describe(`#6712 overwritten database edits (${databaseUrl ? 'postgres' : 'pglite'})`, () => {+ test('a seeded overwrite is detected and restored without publishing over the committed file', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await seedOverwrite(engine, ctx, root, 'notes/a');++ const scan = await scanOverwrittenEdits(engine, 'default');+ expect(scan.edits.map(edit => [edit.slug, edit.confidence, edit.db_operation])).toEqual([['notes/a', 'high', 'put_page']]);++ await engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw("UPDATE persistence_requests SET completed_at = now() - interval '400 days'"); });+ expect(await compactWriteReceipts(engine, 0)).toBeGreaterThan(0);+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE intent IS NOT NULL AND operation IN ('put_page','submit_job') AND slug='notes/a'"))[0]!.n).toBe(0);+ expect((await scanOverwrittenEdits(engine, 'default')).edits.map(edit => [edit.slug, edit.confidence])).toEqual([['notes/a', 'high']]);++ const preview = await repair(engine);+ expect(preview.listing?.map(entry => [entry.item, entry.class])).toEqual([['default:notes/a', 'restore_database_edit']]);+ expect(JSON.stringify(preview.details)).toContain('+DBONLYMARKER the agent edit.');+ expect(await bodyOf(engine, 'notes/a')).toContain('The second committed body.');++ const applied = await repair(engine, { expect: preview.preview_hash });+ expect(applied.outcome_items?.map(entry => entry.outcome)).toEqual(['restored_file_held']);+ expect(await bodyOf(engine, 'notes/a')).toContain('DBONLYMARKER');+ const [restore] = await engine.executeRaw<{ outcome: { write_through: { written: boolean; skipped?: string } }; worktree_id: string | null }>(+ "SELECT outcome, worktree_id::text AS worktree_id FROM persistence_requests WHERE operation='revert_version' AND slug='notes/a'");+ expect(restore!.outcome.write_through).toEqual({ written: false, skipped: 'overwrite_restore' });+ expect(restore!.worktree_id).toBeNull();+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain('The second committed body.');+ const hold = await holdOf(engine, 'notes/a.md');+ expect(hold?.code).toBe('file_drift');+ expect(hold?.meta.page_revision).toBe(await revisionOf(engine, 'notes/a'));++ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A third committed body.'));+ commit(root, 'edit a again');+ await performManagedSync(engine, OPTS);+ expect(await bodyOf(engine, 'notes/a')).toContain('DBONLYMARKER');+ expect((await holdOf(engine, 'notes/a.md'))?.code).toBe('file_drift');+ expect((await scanOverwrittenEdits(engine, 'default')).edits).toEqual([]);+ }, { setup, databaseUrl }), 180_000);++ test('a normal sync-written history is not flagged', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await putPage(engine, ctx, 'notes/c', 'A write-through edit.');+ commit(root, 'write-through publication');+ await engine.setConfig('sync.write_through', 'false');+ await putPage(engine, ctx, 'notes/d', 'A database-only edit no import replaced.');+ await engine.setConfig('sync.write_through', 'true');+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'A file-only edit.'));+ writeFileSync(join(root, 'notes/c.md'), note('notes/c', 'A later committed body of c.'));+ commit(root, 'edit b and c');+ await performManagedSync(engine, OPTS);+ expect(await bodyOf(engine, 'notes/b')).toContain('A file-only edit.');+ expect(await bodyOf(engine, 'notes/c')).toContain('A later committed body of c.');+ expect(await bodyOf(engine, 'notes/d')).toContain('no import replaced');+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_versions'))[0]!.n).toBeGreaterThanOrEqual(3);+ const scan = await scanOverwrittenEdits(engine, 'default');+ expect(scan).toMatchObject({ high: 0, unknown: 0, edits: [], truncated: false });+ expect((await repair(engine)).listing).toEqual([]);+ }, { setup, databaseUrl }), 180_000);++ test('a page that moved after the preview is refused and nothing is restored or held', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await seedOverwrite(engine, ctx, root, 'notes/a');+ const preview = await repair(engine, { slugs: ['notes/a'] });+ expect(preview.listing?.map(entry => entry.class)).toEqual(['restore_database_edit']);+ await engine.setConfig('sync.write_through', 'false');+ await putPage(engine, ctx, 'notes/a', 'A newer database edit after the preview.');+ const applied = await repair(engine, { slugs: ['notes/a'], expect: preview.preview_hash });+ expect(applied.outcome_items?.map(entry => [entry.outcome, entry.reason])).toEqual([['changed_since_preview', 'page_moved']]);+ expect(await bodyOf(engine, 'notes/a')).toContain('A newer database edit after the preview.');+ expect((await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE operation='revert_version'")).length).toBe(0);+ expect(await holdOf(engine, 'notes/a.md')).toBeNull();+ }, { setup, databaseUrl }), 180_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 384a87bfe7..a14147595e 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -125,6 +125,7 @@ test/managed-sync-row-parity.test.tstest/managed-sync-stale-group-head.test.tstest/migration-persistence-request-id-index.test.tstest/migration-persistence-request-slug-index.test.ts+test/overwritten-edits-6712.test.tstest/owner-refusal.test.tstest/pack-relation-direction-engine.test.tstest/page-embedding-budget.test.ts