Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane D): repair file-drift --held --side/--state, deleted-side remove/import

garrytane2db3543af84
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 86f8250ec1..63352d5beb 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1310,6 +1310,26 @@ More: [docs/guides/write-refusals.md#fetch_failed](../../docs/guides/write-refus
More: [docs/guides/write-refusals.md#file_drift](../../docs/guides/write-refusals.md#file_drift)
+### file_drift_mixed_selection
+
+<a id="file_drift_mixed_selection"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain repair file-drift --held selected held pages of more than one Decision (side, or deleted state), so nothing was previewed: one --prefer must not resolve differently shaped drift in bulk. | Each side and deleted state is its own Decision with its own meaning of --prefer file and --prefer database; resolving them together would apply one choice to questions the user answered differently, or not at all. | Preview one Decision at a time with the narrower commands the message names (--held --side <side>, plus --state <state> for --side deleted), or narrow with --only / --skip. Run: gbrain sources status '{source_id}' --json | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/repair.md#file-drift](../../docs/guides/repair.md#file-drift)
+
+### file_drift_state_required
+
+<a id="file_drift_state_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain repair file-drift --held for deleted-side drift needs --state (tombstone_edited, purged_differs or file_gone); nothing was previewed. | In each deleted state --prefer file and --prefer database do opposite things (tombstone_edited: restore and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the file; file_gone: soft-delete the page, or recreate the file), so the state is always named explicitly. | Rerun the preview with --side deleted --state <state>, choosing the state gbrain sources status <source> --json lists for the held files. Run: gbrain sources status '{source_id}' --json | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/repair.md#file-drift](../../docs/guides/repair.md#file-drift)
+
### file_removed_during_scan
<a id="file_removed_during_scan"></a>
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 8468a9aa57..a808f47d41 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -67,7 +67,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
[--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]
gbrain repair receipt-compaction [--older-than <72h|30d>] [--include-failures] [--force]
[--apply --expect <preview-hash> --yes] [--limit <n>] [--json]
- gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>])
+ gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>]
+ | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]])
[--only <glob>]... [--skip <glob>]... --prefer file|database [--apply --expect <preview-hash>] [--json]
gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]
[--keep prior|disk --apply --expect <preview-hash> --yes] [--json]
@@ -104,6 +105,12 @@ Options:
file-drift: the side that wins; select conflict receipts by request id (repeatable), or every page
still drifted (refused across mixed drift classes unless --class keeps one). --keep is refused here:
--prefer database keeps the database copy, --prefer file keeps the file.
+ --held [--side both|unknown|deleted] [--state tombstone_edited|purged_differs|file_gone]
+ file-drift: select the source's held file_drift pages of one Decision. --side deleted needs --state,
+ because --prefer file and --prefer database do opposite things in each state (tombstone_edited: restore
+ and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the
+ file; file_gone: soft-delete the page, or recreate the file). Held pages of several sides or states are
+ refused without --side; the preview prints each page's action.
--since <ISO-8601|7d>
file-drift: keep only pages whose newest drift conflict is at or after the instant (with --all-drifted, or
the bare survey). An age (7d, 12h) is resolved once to a concrete instant; the preview, its hash and the
@@ -130,17 +137,18 @@ Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fence
A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.
Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.`;
-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force']);
-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than']);
+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--held', '--include-failures', '--force']);
+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--side', '--state', '--keep', '--request-id', '--older-than']);
/** 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'],
+ '--held': ['file-drift'], '--side': ['file-drift'], '--state': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
};
const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',
- '--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--keep': 'prior',
+ '--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior',
'--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d' };
/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */
const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,
@@ -149,6 +157,7 @@ const invalid = (message: string, suggestion: string, preview: string[] = ['gbra
interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;
noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];
allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;
+ held: boolean; side?: string; state?: string;
keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean }
/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */
@@ -182,7 +191,7 @@ function fileDriftKeepRefusal(args: string[], keep: string): OperationError {
/** Strict parse: every flag is known, value flags carry a value, at most one kind. */
export function parseRepairArgs(args: string[]): RepairArgs {
const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],
- allDrifted: false, requests: [], includeFailures: false, force: false };
+ allDrifted: false, held: false, requests: [], includeFailures: false, force: false };
const used = new Set<string>();
const positional: string[] = [];
let maxUsdText: string | undefined;
@@ -209,6 +218,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--yes') parsed.yes = true;
else if (flag === '--no-llm') parsed.noLlm = true;
else if (flag === '--all-drifted') parsed.allDrifted = true;
+ else if (flag === '--held') parsed.held = true;
else if (flag === '--include-failures') parsed.includeFailures = true;
else if (flag === '--force') parsed.force = true;
else parsed.noEmbed = true;
@@ -230,6 +240,8 @@ export function parseRepairArgs(args: string[]): RepairArgs {
}
else if (flag === '--request') parsed.requests.push(value);
else if (flag === '--class') parsed.driftClass = value;
+ else if (flag === '--side') parsed.side = value;
+ else if (flag === '--state') parsed.state = value;
else if (flag === '--since') {
try { parsed.since = parseSince(value, '--since'); } catch (error) {
throw invalid((error as Error).message, 'Pass an ISO-8601 instant (2026-10-01T00:00:00Z) or an age (7d, 12h); the preview prints the concrete instant it selected.', ['gbrain', 'repair', 'file-drift', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);
@@ -330,7 +342,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
- prefer, requests, allDrifted, driftClass, since, keep, requestId, olderThan, includeFailures, force } = parseRepairArgs(args);
+ prefer, requests, allDrifted, driftClass, since, held, side, state, keep, requestId, olderThan, includeFailures, force } = parseRepairArgs(args);
const limit = limitText === undefined ? undefined : Number(limitText);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');
// #6712 PR 2: a repair apply is a soak intervention; a file-drift apply is a content decision (soak-counters.ts).
@@ -371,7 +383,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,
...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),
...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
- ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since } : {}),
+ ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}) } : {}),
...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),
...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}) });
results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 32b51e6949..d6cd5e1ad5 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -260,6 +260,8 @@ export const CODES = {
fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },
fix_not_writable: { class: 'host_only', summary: "A gbrain lint fix was not applied because the file refused the write (EACCES, EPERM or EROFS); the file was left unchanged.", why: "Lint repairs files in place, and this file's permissions or a read-only mount stopped the write; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#fix-not-writable', suggestion: "Make the file writable by the user running gbrain, or pass its directory or file name to gbrain lint --exclude, then lint again." },
file_drift: { class: 'caller', summary: "A managed sync import would have overwritten a database version of the page that sync never saw (the page changed since its file was last imported), so the file is held and the page keeps the database version.", why: "Sync imports a file only when the page is still at the revision its last recorded import wrote, or when the import changes nothing. Here the page moved (a database-only write, or no import record to compare on an upgraded brain) and the file's content differs, so importing would silently replace the newer database copy. Pages under storage.keep_db prefixes are never held: the keep_db worker reconciles them from the database.", docs: 'docs/guides/write-refusals.md#file_drift', suggestion: 'Preview with gbrain repair file-drift --source <source> --slug <slug> --prefer database (keep the database copy and rewrite the file) or --prefer file (import the file), decide with the user, then apply it with the plan hash; the next gbrain sync --source <source> --no-pull re-screens the hold.' },
+ file_drift_mixed_selection: { class: 'caller', summary: "gbrain repair file-drift --held selected held pages of more than one Decision (side, or deleted state), so nothing was previewed: one --prefer must not resolve differently shaped drift in bulk.", why: "Each side and deleted state is its own Decision with its own meaning of --prefer file and --prefer database; resolving them together would apply one choice to questions the user answered differently, or not at all.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Preview one Decision at a time with the narrower commands the message names (--held --side <side>, plus --state <state> for --side deleted), or narrow with --only / --skip.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },
+ file_drift_state_required: { class: 'caller', summary: "gbrain repair file-drift --held for deleted-side drift needs --state (tombstone_edited, purged_differs or file_gone); nothing was previewed.", why: "In each deleted state --prefer file and --prefer database do opposite things (tombstone_edited: restore and import, or keep the deletion and remove the file; purged_differs: import as a new page, or remove the file; file_gone: soft-delete the page, or recreate the file), so the state is always named explicitly.", docs: 'docs/guides/repair.md#file-drift', suggestion: 'Rerun the preview with --side deleted --state <state>, choosing the state gbrain sources status <source> --json lists for the held files.', fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the held files of the source with their side and state.', requires_exclusive: false } },
file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },
file_too_large: { class: 'caller', summary: "The file is over the page size limit (24 MiB for a Markdown page, 5 MB for a code file), so it was not imported.", why: "Every page under the limit is stored, chunked and searchable whatever its size; the limit bounds what one page may hold in this release. The same bytes refuse on every retry. A smaller page refused by an MCP or HTTP transport is a different refusal.", docs: 'docs/guides/write-refusals.md#file_too_large', suggestion: 'Leave the file out of the source (sync.exclude), or, if it must be in the brain, split it into files under the limit; then sync or import again. Never split a page under the limit.' },
follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 2fa3885687..fa98e16a78 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -532,6 +532,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
}
if (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_retire_ghost_page') return (await import('../repair/ghost-pages.ts')).prepareGhostPageRetirement(engine, row, config);
+ if (row.intent?.kind === 'managed_maintenance_file_drift_remove') return (await import('../repair/file-drift.ts')).prepareDriftFileRemoval(engine, row);
if (row.intent?.kind !== 'managed_maintenance_consolidate') throw opError('invalid_params', 'Unsupported maintenance request.',
`Request ${row.request_id} for ${row.slug} in ${row.source_id} carries a maintenance kind this gbrain version does not publish (likely queued by a newer release); nothing changed. Upgrade gbrain on the brain host, and read the receipt before submitting anything new.`,
{ fix: receiptFix(row) });
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 6b63c6a6d5..ea2667e5f3 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -93,6 +93,8 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;
/** #6712 PR 2 `file-drift`: only pages whose newest drift conflict is at or after this concrete instant (ISO; `--since`, parsed by `since.ts`). */
since?: string;
+ /** #6712 PR 4b `file-drift`: the source's held `file_drift` pages, of one side and (for `deleted`) one state. */
+ held?: boolean; side?: string; state?: string;
/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */
keep?: 'prior' | 'disk'; requestId?: string;
/** `receipt-compaction` (#6696 A9): the age (`72h`, `30d`), failures too, and compaction inside the retention window. */
@@ -275,7 +277,7 @@ function writerHeld(error: unknown): error is OperationError {
export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,
opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];
explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;
- prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string;
+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */
@@ -297,6 +299,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false,
...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),
...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}), ...(opts.since ? { since: opts.since } : {}),
+ ...(opts.held ? { held: true } : {}), ...(opts.side ? { side: opts.side } : {}), ...(opts.state ? { state: opts.state } : {}),
...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),
...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}) };
const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);
@@ -323,6 +326,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
+ `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path]),
...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.requests ?? []).flatMap(id => ['--request', id]),
...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []), ...(opts.since ? ['--since', opts.since] : []),
+ ...(opts.held ? ['--held'] : []), ...(opts.side ? ['--side', opts.side] : []), ...(opts.state ? ['--state', opts.state] : []),
...(opts.prefer ? ['--prefer', opts.prefer] : [])].map(arg => ` ${shellQuote([arg])}`).join('')}`
+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`
+ ` --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}${spec?.consent === 'destructive' ? ' --yes' : ''}`,
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index 79419c69a7..b57661367e 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -49,7 +49,7 @@ import { join, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
import { flushDirectory } from '../fs-durable.ts';
-import { OperationError, opError } from '../ops/contract.ts';
+import { OperationError, opError, type OperationContext } from '../ops/contract.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { validateSlug } from '../utils.ts';
import { matchesRepairPath } from './path-glob.ts';
@@ -61,7 +61,13 @@ import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, sa
import { canonicalFilesystemPath } from '../persistence/root-registry.ts';
import { auditDriftConflicts, DRIFT_CLASSES, driftClass, liveFileDrift, type DriftClass } from '../persistence/drift-conflicts.ts';
import { protectedReconcileKey, reconcileCanonical, RECONCILE_SCAN_KEYS, type ReconcileDecision } from '../persistence/reconcile-merge.ts';
-import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readReconcileState, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
+import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readDeletedDriftTarget, readReconcileState, type DeletedDriftChange, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
+import { clearGitHold, fileDriftActionVerb, fileDriftSide, FILE_DRIFT_DELETED_STATES, FILE_DRIFT_SIDES, GIT_HOLD_OP, heldDriftPreviewArgv, type FileDriftDeletedState, type FileDriftSide, type GitHoldRecord } from '../persistence/sync-holds.ts';
+import { prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../persistence/file-repair.ts';
+import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { resolveSlugForPath } from '../sync.ts';
import { getWorktreeBinding } from '../persistence/ownership.ts';
import { gitDurabilityPolicy } from '../persistence/git-durability-policy.ts';
import { ghostPageNow, scanGhostSource, type GhostOwner, type GhostPage } from '../ghost-pages.ts';
@@ -84,7 +90,28 @@ export interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftCl
file_gone?: true }
/** #6712 wave: a page whose canonical file is gone from the last commit, resolved `--prefer file`: soft-delete exactly that page. */
export interface SoftDeletePage { slug: string; prefer: 'file'; exceptions: DriftException[]; soft_delete: { ghost: GhostPage; owner: GhostOwner } }
-type PlannedPage = ArtifactPage | SoftDeletePage;
+/**
+ * #6712 PR 4b: what a held deleted-side resolution is bound to (design v3.2 §4): the file's bytes, the tombstone's id and
+ * revision (`tombstone_edited`) or the deletion marker's value (`purged_differs`), and the hold it clears.
+ */
+export interface DeletedDriftPin { state: 'tombstone_edited' | 'purged_differs'; path: string; source_path: string; raw_file_hash: string;
+ page_id: number | null; revision: string | null; marker_digest: string | null; observed_at: string }
+/** #6712 PR 4b `--prefer database` on a deleted side: the deletion stands and the file is removed by a coordinated publication. */
+export interface RemoveFilePage { slug: string; prefer: 'database'; exceptions: DriftException[]; remove_file: DeletedDriftPin }
+/** #6712 PR 4b `--prefer file` on a deleted side: the file's bytes are imported (restoring the tombstone, or as a new page). */
+export interface ImportFilePage { slug: string; prefer: 'file'; exceptions: DriftException[]; import_file: DeletedDriftPin & { result_digest: string } }
+type PlannedPage = ArtifactPage | SoftDeletePage | RemoveFilePage | ImportFilePage;
+/** #6712 PR 4b: one held `file_drift` page a `--held` selection resolves. */
+interface HeldTarget { hold: GitHoldRecord; side: FileDriftSide; state?: FileDriftDeletedState }
+
+/** The coordinated removal `--prefer database` admits for a held file whose page is deleted (prepared by `prepareDriftFileRemoval`). */
+export const FILE_DRIFT_REMOVE_INTENT = 'managed_maintenance_file_drift_remove';
+const DELETED_CHANGES: Record<DeletedDriftChange, string> = {
+ file_gone: 'the file is gone now, so nothing is left to resolve',
+ live_page: 'a live page records the file again, so it is no longer a deleted-side Decision',
+ no_deletion: 'no deleted page or deletion marker is left at its origin; the next sync re-classifies it',
+ deleted_same: 'the file holds the bytes the deleted page had, so the deletion already stands',
+};
const ALL_DRIFTED_LIMIT = 1000;
const TOP_FIELDS = ['title', 'type', 'compiled_truth', 'timeline'] as const;
@@ -92,7 +119,8 @@ const artifactDirectory = () => join(canonicalFilesystemPath(configDir()), 'repa
const escapePointer = (key: string) => key.replace(/~/g, '~0').replace(/\//g, '~1');
function previewCommand(sourceId: string, opts: RepairPlanOptions): string {
- const select = opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}${opts.since ? ` --since ${opts.since}` : ''}`
+ const select = opts.held ? ` --held${opts.side ? ` --side ${opts.side}` : ''}${opts.state ? ` --state ${opts.state}` : ''}`
+ : opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}${opts.since ? ` --since ${opts.since}` : ''}`
: [...(opts.slugs ?? []).map(slug => ` --slug ${slug}`), ...(opts.requests ?? []).map(id => ` --request ${id}`)].join('');
const globs = [...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])];
return `gbrain repair file-drift --source ${sourceId}${select}${globs.length ? ` ${shellQuote(globs)}` : ''} --prefer ${opts.prefer ?? '<file|database>'}`;
@@ -221,14 +249,71 @@ async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPl
return { slugs: [...slugs].sort(), classes, notSelected: 0 };
}
+/**
+ * #6712 PR 4b `--held`: the source's held `file_drift` pages of one side (and, for a deleted side, one state), narrowed by
+ * the `--only` / `--skip` globs over the held file path. Without `--side` the narrowed holds must all be one Decision;
+ * holds of several sides or states are refused (`file_drift_mixed_selection`), and a deleted side always needs `--state`
+ * (`file_drift_state_required`): its two actions are opposite. Holds an older gbrain wrote with `sides: database` have
+ * no side and are listed with their single-page route.
+ */
+async function selectHeld(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions & { prefer: DriftSide }):
+ Promise<{ targets: HeldTarget[]; notSelected: number; legacy: GitHoldRecord[] }> {
+ const rows = await engine.executeRaw<{ record: GitHoldRecord }>(`SELECT h.completed_keys->0 AS record FROM op_checkpoints h
+ JOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'
+ WHERE h.op=$1 AND s.id=$2 AND h.completed_keys->0->>'code'='file_drift' ORDER BY h.fingerprint`, [GIT_HOLD_OP, sourceId]);
+ const targets: HeldTarget[] = [], legacy: GitHoldRecord[] = [];
+ let notSelected = 0;
+ for (const { record } of rows) {
+ if (!selectedByGlobs(record.path, opts)) { notSelected++; continue; }
+ const side = fileDriftSide(record.meta);
+ if (!side || side === 'deleted' && !record.meta.state) { legacy.push(record); continue; }
+ targets.push({ hold: record, side, ...(side === 'deleted' ? { state: record.meta.state } : {}) });
+ }
+ const key = (target: Pick<HeldTarget, 'side' | 'state'>) => target.state ? `${target.side}/${target.state}` : target.side;
+ const groups = new Map<string, { side: FileDriftSide; state?: FileDriftDeletedState; count: number }>();
+ for (const target of targets) {
+ const group = groups.get(key(target)) ?? { side: target.side, ...(target.state ? { state: target.state } : {}), count: 0 };
+ group.count++; groups.set(key(target), group);
+ }
+ const narrower = (group: { side: FileDriftSide; state?: FileDriftDeletedState }) => shellQuote([...heldDriftPreviewArgv(sourceId, group.side, group.state, opts.prefer),
+ ...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])]);
+ const statusFix = readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] });
+ if (!opts.side && groups.size > 1) {
+ const listed = [...groups.entries()].map(([name, group]) => `${name}=${group.count}`).join(', ');
+ throw opError('file_drift_mixed_selection', `The held file-drift pages of '${sourceId}' are ${groups.size} different Decisions (${listed}); one --prefer must not resolve them in bulk.`,
+ `Nothing was previewed. Preview one Decision at a time: ${[...groups.values()].map(narrower).join('; ')}.`, { fix: statusFix });
+ }
+ const only = !opts.side && groups.size === 1 ? [...groups.values()][0]! : null;
+ if (only?.side === 'deleted') throw stateRequired(sourceId, opts, [only.state!]);
+ return { targets: targets.filter(target => !opts.side || target.side === opts.side && (!opts.state || target.state === opts.state)).slice(0, ALL_DRIFTED_LIMIT),
+ notSelected, legacy };
+}
+
+/** #6712 PR 4b: `--side deleted` without `--state` (or a held selection that is all one deleted state) names the state to resolve. */
+function stateRequired(sourceId: string, opts: RepairPlanOptions, states: readonly FileDriftDeletedState[]): OperationError {
+ const prefer = opts.prefer ?? 'database';
+ const globs = [...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])];
+ const commands = states.map(state => `${shellQuote([...heldDriftPreviewArgv(sourceId, 'deleted', state, prefer), ...globs])} (${state}: --prefer ${prefer} ${fileDriftActionVerb('deleted', state, prefer)})`);
+ return opError('file_drift_state_required', 'Resolving held deleted-side file drift needs --state: --prefer file and --prefer database do opposite things in each state.',
+ `Nothing was previewed. Name the state: ${commands.join('; ')}.`,
+ { fix: readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }) });
+}
+
function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined): asserts opts is RepairPlanOptions & { prefer: DriftSide } {
if (opts?.remote !== false) throw trustedCliRequired('gbrain repair file-drift runs only for the trusted local CLI on the brain host.');
- const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>]) [--only <glob>]... [--skip <glob>]... --prefer file|database';
+ const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>] | --held [--side both|unknown|deleted [--state tombstone_edited|purged_differs|file_gone]]) [--only <glob>]... [--skip <glob>]... --prefer file|database';
if (scope.source_ids.length !== 1) throw opError('invalid_params', 'gbrain repair file-drift needs exactly one --source.', `Name the source: ${usage}`);
if (opts.prefer !== 'file' && opts.prefer !== 'database') throw opError('invalid_params', 'gbrain repair file-drift needs --prefer file or --prefer database.',
`Choose the side whose content wins (protected metadata, tags union, protected takes and private facts are kept either way): ${usage}`);
- const modes = [opts.slugs?.length ? 1 : 0, opts.requests?.length ? 1 : 0, opts.allDrifted ? 1 : 0].reduce((a, b) => a + b, 0);
- if (modes !== 1) throw opError('invalid_params', 'Select pages one way: --slug, --request or --all-drifted.', `Pick one selection: ${usage}`);
+ const modes = [opts.slugs?.length ? 1 : 0, opts.requests?.length ? 1 : 0, opts.allDrifted ? 1 : 0, opts.held ? 1 : 0].reduce((a, b) => a + b, 0);
+ if (modes !== 1) throw opError('invalid_params', 'Select pages one way: --slug, --request, --all-drifted or --held.', `Pick one selection: ${usage}`);
+ if ((opts.side || opts.state) && !opts.held) throw opError('invalid_params', '--side and --state only narrow --held.', `Drop them, or select the held pages with --held: ${usage}`);
+ if (opts.side && !(FILE_DRIFT_SIDES as readonly string[]).includes(opts.side)) throw opError('invalid_params', `Unknown file-drift side '${opts.side}'.`,
+ `Pass --side ${FILE_DRIFT_SIDES.join(', --side ')}; gbrain sources status <source> --json lists each held file's side.`);
+ if (opts.state && !(FILE_DRIFT_DELETED_STATES as readonly string[]).includes(opts.state)) throw opError('invalid_params', `Unknown deleted-side state '${opts.state}'.`,
+ `Pass --state ${FILE_DRIFT_DELETED_STATES.join(', --state ')} with --side deleted; gbrain sources status <source> --json lists each held file's state.`);
+ if (opts.state && opts.side !== 'deleted') throw opError('invalid_params', '--state only narrows --side deleted.', `Drop --state, or pass --side deleted with it: ${usage}`);
+ if (opts.side === 'deleted' && !opts.state) throw stateRequired(scope.source_ids[0]!, opts, FILE_DRIFT_DELETED_STATES);
if (opts.driftClass && !opts.allDrifted) throw opError('invalid_params', '--class only narrows --all-drifted.', `Drop --class, or use it with --all-drifted: ${usage}`);
if (opts.since && !opts.allDrifted) throw opError('invalid_params', '--since only narrows --all-drifted.', `Drop --since, or use it with --all-drifted: ${usage}`);
if (opts.driftClass && !(DRIFT_CLASSES as readonly string[]).includes(opts.driftClass)) throw opError('invalid_params', `Unknown drift class '${opts.driftClass}'.`,
@@ -311,7 +396,7 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,
Promise<{ page: PlannedPage; detail: string } | { skip: string; detail: string }> {
const now = await ghostPageNow(engine, sourceId, slug);
if (!now.ghost) return { skip: `unknown_${now.reason}`, detail: now.reason };
- if (!opts.allDrifted && !selectedByGlobs(now.ghost.path, opts)) return { skip: 'not_selected', detail: now.ghost.path };
+ if (!opts.allDrifted && !opts.held && !selectedByGlobs(now.ghost.path, opts)) return { skip: 'not_selected', detail: now.ghost.path };
const binding = await getWorktreeBinding(engine, sourceId);
const root = join(binding!.local_path!, binding!.relative_path);
const deletion = canonicalDeletionState(root, join(root, ...now.ghost.path.split('/')));
@@ -325,6 +410,98 @@ async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string,
return { page, detail: `recreates its missing file ${now.ghost.path} from the page` };
}
+/**
+ * #6712 PR 4b: the resolution of a held file whose page is deleted (design v3.2 §4): a tombstone at its origin
+ * (`tombstone_edited`) or a deletion marker with no page row left (`purged_differs`). `--prefer database` keeps the
+ * deletion and removes the file through a coordinated publication; `--prefer file` imports the file's bytes through the
+ * managed file repair, which restores the tombstone or creates a new page and leaves the marker for sync to retire.
+ */
+async function deletedPage(engine: BrainEngine, sourceId: string, target: HeldTarget & { state: 'tombstone_edited' | 'purged_differs' }, prefer: DriftSide):
+ Promise<{ page: PlannedPage; detail: string } | { skip: string; detail: string }> {
+ const { hold, state } = target;
+ const live = await readDeletedDriftTarget(engine, sourceId, { path: hold.path, sourcePath: hold.source_path, pageId: hold.page_id });
+ if ('changed' in live) return { skip: `resolved_${live.changed}`, detail: DELETED_CHANGES[live.changed] };
+ if (live.state !== state) return { skip: 'state_changed', detail: `it is ${live.state} now; preview it with ${shellQuote(heldDriftPreviewArgv(sourceId, 'deleted', live.state, prefer, hold.path))}` };
+ const slug = live.tombstone?.slug ?? hold.slug ?? resolveSlugForPath(hold.source_path);
+ const pin: DeletedDriftPin = { state, path: hold.path, source_path: hold.source_path, raw_file_hash: live.raw_file_hash, page_id: live.tombstone?.page_id ?? null,
+ revision: live.tombstone?.revision ?? null, marker_digest: live.marker_digest, observed_at: hold.observed_at };
+ const detail = `${fileDriftActionVerb('deleted', state, prefer)}: ${hold.path}`;
+ if (prefer === 'database') return { page: { slug, prefer, exceptions: [], remove_file: pin }, detail };
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ if ((snapshot ? Number(snapshot.page.id) : null) !== pin.page_id) {
+ return { skip: 'slug_taken', detail: `page ${slug} already exists for another file, so ${hold.path} cannot be imported under that slug; give the file a slug: line of its own, commit it and sync` };
+ }
+ const content = live.raw.toString('utf8');
+ if (!Buffer.from(content).equals(live.raw)) throw opError('invalid_params', 'The held file must contain valid UTF-8.', `Nothing changed. Re-save ${hold.path} in '${sourceId}' as UTF-8, then preview it again.`);
+ const publication = await prepareRepairPublication(engine, { sourceId, slug, sourcePath: hold.source_path, path: hold.path, root: live.root, content, snapshot, base: snapshot,
+ ...await repairScreenConfig(engine, sourceId) });
+ if (publication.status !== 'ready') throw opError('invalid_params', `${hold.path} does not import as written (${publication.status === 'refused' ? publication.refusal.code : 'it would store a canonical overlay'}).`,
+ `Nothing changed. Fix the file, commit it and sync, or preview --prefer database to keep the deletion: ${shellQuote(heldDriftPreviewArgv(sourceId, 'deleted', state, 'database', hold.path))}`);
+ return { page: { slug, prefer, exceptions: [], import_file: { ...pin, result_digest: publication.digest } }, detail };
+}
+
+/** #6712 PR 4b: the deleted-side pin as the preview hash and the publication read it again. */
+async function assertDeletedPin(engine: BrainEngine, sourceId: string, pin: DeletedDriftPin): Promise<NonNullable<Exclude<Awaited<ReturnType<typeof readDeletedDriftTarget>>, { changed: DeletedDriftChange }>>> {
+ const live = await readDeletedDriftTarget(engine, sourceId, { path: pin.path, sourcePath: pin.source_path, pageId: pin.page_id });
+ const why = 'changed' in live ? DELETED_CHANGES[live.changed] : live.state !== pin.state ? `it is ${live.state} now`
+ : live.raw_file_hash !== pin.raw_file_hash ? 'the file bytes changed'
+ : (live.tombstone?.page_id ?? null) !== pin.page_id || (live.tombstone?.revision ?? null) !== pin.revision ? 'the deleted page changed'
+ : live.marker_digest !== pin.marker_digest ? 'its deletion marker changed' : null;
+ if (why !== null || 'changed' in live) throw opError('changed_since_preview', `${pin.path} changed since its file-drift resolution was previewed: ${why}.`,
+ `Nothing was written for ${pin.path}. Preview again with ${shellQuote(heldDriftPreviewArgv(sourceId, 'deleted', pin.state, 'database', pin.path))} (or --prefer file) and apply its new hash.`,
+ { fix: readFix('Lists the held files of this source with their side and state, read-only.', { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }) });
+ return live;
+}
+
+/**
+ * #6712 PR 4b: the preparer of `managed_maintenance_file_drift_remove`, the coordinated removal of a held file whose page is
+ * deleted. It re-reads the deleted side bound to the preview (file bytes, tombstone id and revision or marker value) here
+ * and again under the publication guard, removes the file through the page file target (a recovery record, the Git
+ * effect commits the removal) and clears the hold it resolves in the publishing transaction. The page row is untouched.
+ */
+export async function prepareDriftFileRemoval(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const pin = row.intent?.target as DeletedDriftPin | undefined;
+ if (row.authority.remote || !pin || typeof pin.path !== 'string' || typeof pin.source_path !== 'string' || typeof pin.raw_file_hash !== 'string'
+ || (pin.page_id ?? null) !== (row.page_id === null || row.page_id === undefined ? null : Number(row.page_id))) {
+ throw opError('invalid_params', 'The file-drift removal intent does not name its held file.',
+ `Request ${row.request_id} in source ${row.source_id} does not name the held file it removes, so nothing changed. Preview the repair again with gbrain repair file-drift --source ${row.source_id} --held --side deleted.`);
+ }
+ const live = await assertDeletedPin(engine, row.source_id, pin);
+ return { observedRevision: pin.revision, file: { root: live.root, path: live.path, content: null, expectedBeforeHash: pin.raw_file_hash },
+ validate: async tx => { await assertDeletedPin(tx, row.source_id, pin); },
+ apply: async tx => ({ status: 'file_removed', slug: row.slug, source_id: row.source_id, path: pin.path, state: pin.state,
+ hold_cleared: await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: pin.path, observedAt: pin.observed_at }) }) };
+}
+
+/**
+ * #6712 PR 4b: one held deleted-side page applied as previewed. `remove_file` admits the coordinated removal, bound to the
+ * pin; `import_file` re-reads the pin and submits the managed file repair of the exact previewed bytes and result.
+ */
+async function applyDeletedSide(ctx: OperationContext, page: ApprovedPage, artifact: RemoveFilePage | ImportFilePage, requestId: string, embed: boolean): Promise<RepairItemOutcome> {
+ const pin = 'remove_file' in artifact ? artifact.remove_file : artifact.import_file;
+ const action = 'remove_file' in artifact ? 'remove_file' : 'import_file';
+ try {
+ if ('remove_file' in artifact) {
+ await assertDeletedPin(ctx.engine, page.source_id, pin);
+ const authority = await maintenancePreflight(ctx.engine, page.source_id);
+ if (!authority) throw opError('owner_unavailable', 'Removing a held file needs the managed write path.',
+ `Managed persistence is off for this brain, so ${pin.path} was not removed. Held file-drift pages exist only on managed sources; check the source with gbrain sources status ${page.source_id} --json.`);
+ await submitMaintenanceIntent(ctx.engine, authority, artifact.slug, { kind: FILE_DRIFT_REMOVE_INTENT, expected_revision: pin.revision,
+ ...(pin.page_id !== null ? { deleted_page: true } : {}), target: pin }, requestId);
+ } else {
+ const live = await assertDeletedPin(ctx.engine, page.source_id, pin);
+ await asLocalCli(ctx.engine, () => submitManagedFileRepair(ctx, { sourceId: page.source_id, requestId, slug: artifact.slug, path: pin.path, sourcePath: pin.source_path,
+ content: live.raw.toString('utf8'), beforeHash: pin.raw_file_hash, resultDigest: artifact.import_file.result_digest, ...(pin.revision ? { expected_revision: pin.revision } : {}),
+ noEmbed: !embed, holdObservedAt: pin.observed_at }));
+ }
+ return { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: artifact.prefer, action, state: pin.state } };
+ } catch (error) {
+ if (acceptedPendingReceipt(error) || !(error instanceof OperationError) || ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy', 'write_pending'].includes(error.code)) throw error;
+ const changed = ['changed_since_preview', 'revision_conflict', 'page_identity_changed', 'page_not_found', 'source_changed'].includes(error.code);
+ return { applied: false, outcome: changed ? 'changed_since_preview' : 'refused', reason: error.code, detail: { request_id: requestId, action, message: error.message } };
+ }
+}
+
function item(page: ApprovedPage, index: number, hash: string, last: boolean, prefer: DriftSide): DriftItem {
return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0, action: `prefer_${prefer}`, page, hash, last };
}
@@ -340,7 +517,8 @@ export const fileDriftRepair: RepairHandler = {
const only = [...new Set(opts.only ?? [])].sort();
const skip = [...new Set(opts.skip ?? [])].sort();
const selection = digest({ prefer: opts.prefer, slugs: opts.slugs ?? [], requests: opts.requests ?? [], all: opts.allDrifted === true, class: opts.driftClass ?? null,
- ...(opts.since ? { since: opts.since } : {}), ...(only.length ? { only } : {}), ...(skip.length ? { skip } : {}) });
+ ...(opts.since ? { since: opts.since } : {}), ...(only.length ? { only } : {}), ...(skip.length ? { skip } : {}),
+ ...(opts.held ? { held: true, side: opts.side ?? null, state: opts.state ?? null } : {}) });
if (opts.apply) {
if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair file-drift --apply applies only the set a preview printed.',
`Preview first: ${command} — then run the apply command it prints with --expect <preview-hash>.`, 'docs/guides/repair.md#explicit-only-repair-kinds');
@@ -360,17 +538,40 @@ export const fileDriftRepair: RepairHandler = {
const items = approved.items.map((page, index) => item(page, index, opts.expect!, index === approved.items.length - 1, opts.prefer));
return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
}
- const { slugs, classes, notSelected } = await selectSlugs(engine, sourceId, opts);
+ const held = opts.held ? await selectHeld(engine, sourceId, opts) : null;
+ const { slugs, classes, notSelected } = held ? { slugs: [], classes: new Map<string, DriftClass>(), notSelected: held.notSelected } : await selectSlugs(engine, sourceId, opts);
const assessmentAt = new Date().toISOString();
const pages: PlannedPage[] = [];
const listing: NonNullable<RepairPlan['listing']> = [];
const residuals: Record<string, number> = notSelected ? { not_selected: notSelected } : {};
const count = (key: string) => { residuals[key] = (residuals[key] ?? 0) + 1; };
+ for (const hold of held?.legacy ?? []) {
+ count('legacy_side');
+ listing.push({ item: `${sourceId}:${hold.slug ?? hold.path}`, class: 'legacy_side',
+ detail: `held before holds named a side; preview it alone with gbrain repair file-drift --source ${sourceId} --slug ${hold.slug ?? '<slug>'} --prefer ${opts.prefer}` });
+ }
+ const targets: Array<{ slug: string | null; held?: HeldTarget }> = held ? held.targets.map(target => ({ slug: target.hold.slug, held: target })) : slugs.map(slug => ({ slug }));
await asLocalCli(engine, async () => {
- for (const slug of slugs) {
+ for (const { slug: targetSlug, held: target } of targets) {
+ const label = targetSlug ?? target?.hold.path ?? '';
try {
+ if (target?.state === 'tombstone_edited' || target?.state === 'purged_differs') {
+ const resolved = await deletedPage(engine, sourceId, { ...target, state: target.state }, opts.prefer);
+ if ('skip' in resolved) { count(resolved.skip); listing.push({ item: `${sourceId}:${label}`, class: resolved.skip, detail: resolved.detail }); continue; }
+ await authorizeReconcile(engine, sourceId, resolved.page.slug);
+ pages.push(resolved.page);
+ listing.push({ item: `${sourceId}:${resolved.page.slug}`, class: `prefer_${opts.prefer}`, detail: resolved.detail });
+ continue;
+ }
+ if (targetSlug === null) { count('no_page'); listing.push({ item: `${sourceId}:${label}`, class: 'no_page', detail: 'the hold names no page; the next sync re-classifies it' }); continue; }
+ const slug = targetSlug;
await authorizeReconcile(engine, sourceId, slug);
const live = await liveFileDrift(engine, sourceId, slug);
+ if (target && (target.state === 'file_gone') !== (live.reason === 'canonical_file_missing')) {
+ count('side_changed');
+ listing.push({ item: `${sourceId}:${slug}`, class: 'side_changed', detail: `its file is ${live.reason === 'canonical_file_missing' ? 'gone' : 'present'} now; gbrain sources status ${sourceId} --json shows its current Decision after the next sync` });
+ continue;
+ }
if (live.reason === 'canonical_file_missing') {
const gone = await fileGonePage(engine, sourceId, slug, opts, assessmentAt);
if ('skip' in gone) {
@@ -382,7 +583,7 @@ export const fileDriftRepair: RepairHandler = {
listing.push({ item: `${sourceId}:${slug}`, class: `prefer_${opts.prefer}`, detail: gone.detail });
continue;
}
- if (!opts.allDrifted && !selectedByGlobs(live.path, opts)) { count('not_selected'); continue; }
+ if (!opts.allDrifted && !opts.held && !selectedByGlobs(live.path, opts)) { count('not_selected'); continue; }
if (live.still_present !== true) {
count(live.still_present === false ? 'no_drift' : `unknown_${live.reason}`);
listing.push({ item: `${sourceId}:${slug}`, class: live.still_present === false ? 'no_drift' : 'unknown', detail: live.reason });
@@ -396,12 +597,14 @@ export const fileDriftRepair: RepairHandler = {
} catch (error) {
if (!(error instanceof OperationError) || ['owner_unavailable', 'writer_registration_required'].includes(error.code)) throw error;
count(`refused_${error.code}`);
- listing.push({ item: `${sourceId}:${slug}`, class: 'refused', detail: `${error.code}: ${error.message}` });
+ listing.push({ item: `${sourceId}:${label}`, class: 'refused', detail: `${error.code}: ${error.message}` });
}
}
});
const hash = previewHash({ kind: 'file-drift-v1', brain_id: scope.brain_id, source_id: sourceId, selection,
pages: pages.map(page => 'soft_delete' in page ? [page.slug, page.soft_delete.ghost.revision, ABSENT_FILE_HASH, 'soft_delete']
+ : 'remove_file' in page ? [page.slug, page.remove_file.revision, page.remove_file.raw_file_hash, 'remove_file', page.remove_file.state, page.remove_file.marker_digest]
+ : 'import_file' in page ? [page.slug, page.import_file.revision, page.import_file.raw_file_hash, page.import_file.result_digest, page.import_file.state, page.import_file.marker_digest]
: [page.slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash, page.preview.result_digest]) });
// #6712 wave: a recreated file stays only once committed; without Git durability the next sync imports the committed deletion again.
const recreated = pages.flatMap(page => 'preview' in page && page.file_gone ? [page.preview.preconditions.relative_path] : []);
@@ -423,8 +626,12 @@ export const fileDriftRepair: RepairHandler = {
return { items: pages.map((page, index) => item({ source_id: sourceId, slug: page.slug, artifact_digest: digest(page), selection }, index, hash, index === pages.length - 1, opts.prefer)),
preview_hash: hash, residuals, listing, ...(warnings.length ? { warnings } : {}),
details: { prefer: opts.prefer, ...(artifact ? { artifact } : {}),
- pages: pages.map(page => 'soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, exceptions: page.exceptions }
- : { slug: page.slug, ...(page.file_gone ? { action: 'recreate_file' } : {}), ...(page.class ? { class: page.class } : {}), adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest }),
+ pages: pages.map(page => 'soft_delete' in page ? { slug: page.slug, action: 'soft_delete', path: page.soft_delete.ghost.path, verb: fileDriftActionVerb('deleted', 'file_gone', 'file'), exceptions: page.exceptions }
+ : 'remove_file' in page ? { slug: page.slug, action: 'remove_file', state: page.remove_file.state, path: page.remove_file.path, verb: fileDriftActionVerb('deleted', page.remove_file.state, 'database'), exceptions: page.exceptions }
+ : 'import_file' in page ? { slug: page.slug, action: 'import_file', state: page.import_file.state, path: page.import_file.path, verb: fileDriftActionVerb('deleted', page.import_file.state, 'file'), exceptions: page.exceptions, result_digest: page.import_file.result_digest }
+ : { slug: page.slug, ...(page.file_gone ? { action: 'recreate_file' } : {}), ...(page.class ? { class: page.class } : {}),
+ verb: page.file_gone ? fileDriftActionVerb('deleted', 'file_gone', 'database') : fileDriftActionVerb('both', undefined, page.prefer),
+ adopt_slug_path: page.adopt_slug_path, exceptions: page.exceptions, result_digest: page.preview.result_digest }),
protections: 'Protected metadata stays as the database holds it, tags are the union of both sides, and protected takes and private fact rows are kept; exceptions lists each page\'s.' } };
},
async apply(ctx, entry, opts): Promise<RepairItemOutcome> {
@@ -434,7 +641,8 @@ export const fileDriftRepair: RepairHandler = {
if (!artifact || digest(artifact) !== page.artifact_digest) throw previewChangedError(opts?.expect ?? hash, command);
const requestId = requestIdFor(hash, page);
let outcome: RepairItemOutcome;
- if ('soft_delete' in artifact) {
+ if ('remove_file' in artifact || 'import_file' in artifact) outcome = await applyDeletedSide(ctx, page, artifact, requestId, opts?.embed !== false);
+ else if ('soft_delete' in artifact) {
const retired = await retireGhost(ctx, artifact.soft_delete.ghost, artifact.soft_delete.owner, async () => requestId);
outcome = retired.applied ? { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: 'file', action: 'soft_delete' } }
: { applied: false, outcome: 'changed_since_preview', reason: retired.outcome === 'file_restored' ? 'file_restored' : 'revision_conflict', detail: { request_id: requestId, message: retired.reason } };
@@ -456,6 +664,7 @@ export const fileDriftRepair: RepairHandler = {
},
render(details) {
const lines: string[] = [];
+ for (const page of (details.pages ?? []) as Array<{ slug: string; verb?: string; path?: string }>) if (page.verb) lines.push(` ${page.slug}: ${page.verb}${page.path ? ` (${page.path})` : ''}`);
for (const action of (details.next_actions ?? []) as string[]) lines.push(` ${action}`);
if (typeof details.artifact === 'string') lines.push(` private artifact (each page's resolved result and exceptions): ${details.artifact}`);
if (typeof details.protections === 'string') lines.push(` ${details.protections}`);
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 3426357cd0..330b28df99 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -306,7 +306,10 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'writes each resolved result to a private artifact; --apply --expect <hash> applies exactly that set with request ids derived from the hash, '
+ 'resumable, per page repaired, refused or changed_since_preview. Backups are reconcile\'s own. A selected page whose canonical file is gone from the '
+ 'last commit: --prefer database recreates the file from the page, --prefer file soft-deletes exactly that page (mass-delete valve applies); a file '
- + 'deleted only in the worktree is listed deletion_uncommitted and routed to committing the deletion or repair ghost-pages. Trusted local CLI only; runs only when named.',
+ + 'deleted only in the worktree is listed deletion_uncommitted and routed to committing the deletion or repair ghost-pages. --held [--side both|unknown|deleted '
+ + '[--state tombstone_edited|purged_differs|file_gone]] selects the source\'s held file_drift pages of one Decision (several sides or states are refused; '
+ + '--side deleted needs --state): a deleted page whose file changed is restored and imported (--prefer file) or keeps its deletion while the file is '
+ + 'removed by a coordinated commit (--prefer database); a purged page\'s file is imported as a new page or removed. Trusted local CLI only; runs only when named.',
},
'stuck-recovery': {
handler: stuckRecoveryRepair, embeds: 'none', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
@@ -437,7 +440,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
*/
async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];
slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;
- prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string;
+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean } = {}): Promise<RepairResult> {
const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;
const spec = repairSpec(kind, opts.registry);
@@ -446,7 +449,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : [])],
explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
- keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force });
+ held: run.held, side: run.side, state: run.state, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force });
},
};
}