Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712: only the checkout owner host holds the file; other hosts report restored_file_unheld with the owner command; goldens without merge-time eval_drift
garrytan9a4c9ccfa61a
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex b02d47c3cf..c2dc9e253e 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -26,6 +26,6 @@- `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/repair/overwritten-edits.ts` — `gbrain repair overwritten-edits`, explicit-only and preview-bound (`--slug` narrows): the preview lists each `high` page with a diff of the live page against the archived edit and saves the set; `--apply --expect <hash>` rechecks the page revision and version digest, then submits `revert_version` with `expected_revision` and `databaseOnly: 'overwrite_restore'` (`page-mutations.ts`: no worktree, receipt `write_through.skipped: overwrite_restore`), so the committed file is never rewritten; when this host owns the checkout and the committed HEAD blob differs from the restored page (`fileMatchesSnapshot`), it writes a `file_drift` hold (`fileDriftHold` + `writeGitHold`, `page_revision` = the restored revision). On another host, or for a file over the read bound, the outcome is `restored_file_unheld` with `next` naming the owner host's `gbrain repair file-drift --prefer database`; an apply whose restore request already committed replays it and writes the hold. Outcomes `restored`, `restored_file_held`, `restored_file_unheld`, `changed_since_preview`. Test: `test/overwritten-edits-6712.test.ts` (PGLite and Postgres).- `src/core/persistence/detached-pages.ts` — #6609 (D5) restore of a page whose recorded canonical file is gone on a brain without managed persistence. `assertRestoreOrigin` (called by `submitPageMutation` for `restore_page`, `publishesFile` = write-through on and a file target) refuses a restore that writes no file of a soft-deleted page whose `source_path` file `inSyncableTree` does not find (exists and is tracked or untracked-not-ignored, the set sync imports) with `source_changed` / detail `canonical_file_absent`, `retryable: false`, docs `storage-tiering.md#restoring-a-page-whose-file-is-gone` and an `ask_user` fix (`gbrain restore <slug> --source-id <id> --detach`, MCP `restore_page` `detach: true`); `detach: true` with nothing to detach refuses `invalid_params`. `detachRestoredPage` runs in the restore publication (from `classifyUnboundPage`) and clears `source_path`, stamping `pages.database_only_reason='detached'`; the page upsert in `engine-sql/pages.ts` clears that stamp when a sync writes a `source_path` again. `scanMissingRecordedFiles` (at most `MISSING_FILES_SCAN_LIMIT` live pages per source, `collectSyncableFiles` + `scannerSlugRootMode` path resolution) feeds doctor `missing_recorded_files`. Test: `test/restore-detach-6609.test.ts`.- `src/core/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 49f8c25f6a..953256ffe3 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -535,11 +535,28 @@ 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. An apply interrupted after arestore committed replays that restore's request on the next run and then-writes the hold, instead of reporting the page as moved. 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.+writes the hold, instead of reporting the page as moved. The restore+publishes to the database only and never rewrites the committed file.++Only the host that owns the source's checkout compares that file with the+restored page. There, a file that differs is held `file_drift` (outcome+`restored_file_held`), so no later sync publishes it over the edit; pick the+winner with [`gbrain repair file-drift`](#file-drift). On any other host the+restore still applies, but the file is neither compared nor held: the outcome+is `restored_file_unheld` (`why=checkout_not_on_this_host`; the same outcome+with `why=file_over_read_bound` means the owner host could not read a file+that large). A later sync that imports a change to that file can then publish+it over the restored edit again. No command writes only the hold afterward,+and the restored page is not listed again, so run the apply on the owner host.+After a restore on another host, resolve the page on the owner host so the+file holds the restored edit:++```bash+gbrain repair file-drift --source <id> --slug <slug> --prefer database # preview+gbrain repair file-drift --source <id> --slug <slug> --prefer database --apply --expect <preview-hash>+```++A restored page is not listed again.<a id="orphan-bindings"></a>### Orphan persistence bindingsdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 36e56e8148..ab5b058ed5 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -765,7 +765,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.278.0', text: 'An explicit `--max-usd N` on `gbrain embed --slugs` or `--held` now releases a held page on a free embedding provider too (#6847); it used to reprint the hold. Free-recipe models cost $0 in the per-page ledger, printed approve commands carry a concrete N (a paid N includes the 1.5x headroom and $0.25 floor), a free provider\'s approve asks for no paid or egress consent, and an approval when embeddings cannot run or the paid model has no price is refused before the hold is released. `--yes` still never releases a hold.' },{ since: '0.60.278.0', text: '`gbrain extract --stale --source <id>` now refuses with `invalid_params` naming `--source-id <id>` instead of running brain-wide; `--source fs` exits 2 `invalid_params` (it exited 1), and `--source db` refuses as ambiguous when a source is named `db`. Rendered extract fixes pin `--source-id`. The end-of-sync extraction nudge stays silent when doctor `links_extraction_lag` would not warn (attendance-blocked meetings no longer count), names both `gbrain extract --stale` and `gbrain extract --stale --catch-up` with estimates, and becomes a run-it-yourself step above two minutes; `extract --stale` JSON gains `actionable`, `attendance_blocked`, `mention_due` and `complete`; the per-source "still owe extraction" line counts only pages that sync imported; and an owner-delegated plain `extract --stale` keeps the 30-minute budget (`--catch-up` is carried through).' },// #6712 follow-up (#6891): `since` is a placeholder equal to the branch's VERSION, restamped when the merge slot is called.- { since: '0.60.278.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.' },+ { since: '0.60.278.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. Only the host that owns the source\'s checkout compares that file and holds it `file_drift` when it differs from the restored page; on any other host the restore applies with the file left unheld (outcome `restored_file_unheld`), and the owner host runs `gbrain repair file-drift --source <id> --slug <slug> --prefer database` afterward to write the restored edit to the file (no command writes only the hold).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/repair/overwritten-edits.ts b/src/core/repair/overwritten-edits.tsindex a2b5e8524b..0ed99359c3 100644--- a/src/core/repair/overwritten-edits.ts+++ b/src/core/repair/overwritten-edits.ts@@ -105,7 +105,7 @@ export const overwrittenEditsRepair: RepairHandler = {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.'] } : {}),+ ...(approved.length ? { warnings: ['Each restore writes the database edit as a new page revision without touching the committed file. Only the host that owns the source\'s checkout compares the file and holds it file_drift when it differs; pick a side later with gbrain repair file-drift. On any other host the restore still applies but the file is left unheld (outcome restored_file_unheld), so a later sync that imports a change to that file can publish it over the edit again; run the apply on the owner host, or afterwards run gbrain repair file-drift --source <id> --slug <slug> --prefer database there. No command writes only the hold.'] } : {}),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) {@@ -140,6 +140,8 @@ export const overwrittenEditsRepair: RepairHandler = {},};+const ownerHostCommand = (edit: Pick<ApprovedEdit, 'source_id' | 'slug'>) => `gbrain repair file-drift --source ${edit.source_id} --slug ${edit.slug} --prefer database`;+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` } });@@ -160,7 +162,10 @@ async function restoreEdit(ctx: OperationContext, entry: RepairItem, edit: Approthrow 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, ...(replayed ? { replayed } : {}), ...hold } };+ const unheld = hold.why === 'checkout_not_on_this_host' || hold.why === 'file_over_read_bound';+ return { applied: true, outcome: hold.held ? 'restored_file_held' : unheld ? 'restored_file_unheld' : 'restored',+ detail: { request_id: requestId, version_id: edit.version_id, ...(replayed ? { replayed } : {}), ...hold,+ ...(unheld ? { next: `the committed file was not compared or held; on the host that owns the checkout, preview ${ownerHostCommand(edit)} and apply it to write the restored edit to the file (no command writes only the hold)` } : {}) } };}/**diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex d1a493bc11..3f33b44c61 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2900,7 +2900,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "2 retrieval-affecting file(s) changed since HEAD: src/core/search/projection-readiness.ts, src/core/search/safe-chunks.ts. Re-run `gbrain eval run-all` after committing these changes.",+ "message": "No retrieval-affecting files changed in working tree.","name": "eval_drift","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex af6f3c3153..f270805619 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2945,7 +2945,7 @@{"category": "brain","elapsed_ms": "<volatile>",- "message": "2 retrieval-affecting file(s) changed since HEAD: src/core/search/projection-readiness.ts, src/core/search/safe-chunks.ts. Re-run `gbrain eval run-all` after committing these changes.",+ "message": "No retrieval-affecting files changed in working tree.","name": "eval_drift","status": "ok"},diff --git a/test/overwritten-edits-6712.test.ts b/test/overwritten-edits-6712.test.tsindex 85102c69e6..40b97fd25f 100644--- a/test/overwritten-edits-6712.test.ts+++ b/test/overwritten-edits-6712.test.ts@@ -15,7 +15,10 @@* 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;* - an apply interrupted after its restore committed but before the hold was written replays the same request and- * writes the hold, instead of reporting the restored page as moved.+ * writes the hold, instead of reporting the restored page as moved;+ * - on a host that does not own the checkout the restore applies but reports the file left unheld+ * (`restored_file_unheld`, `checkout_not_on_this_host`) with the owner host's command, and that command+ * (`gbrain repair file-drift --prefer database`, run once the host owns the checkout) writes the edit to the file.** Doctor `sync_overwritten_db_edits` warns with the source's count and slugs for a high finding and is ok otherwise.*@@ -41,6 +44,7 @@ import { overwrittenEditsEntry } from '../src/commands/doctor/checks/overwrittenimport 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 { localHostId } from '../src/core/persistence/identity.ts';import { managedBrain } from './helpers/managed-brain.ts';import { waitFor } from './helpers/wait-for.ts';@@ -179,4 +183,28 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATexpect((await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE operation='revert_version'")).length).toBe(1);expect((await holdOf(engine, 'notes/a.md'))?.meta.page_revision).toBe(restored);}, { setup, databaseUrl }), 180_000);++ test('a restore on a host that does not own the checkout reports the file left unheld and names the owner host command', () => 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.warnings?.join(' ')).toContain("Only the host that owns the source's checkout compares the file");+ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id = $1::uuid', [randomUUID()]);+ const applied = await repair(engine, { slugs: ['notes/a'], expect: preview.preview_hash });+ const [outcome] = applied.outcome_items ?? [];+ expect([outcome?.outcome, outcome?.detail?.held, outcome?.detail?.why]).toEqual(['restored_file_unheld', false, 'checkout_not_on_this_host']);+ expect(String(outcome?.detail?.next)).toContain('gbrain repair file-drift --source default --slug notes/a --prefer database');+ expect(await bodyOf(engine, 'notes/a')).toContain('DBONLYMARKER');+ expect(await holdOf(engine, 'notes/a.md')).toBeNull();+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain('The second committed body.');++ await engine.executeRaw('UPDATE persistence_worktrees SET owner_host_id = $1::uuid', [localHostId()]);+ const scope = await resolveRepairScope(engine, 'default');+ const drift = { explicit: true, sourceFlag: 'default', slugs: ['notes/a'], prefer: 'database' as const };+ const driftPreview = await (await repairRunner(engine, { apply: false, logger })).run('file-drift', scope, drift);+ expect(driftPreview.listing?.map(entry => [entry.item, entry.class])).toEqual([['default:notes/a', 'prefer_database']]);+ const driftApplied = await (await repairRunner(engine, { apply: true, logger })).run('file-drift', scope, { ...drift, expect: driftPreview.preview_hash });+ expect(driftApplied.outcome_items?.map(entry => entry.outcome)).toEqual(['repaired']);+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain('DBONLYMARKER');+ }, { setup, databaseUrl }), 180_000);});