Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712: doctor assertions, docs, behavior row, goldens
garrytan3e443edd5ef5
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 9048e00d9f..7fbff7b2ee 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -22,5 +22,8 @@- `src/core/ghost-pages.ts` — #6696 B5, the one ghost-page classifier: a ghost is a live page for which `liveFileDrift` returns reason `canonical_file_missing` on the source's canonical owner host (`prepareFileTarget` tags that refusal `detail: 'canonical_file_missing'`). `scanGhostSource` reads a source's live pages in id order (at most `GHOST_SCAN_LIMIT`), resolves each recorded canonical path exactly as `prepareFileTarget` does and stats it, skips `publishesDatabaseOnly` and legacy slugs, and runs the full check on at most `candidateLimit` candidates; it returns the ghosts, `inspected`, `file_backed` (the mass-delete valve's population), `truncated` and the owner it ran under (host, worktree, owner epoch, incarnation). Off the owner host a source is `not_applicable` (`not_owner_host`, or `not_applicable` with no binding); a missing root is `unknown` (`storage_unavailable`), a stat error, invalid gbrain.yml or inconclusive check `unknown` (`ambiguous_storage`). `ghostPageNow` re-checks one page (the repair's recheck); `readGhostPages(engine, { sourceIds?, sampleLimit? })` is the counts-and-samples summary for doctor and the read-scope health op. Tests: `test/ghost-pages-6696.test.ts`.- `src/core/repair/ghost-pages.ts` — `gbrain repair ghost-pages --source <id>` (#6696 B5): explicit-only, preview-bound, destructive consent (`GHOST_CONSENT_TEXT`: the 72 h purge fuse, the per-slug `gbrain restore <slug> --force` undo, and the keep path of restoring the file and syncing). The preview binds the ghost set to the owner and each page's revision and path; the apply refuses `not_owner_host`, `ghost_storage_unknown`, `preview_changed` on an owner change, and `ghost_mass_delete_refused` (`massGhosts`: the sync valve, `MASS_RECONCILE_RATIO` over more than `MASS_RECONCILE_MIN_PAGES` file-backed pages, unless `massReconcileAllowed()`). Each page re-checks with `ghostPageNow`, then a managed brain submits one `managed_maintenance_retire_ghost_page` request (`prepareGhostPageRetirement`, dispatched from `prepared-maintenance.ts`: re-check, `delete_page` with `allowMissingFile`, refusal unless the prepared file target is the approved path with no bytes, so filesystem publication refuses a file that appeared later); an unmanaged brain soft-deletes in one transaction after the same check. Outcomes `soft_deleted`, `file_restored` (asks for a new preview), `changed_since_preview`. Doctor `ghost_pages` (`src/commands/doctor/checks/ghost-pages.ts`, BRAIN, after `fence_integrity`) reports the count, samples and coverage with the preview as its fix, `ok` + info off the owner host, unknown on an unreadable checkout; `gbrain pages ghosts` (`src/commands/pages-ghosts.ts`) lists them read-only.- `src/commands/doctor/checks/missing-recorded-files.ts` — #6609 doctor `missing_recorded_files` (BRAIN, after `ghost_pages`): the classic-brain counterpart of `ghost_pages`. Read-only; per source with a checkout on this host and managed persistence off it runs `scanMissingRecordedFiles` (`src/core/persistence/detached-pages.ts`) and warns with counts, samples and an `ask_user` fix (put the file back and sync, or `gbrain delete` then `gbrain restore <slug> --source-id <id> --detach`) for live pages whose recorded file a `gbrain sync --full` would not find; `ok` + `not_applicable` when no source qualifies. Test: `test/restore-detach-6609.test.ts`.+- `src/core/persistence/overwritten-edits.ts` — #6712 follow-up: `scanOverwrittenEdits` finds live pages whose database-only revision a managed-sync import replaced with different content and no hold, from durable rows only (it survives receipt compaction): `page_versions.write_request_id` / `archived_write_request_id`, the writer's committed receipt (`outcome.persistence.mode = 'database'`, not an import, no `git` effect for that revision, not a read-only mirror write), the archiving request recognised as a managed-sync import by intent kind or, once compacted, by operation `submit_job` + `outcome.imported_file` without `connector_database`, and `reconcileCanonical` digests (the import's own revision differs; no later revision holds the edit again). `high` or `unknown` (`no_persistence_outcome`, `import_content_unreadable`, `segmented`); the newest open overwrite per page; at most `OVERWRITE_SCAN_LIMIT` candidate versions per source. Revisions with no recorded writer are not reported.+- `src/commands/doctor/checks/overwritten-edits.ts` — doctor `sync_overwritten_db_edits` (BRAIN, after `missing_recorded_files`): per source count and first slugs from `scanOverwrittenEdits`; `warn` only for `high` findings, with the read-only `gbrain repair overwritten-edits --source <id>` preview as an `ask_user` fix; `unknown` findings are counted in `details` and never warn.+- `src/core/repair/overwritten-edits.ts` — `gbrain repair overwritten-edits`, explicit-only and preview-bound (`--slug` narrows): the preview lists each `high` page with a diff of the live page against the archived edit and saves the set; `--apply --expect <hash>` rechecks the page revision and version digest, then submits `revert_version` with `expected_revision` and `databaseOnly: 'overwrite_restore'` (`page-mutations.ts`: no worktree, receipt `write_through.skipped: overwrite_restore`), so the committed file is never rewritten; when this host owns the checkout and the committed HEAD blob differs from the restored page (`fileMatchesSnapshot`), it writes a `file_drift` hold (`fileDriftHold` + `writeGitHold`, `page_revision` = the restored revision). Outcomes `restored`, `restored_file_held`, `changed_since_preview`. Test: `test/overwritten-edits-6712.test.ts` (PGLite and Postgres).- `src/core/persistence/detached-pages.ts` — #6609 (D5) restore of a page whose recorded canonical file is gone on a brain without managed persistence. `assertRestoreOrigin` (called by `submitPageMutation` for `restore_page`, `publishesFile` = write-through on and a file target) refuses a restore that writes no file of a soft-deleted page whose `source_path` file `inSyncableTree` does not find (exists and is tracked or untracked-not-ignored, the set sync imports) with `source_changed` / detail `canonical_file_absent`, `retryable: false`, docs `storage-tiering.md#restoring-a-page-whose-file-is-gone` and an `ask_user` fix (`gbrain restore <slug> --source-id <id> --detach`, MCP `restore_page` `detach: true`); `detach: true` with nothing to detach refuses `invalid_params`. `detachRestoredPage` runs in the restore publication (from `classifyUnboundPage`) and clears `source_path`, stamping `pages.database_only_reason='detached'`; the page upsert in `engine-sql/pages.ts` clears that stamp when a sync writes a `source_path` again. `scanMissingRecordedFiles` (at most `MISSING_FILES_SCAN_LIMIT` live pages per source, `collectSyncableFiles` + `scannerSlugRootMode` path resolution) feeds doctor `missing_recorded_files`. Test: `test/restore-detach-6609.test.ts`.- `src/core/repair/keep-db-policy.ts` — the opt-in `storage.keep_db` policy (#6696 C7). `readKeepDbPolicy` reads a source's `keep_db` prefixes from the gbrain.yml of its canonical checkout, only when the given host owns the active binding. `runKeepDbPolicy` takes the slugs under the prefixes with a drift conflict receipt in the newest 100,000 request sequences plus the recorded concept drift skips, checks each live, prepares the `--prefer database` resolution (`prepareDriftPage`) and submits it through `runReconcileApply` under this installation's own CLI writer registration (never an inherited caller context), with a request id derived from the page revision and file bytes, so one drift is never submitted twice. A run submits at most `KEEP_DB_BATCH` (10) requests (`stopped: 'rate_limit'`) and asks its `admission` gate before each one (default: the repair core's 90% stop line on lifetime ids and receipt bytes, `stopped: 'capacity'`; the seam for background-producer backpressure). The persistence consumer (`consumer.ts`) runs it while idle at most every 10 minutes when started with `keepDbPolicy` (`service.ts`: serve, jobs and autopilot owners only; never with `requestsOnly`), and `stop()` awaits the pass. Tests: `test/file-drift-bulk-reconcile.test.ts` (PGLite; Postgres via `test/e2e/file-drift-bulk-reconcile-postgres.test.ts`).diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex ee4e7dc506..5f93fbcd20 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -147,6 +147,7 @@ work behind exits 0, so scripts should also check `results[].complete`.| `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`). || `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. |+| `overwritten-edits` | `sync_overwritten_db_edits` | Explicit-only, preview-bound. Restores database edits that an incremental managed sync replaced with a committed file edit and no `file_drift` hold (#6712, fixed by #6887). It restores 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 diffs the live page against the edit; `--apply --expect <hash>` reverts each page to that version through a revision-bound, database-only `revert_version` and holds the committed file `file_drift` when it differs. See [overwritten edits](#overwritten-edits). | `unknown_*` findings (no persistence outcome on the writer's receipt, the import's content no longer readable, a segmented version), listed but not restored; pages that moved after the preview (`changed_since_preview`). |Timeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nor@@ -465,6 +466,47 @@ record holds it: a grade or resolution stored only in the database, the take'sid (the row gets a new one) and its embedding (re-embedded). A second previewlists nothing.+<a id="overwritten-edits"></a>+### Overwritten database edits++**Say to your agent:** *"Check whether sync overwrote any of my database edits and show me what it would restore."*++From v0.60.255.0 until #6887, an ordinary incremental `gbrain sync` on a managed+brain could publish a committed file edit over a page that was also edited in+the database since its last import (for example a `put_page` with+`sync.write_through` off). It wrote no `file_drift` hold and no backup. The database edit is still in+the page's history: the import archived it as a page version. Doctor+`sync_overwritten_db_edits` counts the pages per source and names the first ones.++Preview, show the user both versions, then apply after they agree:++```bash+gbrain repair overwritten-edits --source <id> # each page, the edit's version, who wrote it, the import that replaced it, a diff+gbrain repair overwritten-edits --source <id> --slug notes/a # one page+gbrain repair overwritten-edits --source <id> --apply --expect <preview-hash>+```++A page is listed only when the records prove it: the archived revision's writer+is a committed request whose receipt published no file (`persistence.mode`+`database`, no Git effect for that revision, not a read-only mirror write), the+request that archived it is a managed-sync import (also after receipt+compaction, from its operation and outcome), the import wrote different content,+and no later revision of the page holds the edit again. Findings the records+cannot prove are listed `unknown` with the reason and never restored: the+writer's receipt has no `persistence` outcome, the import's own content is no+longer readable, or a version is segmented. A revision with no recorded writer+(written before write attribution, by a classic sync, or by unattributed+maintenance) is not reported, because it looks exactly like ordinary sync+history.++The apply reverts each page to the archived version through `revert_version`,+bound to the page revision the preview saw, so a page that moved since is+`changed_since_preview` and nothing is written. The restore publishes to the+database only and never rewrites the committed file. When that file then differs+from the restored page (on the host that owns the checkout), the file is held+`file_drift`, so no later sync publishes it over the edit; pick the winner with+[`gbrain repair file-drift`](#file-drift). A restored page is not listed again.+<a id="orphan-bindings"></a>### Orphan persistence bindingsdiff --git a/src/commands/doctor/checks/overwritten-edits.ts b/src/commands/doctor/checks/overwritten-edits.tsindex d48ab3c5d5..03b4e9b7ea 100644--- a/src/commands/doctor/checks/overwritten-edits.ts+++ b/src/commands/doctor/checks/overwritten-edits.ts@@ -1,6 +1,6 @@/*** #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;+ * replaced with a committed file edit and no `file_drift` hold (the bug #6887 fixes, or any other unguarded import). 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)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d7e9575451..18dd30846a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -752,6 +752,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.276.0', text: 'On a writer-claimed brain, background writes are refused before any receipt, so they spend no write-request id, when their source cannot publish: the worktree is in recovery, or the claim\'s owner verification fails on the owner host (a missing canonical or coordination path, or a physical root whose owner marker .gbrain-owner.json or reservation is gone or changed; a device-only change is still re-stamped by the write). The refusal is owner_unavailable with the fix `gbrain sources writer status --source <id> --json`, checked once per source per run. Background writes are every write not made from an interactive surface: the autopilot cycle and its maintenance phases (extraction, synthesis, patterns, consolidation, fence and content repair, lint fixes), Minion jobs (sync, extract and the other job handlers), connector syncs, delegated serve syncs started as background, the keep-DB reconcile, autopilot and job managed syncs, and the transcript stale-part delete. Interactive CLI, MCP and repair writes are unaffected; a paused (draining) owner still accepts and replays.' },{ since: '0.60.276.0', text: 'The managed purge (autopilot purge phase, the purge job and `gbrain pages purge-deleted`) submits nothing for a source whose writer needs recovery (reported `writer_not_active` with its state and reason) and parks a page after five failed purges (doctor `purge_parked_pages`: actor agent on the CLI, host_admin remotely). The cycle purge phase reports warn, not fail, for either. `gbrain pages purge-deleted --retry-parked` retries parked pages once; it obeys `--older-than` (a parked page younger than the cutoff is not retried) and the rename-recovery hold, and its preview, its consent text (which names the parked count) and its run come from one selector.' },{ since: '0.60.276.0', text: '`gbrain repair content` / `repair slug-conflicts` now clears a frontmatter_slug_conflict hold deterministically (remove_slug) when the only other change autoFixFrontmatter would make is a style-only NESTED_QUOTES re-quote of a valid JSON-style tag or alias array. Only the slug: line is removed; the array is left as written and listed as style_only in the preview, the run result and the content_repair receipt. Such holds used to stay still_invalid and needed `repair frontmatter --include-ambiguous`. When the lane still cannot clear a hold because the frontmatter needs other fixes, the still_invalid message now names those fix codes (for example NULL_BYTES).' },+ { since: '0.60.276.0', text: 'New doctor check `sync_overwritten_db_edits` warns when an incremental managed sync published a committed file edit over a page that was also edited in the database since its last import, with no `file_drift` hold (the bug #6887 fixes): the database edit survives only in the page\'s history. It counts the pages per source from page history and write receipts (also after receipt compaction) and warns only when the records prove it; findings it cannot prove are counted as unknown. New explicit-only repair `gbrain repair overwritten-edits --source <id>` previews each page with a diff, and `--apply --expect <hash>` restores the edit as a new revision through a database-only `revert_version` bound to the previewed revision (a page that moved is `changed_since_preview`); it never rewrites the committed file, and holds that file `file_drift` when it differs from the restored page.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/overwritten-edits.ts b/src/core/persistence/overwritten-edits.tsindex c70c3152c7..1c7a25d206 100644--- a/src/core/persistence/overwritten-edits.ts+++ b/src/core/persistence/overwritten-edits.ts@@ -2,7 +2,7 @@* #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+ * `file_drift` hold and no backup. 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` thediff --git a/src/core/repair/overwritten-edits.ts b/src/core/repair/overwritten-edits.tsindex c536fe673a..b78b27a5af 100644--- a/src/core/repair/overwritten-edits.ts+++ b/src/core/repair/overwritten-edits.ts@@ -1,8 +1,8 @@/*** `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.+ * incremental managed sync published a committed file edit over, with no `file_drift` hold (the bug #6887 fixes, or any+ * other unguarded import). 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@@ -24,7 +24,7 @@ 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 { clearApprovedSet, loadApprovedSet, previewChangedError, 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';@@ -116,7 +116,7 @@ export const overwrittenEditsRepair: RepairHandler = {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}`);+ throw previewChangedError(opts.expect, 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: {} };diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex b16d5d0b17..d4d68e74c7 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2681,6 +2681,20 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#overwritten-edits",+ "sources": [],+ "truncated": false,+ "unknown": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No page shows a database edit that a sync import overwrote.",+ "name": "sync_overwritten_db_edits",+ "status": "ok"+ },{"category": "meta","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 0550a761da..f59197e387 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2726,6 +2726,20 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#overwritten-edits",+ "sources": [],+ "truncated": false,+ "unknown": 0+ },+ "elapsed_ms": "<volatile>",+ "message": "No page shows a database edit that a sync import overwrote.",+ "name": "sync_overwritten_db_edits",+ "status": "ok"+ },{"category": "meta","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 4afecf063d..667ff02e3f 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -857,6 +857,10 @@"category": "brain","name": "missing_recorded_files"},+ {+ "category": "brain",+ "name": "sync_overwritten_db_edits"+ },{"category": "meta","name": "sync_config_keys"diff --git a/test/overwritten-edits-6712.test.ts b/test/overwritten-edits-6712.test.tsindex c8d7fd171b..7da0ecdd23 100644--- a/test/overwritten-edits-6712.test.ts+++ b/test/overwritten-edits-6712.test.ts@@ -15,6 +15,8 @@* 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.*+ * Doctor `sync_overwritten_db_edits` warns with the source's count and slugs for a high finding and is ok otherwise.+ ** PGLite always; Postgres too when DATABASE_URL is set.*/import { describe, expect, test } from 'bun:test';@@ -32,6 +34,10 @@ import { scanOverwrittenEdits } from '../src/core/persistence/overwritten-edits.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 { overwrittenEditsEntry } from '../src/commands/doctor/checks/overwritten-edits.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';import { managedBrain } from './helpers/managed-brain.ts';import { waitFor } from './helpers/wait-for.ts';@@ -66,6 +72,7 @@ async function seedOverwrite(engine: BrainEngine, ctx: OperationContext, root: sawait performManagedSync(engine, OPTS);expect(await bodyOf(engine, slug)).toContain('The second committed body.');}+const doctor = async (engine: BrainEngine) => ((await overwrittenEditsEntry.run({ engine, tier: 'standard', doFix: false, dryRun: false } as unknown as DoctorContext)) as Check[])[0]!;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 } : {}) });@@ -77,6 +84,11 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATconst scan = await scanOverwrittenEdits(engine, 'default');expect(scan.edits.map(edit => [edit.slug, edit.confidence, edit.db_operation])).toEqual([['notes/a', 'high', 'put_page']]);+ const warned = await doctor(engine);+ expect(warned.status).toBe('warn');+ expect(warned.details).toMatchObject({ count: 1, unknown: 0, sources: [{ source_id: 'default', count: 1, slugs: ['notes/a'] }] });+ expect(warned.fix?.argv).toEqual(['gbrain', 'repair', 'overwritten-edits', '--source', 'default', '--json']);+ expect(categorizeCheck('sync_overwritten_db_edits')).toBe('brain');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);@@ -106,6 +118,7 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATexpect(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([]);+ expect((await doctor(engine)).status).toBe('ok');}, { setup, databaseUrl }), 180_000);test('a normal sync-written history is not flagged', () => managedBrain(async ({ engine, ctx, root }) => {@@ -126,6 +139,7 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATconst scan = await scanOverwrittenEdits(engine, 'default');expect(scan).toMatchObject({ high: 0, unknown: 0, edits: [], truncated: false });expect((await repair(engine)).listing).toEqual([]);+ expect(await doctor(engine)).toMatchObject({ status: 'ok', details: { count: 0, unknown: 0 } });}, { 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 }) => {diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 1e7a28fbd9..f6d1020813 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', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'receipt-compaction', 'aliases', 'overwritten-edits'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));