Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

repair file-drift: deleted-file modes for a page whose file is gone from the commit; routing by deletion state (#6712 wave)

garrytanb3db044460ea
diff --git a/src/core/persistence/file-claims.ts b/src/core/persistence/file-claims.ts
index 1c4118a76c..ffaf914317 100644
--- a/src/core/persistence/file-claims.ts
+++ b/src/core/persistence/file-claims.ts
@@ -16,8 +16,8 @@
* POSIX the slash-only basename is rechecked on the rows it finds. Tombstones
* are not claimants (#6517): a soft-deleted twin has given the file up.
*/
-import { realpathSync } from 'node:fs';
-import { basename, join } from 'node:path';
+import { existsSync, realpathSync } from 'node:fs';
+import { basename, dirname, join } from 'node:path';
import { pathToFileURL } from 'node:url';
import type { BrainEngine } from '../engine.ts';
import { resolveSourceLocalFilePath } from '../markdown.ts';
@@ -28,9 +28,19 @@ import { recordedPathFromFileUri } from '../write-through.ts';
export interface FileClaimTarget {
sourceId: string; slug: string; pageId: number; root: string; mode: 'git-root' | 'source-root';
path: string; canonicalPath: string; recordedUri: string | null;
+ /** #6712 wave: the target file is gone (`absentCanonicalPath`), so a candidate whose recorded file is gone too claims it by path. */
+ absent?: true;
}
export interface FileClaimant { id: number; slug: string }
+/** A path that may not exist, canonicalized the way `isWriteTargetContained` does: its nearest existing ancestor's realpath plus the rest. */
+export function absentCanonicalPath(path: string): string {
+ const tail: string[] = [];
+ let existing = path;
+ while (!existsSync(existing) && dirname(existing) !== existing) { tail.unshift(basename(existing)); existing = dirname(existing); }
+ return join(realpathSync(existing), ...tail);
+}
+
export function recordedReconcilePath(root: string, page: { slug: string; source_path?: string | null; source_uri?: string | null },
mode: 'git-root' | 'source-root'): string | null {
const path = resolveSourceLocalFilePath(root, page.source_path, page.slug, mode);
@@ -87,7 +97,10 @@ export async function findLiveFileClaimants(engine: BrainEngine, target: FileCla
let canonicalCandidate: string;
try { canonicalCandidate = realpathSync(candidatePath); }
catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ if (target.absent && absentCanonicalPath(candidatePath) === canonicalPath) claimants.push({ id: Number(candidate.id), slug: candidate.slug });
+ continue;
+ }
throw opError('source_changed', 'A candidate canonical file origin could not be verified.',
`Nothing changed. Page ${candidate.slug} in '${sourceId}' records a file that could not be resolved; check that the source checkout is readable, then preview ${slug} again.`);
}
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index da1e0d4ab5..cbb9e86ffd 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -21,7 +21,7 @@ import { preserveProtectedTakes } from './protected-takes.ts';
import { digest, sha256 } from './digest.ts';
import { mergeReconcile, reconcileCanonical, type ReconcileDecision } from './reconcile-merge.ts';
import { stabilizeSafetyAssessments } from './reconcile-safety.ts';
-import { assertReconcilePins, readReconcileState, reconcileFileReading, reconcilePreviewAdopts, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
+import { ABSENT_FILE_HASH, assertReconcilePins, readReconcileState, reconcileFileReading, reconcileReadOptions, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { verifyReconcileBackup } from './reconcile-backup.ts';
import { assertAutoDecisions } from './reconcile-additive.ts';
@@ -131,7 +131,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
`The resolved preview applied by request ${row.request_id} is not ready or names a different source, page or page id than ${row.slug} in source ${row.source_id}. ${freshPreview(row.source_id, row.slug)}`,
{ fix: receiptFix(row) });
}
- const adopt = { adoptSlugPath: reconcilePreviewAdopts(artifact) };
+ const adopt = reconcileReadOptions(artifact);
const state = await readReconcileState(engine, row.source_id, row.slug, artifact.preconditions.assessment_at, adopt);
assertReconcilePins(artifact.preconditions, state.pins);
assertAutoDecisions(artifact.auto_decisions ?? [], state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), artifact.decisions);
@@ -139,12 +139,14 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('canonical policy result changed');
// #6643: a request that asks to keep the file's bytes (repair file-drift --prefer file) leaves a file that already parses to the
// reviewed result as it is; any other difference (a protected key, a tag union, a kept private row) renders the result.
- const keep = row.intent.keep_file_bytes === true && digest(reconcileCanonical(state.file, state.file.tags)) === artifact.result_digest;
+ // #6712 wave: a preview that observed the file absent recreates it from the page and expects no bytes there.
+ const absent = state.pins.raw_file_hash === ABSENT_FILE_HASH;
+ const keep = !absent && row.intent.keep_file_bytes === true && digest(reconcileCanonical(state.file, state.file.tags)) === artifact.result_digest;
const content = keep ? state.raw.toString('utf8') : serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);
const ready = prepared.ready;
return {
observedRevision: state.snapshot.revision, trust: await ownerImportTrust(engine, row, prepared.result.frontmatter, state.path),
- file: { path: state.path, root: state.root, content, expectedBeforeHash: state.pins.raw_file_hash },
+ file: { path: state.path, root: state.root, content, expectedBeforeHash: absent ? null : state.pins.raw_file_hash },
// A database-only page matched by its slug path always records that file as its origin.
noop: ready.noop && sha256(content) === state.pins.raw_file_hash && state.origin === 'recorded',
validate: async tx => {
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index c31334a063..a40917271f 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -1,5 +1,5 @@
-import { lstatSync, readFileSync, realpathSync } from 'node:fs';
-import { join, relative } from 'node:path';
+import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
+import { dirname, join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { loadConfig, loadConfigWithEngine } from '../config.ts';
import { loadOperatorLiterals } from '../content-sanity-literals.ts';
@@ -10,7 +10,7 @@ import { readFix } from '../ops/op-fix.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
-import { findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';
+import { absentCanonicalPath, findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';
import { sharedOriginExit } from './sync-origin.ts';
export { fileClaimCandidatesQuery } from './file-claims.ts';
import { localHostId } from './identity.ts';
@@ -23,6 +23,7 @@ import type { ParsedPage } from '../import-file.ts';
import type { AutoDecision } from './reconcile-additive.ts';
import { publishesDatabaseOnly, readCanonicalAsImported } from './page-prepare.ts';
import { isMirrorOnlyPage } from './mirror-read-only.ts';
+import { hardenedGitSync } from '../hardened-git.ts';
export interface ReconcilePins {
brain_id: string; source_id: string; source_incarnation: string; slug: string; page_id: number;
@@ -68,6 +69,59 @@ export async function reconcilePolicyDigest(engine: BrainEngine, sourceId: strin
const source = row ? { ...row, config: sourceConfig } : row;
return digest({ version: 1, config, source, literals: loadOperatorLiterals(), disabled: process.env.GBRAIN_NO_SANITY ?? null });
}
+/**
+ * #6712 wave: the `raw_file_hash` pin of a preview that observed the canonical file absent (`readReconcileState` with
+ * `fileGone`). No file's sha256 is all zeros, so a file that reappears before apply never matches it.
+ */
+export const ABSENT_FILE_HASH = '0'.repeat(64);
+/** The read options a stored preview implies: its slug-path adoption, and whether it observed the file absent. */
+export function reconcileReadOptions(artifact: Pick<ReconcileArtifact, 'preimages' | 'preconditions'>): { adoptSlugPath: boolean; fileGone: boolean } {
+ return { adoptSlugPath: reconcilePreviewAdopts(artifact), fileGone: artifact.preconditions.raw_file_hash === ABSENT_FILE_HASH };
+}
+/**
+ * #6712 wave: where a missing canonical file's deletion stands in Git. `in_head`: still committed at HEAD (deleted only in
+ * the worktree, staged or not); `gone`: not in HEAD's tree, or the checkout has no commit or no Git; `unknown`: Git
+ * could not say. Filter-free plumbing only, each call bounded (hardened-git.ts).
+ */
+export function canonicalDeletionState(root: string, path: string): 'in_head' | 'gone' | 'unknown' {
+ const limits = { timeoutMs: 10_000, maxBytes: 1024 * 1024 };
+ const top = hardenedGitSync(root, ['rev-parse', '--show-toplevel'], limits);
+ if (!top.ok) return insideGitCheckout(root) ? 'unknown' : 'gone';
+ const head = hardenedGitSync(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], limits);
+ if (!head.ok) return head.reason === 'exit' && head.status === 1 ? 'gone' : 'unknown';
+ let repoPath: string;
+ try { repoPath = relative(realpathSync(top.stdout.toString('utf8').trim()), absentCanonicalPath(path)).split(sep).join('/'); } catch { return 'unknown'; }
+ if (!repoPath || repoPath.startsWith('..')) return 'unknown';
+ const listed = hardenedGitSync(root, ['ls-tree', '-z', '--full-tree', 'HEAD', '--', repoPath], limits);
+ if (!listed.ok) return 'unknown';
+ return listed.stdout.toString('utf8').split('\0').some(entry => entry.split('\t')[1] === repoPath) ? 'in_head' : 'gone';
+}
+/** Whether `root` or an ancestor holds a `.git` entry (a checkout Git should answer for). */
+function insideGitCheckout(root: string): boolean {
+ for (let dir = root; ; dir = dirname(dir)) {
+ if (existsSync(join(dir, '.git'))) return true;
+ if (dirname(dir) === dir) return false;
+ }
+}
+/**
+ * #6712 wave: the route for a page whose canonical file `rel` (source-relative) is missing, by where its deletion stands
+ * in Git: still committed at HEAD goes to committing the deletion or `repair ghost-pages`; gone from HEAD goes to
+ * `repair file-drift`.
+ */
+export function missingFileRoute(sourceId: string, slug: string, rel: string, state: ReturnType<typeof canonicalDeletionState>): string {
+ const fileDrift = `gbrain repair file-drift --source ${sourceId} --slug ${slug} --prefer database`;
+ const ghosts = `gbrain repair ghost-pages --source ${sourceId}`;
+ if (state === 'in_head') return `${rel} is deleted in the worktree but still committed, so this is not file drift: commit the deletion (sync then imports it), or remove the page with ${ghosts}; to keep the page, restore the file from Git (git checkout -- ${rel}) and sync.`;
+ if (state === 'gone') return `${rel} is gone from the last commit. Preview the resolution with ${fileDrift} (recreates the file from the page) or with --prefer file (soft-deletes the page), then apply the printed command after the user decides.`;
+ return `Git could not say whether the deletion of ${rel} is committed. If it is (gone from HEAD), preview ${fileDrift} or --prefer file; if it is deleted only in the worktree, commit the deletion or remove the page with ${ghosts}.`;
+}
+/** The refusal for a canonical file that is gone, routed by where its deletion stands in Git (#6712 wave). */
+function missingCanonicalFile(sourceId: string, slug: string, root: string, path: string): OperationError {
+ const rel = relative(root, path).split(sep).join('/');
+ return opError('source_changed', 'The recorded canonical file is missing.',
+ `Nothing changed. The canonical file of ${slug} in '${sourceId}' is missing. ${missingFileRoute(sourceId, slug, rel, canonicalDeletionState(root, path))}`,
+ { detail: 'canonical_file_missing' });
+}
export function staleReconcile(what: string): never {
throw new OperationError('source_changed', `Reconciliation preview is stale: ${what}.`, 'Generate a fresh preview; submit a corrected intent with a new request ID.');
}
@@ -88,7 +142,7 @@ async function assertSoleFileClaim(engine: BrainEngine, target: FileClaimTarget)
* slug, a never-filed derive-phase page) or a mirror-only page never adopts one.
*/
export async function readReconcileState(engine: BrainEngine, sourceId: string, slug: string, assessmentAt = new Date().toISOString(),
- opts: { adoptSlugPath?: boolean } = {}): Promise<ReconcileState> {
+ opts: { adoptSlugPath?: boolean; fileGone?: boolean } = {}): Promise<ReconcileState> {
const binding = await getWorktreeBinding(engine, sourceId);
if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {
throw new OperationError('owner_unavailable', 'Reconciliation requires the existing active owner on this host.', 'Run repair on the current owner; repair never claims or activates a source.');
@@ -121,9 +175,17 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
const info = lstatSync(path);
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) throw new Error('not an ordinary file');
size = info.size;
- } catch {
- throw opError('source_changed', 'The recorded canonical file is missing or is not an ordinary file; repair does not restore files.',
- `Nothing changed. Restore the canonical file of ${slug} in '${sourceId}' as a regular file (for example from git), then preview the page again.`);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw opError('source_changed', 'The recorded canonical file is not an ordinary file; repair does not replace it.',
+ `Nothing changed. Make the canonical file of ${slug} in '${sourceId}' a regular file (not a symlink, directory or hard link), then preview the page again.`);
+ if (!opts.fileGone || origin !== 'recorded') throw missingCanonicalFile(sourceId, slug, root, path);
+ // #6712 wave: `repair file-drift --prefer database` recreates the file from the page; the preview pins the observed absence.
+ const canonicalPath = absentCanonicalPath(path);
+ await assertSoleFileClaim(engine, { sourceId, slug, pageId: snapshot.page.id, root, mode, path, canonicalPath,
+ recordedUri: recorded ? snapshot.page.source_uri ?? null : null, absent: true });
+ return { binding, root, path, importPath: scannerSourcePath(root, path, mode), raw: Buffer.alloc(0), snapshot, storedPage,
+ file: reconcileCanonical(snapshot.page, snapshot.tags), origin, originSourcePath: null,
+ pins: await reconcilePins(engine, { brain_id: brain.brain_id, sourceId, binding, snapshot, slug, assessmentAt, root, path, canonicalPath, rawFileHash: ABSENT_FILE_HASH }) };
}
const { readJournalLimits } = await import('./limits.ts');
const limits = await readJournalLimits(engine);
@@ -159,12 +221,17 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
throw opError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.',
`Nothing changed. Fix the frontmatter of the canonical file of ${slug} in '${sourceId}' (close the --- block, keep its slug), then preview the page again.`);
}
- const pins: ReconcilePins = { brain_id: brain.brain_id, source_id: sourceId, source_incarnation: snapshot.sourceIncarnation, slug,
- page_id: snapshot.page.id, worktree_id: binding.worktree_id, binding_digest: digest({ binding, root, path: canonicalPath }), owner_epoch: String(binding.owner_epoch),
- revision: snapshot.revision, raw_file_hash: sha256(raw), relative_path: relative(root, path),
- policy_digest: await reconcilePolicyDigest(engine, sourceId), withdrawals_digest: digest({ withdrawals: snapshot.withdrawals, global_purges: snapshot.globalPurges ?? null }), assessment_at: assessmentAt };
+ const pins = await reconcilePins(engine, { brain_id: brain.brain_id, sourceId, binding, snapshot, slug, assessmentAt, root, path, canonicalPath, rawFileHash: sha256(raw) });
return { binding, root, path, importPath, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins, origin, originSourcePath: derived?.sourcePath ?? null };
}
+async function reconcilePins(engine: BrainEngine, input: { brain_id: string; sourceId: string; binding: WorktreeBinding; snapshot: PageSnapshot; slug: string; assessmentAt: string;
+ root: string; path: string; canonicalPath: string; rawFileHash: string }): Promise<ReconcilePins> {
+ const { binding, snapshot, root, path } = input;
+ return { brain_id: input.brain_id, source_id: input.sourceId, source_incarnation: snapshot.sourceIncarnation, slug: input.slug,
+ page_id: snapshot.page.id, worktree_id: binding.worktree_id, binding_digest: digest({ binding, root, path: input.canonicalPath }), owner_epoch: String(binding.owner_epoch),
+ revision: snapshot.revision, raw_file_hash: input.rawFileHash, relative_path: relative(root, path),
+ policy_digest: await reconcilePolicyDigest(engine, input.sourceId), withdrawals_digest: digest({ withdrawals: snapshot.withdrawals, global_purges: snapshot.globalPurges ?? null }), assessment_at: input.assessmentAt };
+}
/** #6394: a preview made with --adopt-slug-path recorded a page with no origin; apply and publication adopt the same pinned file. */
export function reconcilePreviewAdopts(artifact: Pick<ReconcileArtifact, 'preimages'>): boolean {
const stored = (artifact.preimages as { stored_page?: { source_path?: unknown; source_uri?: unknown } | null } | null)?.stored_page;
diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.ts
index 02e8358a6b..a8e7518c98 100644
--- a/src/core/persistence/reconcile.ts
+++ b/src/core/persistence/reconcile.ts
@@ -13,7 +13,7 @@ import { assertPersistenceAccepting, waitForWrite, writeResponse } from './servi
import { digest, requireUuid, sha256, stableJson } from './digest.ts';
import { mergeReconcile, reconcileCanonical, reconcileDecisions, strictReconcileKeys } from './reconcile-merge.ts';
import { additiveDecisions, assertAutoDecisions, classifyDrift, type AutoDecision, type DriftClassification } from './reconcile-additive.ts';
-import { assertReconcilePins, readReconcileState, reconcilePreviewAdopts, staleReconcile, validateReconcileArtifact, type ReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
+import { assertReconcilePins, readReconcileState, reconcilePreviewAdopts, reconcileReadOptions, staleReconcile, validateReconcileArtifact, type ReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { prepareReconcileResult } from './reconcile-prepare.ts';
import { assertReconcileOutputPath, assertReconcileSize, manageReconcileBackups, retainReconcileBackup } from './reconcile-backup.ts';
import type { LocalGrant } from './identity.ts';
@@ -171,7 +171,7 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<stri
try {
assertPersistenceAccepting(engine);
await assertReconcileSize(engine, artifact);
- const adopt = { adoptSlugPath: reconcilePreviewAdopts(artifact) };
+ const adopt = reconcileReadOptions(artifact);
const state = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at, adopt);
assertPreimages(artifact, state);
assertAutoDecisions(artifact.auto_decisions ?? [], state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), artifact.decisions);
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 8793d8053e..a99b0ac37f 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -598,6 +598,17 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
const slug = record.slug ?? '<slug>';
const by = record.meta.competing_request_id ? `${record.meta.competing_operation ?? 'a database'} request ${record.meta.competing_request_id} wrote page ${slug} straight to the database`
: `page ${slug} changed in the database${record.meta.page_revision ? ` (revision ${record.meta.page_revision})` : ''} after the sync enumerated it`;
+ // #6712 wave: a held deletion has no file left to reconcile; repair file-drift resolves a page whose file is gone from the commit.
+ if (record.meta.deleted) {
+ const preview = (prefer: 'database' | 'file') => ['gbrain', 'repair', 'file-drift', '--source', source, '--slug', slug, '--prefer', prefer];
+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };
+ return { argv: preview('database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#deleted-canonical-files',
+ why: `${record.path} was deleted in Git while ${by}, so sync held the deletion instead of removing a page that changed. This preview (writes nothing) keeps the page and recreates its file; `
+ + `${preview('file').join(' ')} previews the deletion instead (soft-deletes exactly that page). Decide with the user, run the apply command the preview prints, then sync again. The rest of the source is not blocked.`,
+ then: { argv: ['gbrain', 'sync', '--source', source, '--no-pull'], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: `Re-screens ${record.path} after the repair (a changed file or page revision re-screens it by itself).` },
+ verify };
+ }
return { argv: ['gbrain', 'sources', 'reconcile', source, slug, '--preview'], consent: [], actor: 'agent', requires_exclusive: false,
why: `${record.path} changed in Git while ${by}, so the two versions diverge and neither was overwritten. `
+ `The reconcile preview shows both and writes nothing; resolve it with the user, apply it, then re-screen the file with gbrain sources retry-held ${source} and gbrain sync --source ${source} --no-pull. The rest of the source is not blocked.`,
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index 819f40dab0..9158cb94d0 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -34,10 +34,18 @@
* every printed preview and apply command. #6712 PR 2: `--since` keeps the pages whose newest
* drift conflict is at or after one concrete instant (the CLI resolves an age once, `since.ts`), part of
* the selection digest and of every printed command. Trusted local CLI only.
+ *
+ * #6712 wave: a selected live page whose canonical file is gone from the last commit (a ghost whose deletion is
+ * committed, such as a held deletion whose page moved) resolves too: `--prefer database` recreates the file from the
+ * page through the same reconcile apply (its preview pins the observed absence, so a file that reappears is
+ * `changed_since_preview`), and `--prefer file` soft-deletes exactly that page through the ghost-page retirement intent
+ * (bound to its revision, path and owner; the mass-delete valve applies). A file deleted only in the worktree (still
+ * committed at HEAD) is not drift: the preview lists it `deletion_uncommitted` with its route (commit the deletion, or
+ * `gbrain repair ghost-pages`) and resolves nothing.
*/
import { randomUUID } from 'node:crypto';
import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { join, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
import { flushDirectory } from '../fs-durable.ts';
@@ -53,7 +61,11 @@ 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 { readReconcileState, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
+import { ABSENT_FILE_HASH, canonicalDeletionState, missingFileRoute, readReconcileState, type ReconcileArtifact } from '../persistence/reconcile-state.ts';
+import { getWorktreeBinding } from '../persistence/ownership.ts';
+import { ghostPageNow, scanGhostSource, type GhostOwner, type GhostPage } from '../ghost-pages.ts';
+import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';
+import { GHOST_PURGE_FUSE_HOURS, GHOST_REPAIR_LIMIT, ghostScanRefusal, massGhosts, massRefusal, retireGhost } from './ghost-pages.ts';
import { prepareReconcileResult } from '../persistence/reconcile-prepare.ts';
import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/reconcile-backup.ts';
import { authorizeReconcile, runReconcileApply } from '../persistence/reconcile.ts';
@@ -66,7 +78,12 @@ export interface DriftException { path: string; reason: 'protected_metadata' | '
interface ApprovedPage { source_id: string; slug: string; artifact_digest: string; selection: string }
interface DriftItem extends RepairItem { page: ApprovedPage; hash: string; last: boolean }
/** One page's prepared resolution: the ready reconcile preview its apply submits, and where it departs from the preferred side. */
-export interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftClass; adopt_slug_path: boolean; exceptions: DriftException[]; result: ParsedPage; preview: ReconcileArtifact }
+export interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftClass; adopt_slug_path: boolean; exceptions: DriftException[]; result: ParsedPage; preview: ReconcileArtifact;
+ /** #6712 wave: the canonical file is gone from the last commit and the apply recreates it from the page. */
+ 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;
const ALL_DRIFTED_LIMIT = 1000;
const TOP_FIELDS = ['title', 'type', 'compiled_truth', 'timeline'] as const;
@@ -148,12 +165,12 @@ function writeArtifact(hash: string, value: unknown): string {
return path;
}
-function readArtifact(hash: string, command: string): Map<string, ArtifactPage> {
+function readArtifact(hash: string, command: string): Map<string, PlannedPage> {
const path = join(artifactDirectory(), `${hash}.json`);
try {
const stat = lstatSync(path);
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('not a regular file');
- const parsed = JSON.parse(readFileSync(path, 'utf8')) as { pages?: ArtifactPage[] };
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as { pages?: PlannedPage[] };
return new Map((parsed.pages ?? []).map(page => [page.slug, page]));
} catch { throw previewChangedError(hash, command); }
}
@@ -264,10 +281,13 @@ async function survey(engine: BrainEngine, scope: RepairScope, opts: Pick<Repair
* reconcile's protections, the size check, and the exceptions. Throws `invalid_params` when a path still needs a
* human decision. The caller runs it as the trusted local CLI and has checked the page is still drifted.
*/
-export async function prepareDriftPage(engine: BrainEngine, sourceId: string, slug: string, prefer: DriftSide, assessmentAt: string): Promise<ArtifactPage> {
+export async function prepareDriftPage(engine: BrainEngine, sourceId: string, slug: string, prefer: DriftSide, assessmentAt: string,
+ opts: { fileGone?: boolean } = {}): Promise<ArtifactPage> {
const snapshotRow = await engine.readPageSnapshot(slug, { sourceId });
- const adopt = !!snapshotRow && !snapshotRow.page.source_path && !snapshotRow.page.source_uri;
- const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: adopt });
+ const adopt = !opts.fileGone && !!snapshotRow && !snapshotRow.page.source_path && !snapshotRow.page.source_uri;
+ const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: adopt, ...(opts.fileGone ? { fileGone: true } : {}) });
+ if (opts.fileGone && state.pins.raw_file_hash !== ABSENT_FILE_HASH) throw opError('source_changed', 'The canonical file reappeared during the preview.',
+ `Nothing was written. The canonical file of ${slug} in '${sourceId}' exists again; preview the page again.`);
const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);
const file = reconcileCanonical(state.file, state.file.tags);
const decisions = preferSideDecisions(state.file, database, prefer);
@@ -278,7 +298,30 @@ export async function prepareDriftPage(engine: BrainEngine, sourceId: string, sl
preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),
decisions, conflicts: [], result: prepared.result, result_digest: digest(prepared.result), status: 'ready' };
await assertReconcileSize(engine, preview);
- return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview };
+ return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview,
+ ...(opts.fileGone ? { file_gone: true as const } : {}) };
+}
+
+/**
+ * #6712 wave: the resolution of a selected page whose canonical file is gone (`canonical_file_missing`), or the reason it
+ * is skipped. Only a deletion gone from HEAD is file-drift's; one still committed at HEAD routes elsewhere.
+ */
+async function fileGonePage(engine: BrainEngine, sourceId: string, slug: string, opts: RepairPlanOptions & { prefer: DriftSide }, assessmentAt: 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 };
+ 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('/')));
+ if (deletion !== 'gone') return { skip: deletion === 'in_head' ? 'deletion_uncommitted' : 'unknown_deletion_state', detail: missingFileRoute(sourceId, slug, now.ghost.path, deletion) };
+ if (opts.prefer === 'file') return { page: { slug, prefer: 'file', exceptions: [], soft_delete: { ghost: now.ghost, owner: now.owner } },
+ detail: `soft-deletes the page: its file ${now.ghost.path} is gone from the last commit (purged after ${GHOST_PURGE_FUSE_HOURS} h; gbrain restore ${slug} --force undoes it until then)` };
+ const page = await prepareDriftPage(engine, sourceId, slug, 'database', assessmentAt, { fileGone: true });
+ if (page.preview.preconditions.revision !== now.ghost.revision || page.preview.preconditions.relative_path.split(sep).join('/') !== now.ghost.path) {
+ throw opError('source_changed', 'The page or its canonical path changed during the preview.', `Nothing was written. Preview ${slug} in '${sourceId}' again.`);
+ }
+ return { page, detail: `recreates its missing file ${now.ghost.path} from the page` };
}
function item(page: ApprovedPage, index: number, hash: string, last: boolean, prefer: DriftSide): DriftItem {
@@ -302,12 +345,23 @@ export const fileDriftRepair: RepairHandler = {
`Preview first: ${command} — then run the apply command it prints with --expect <preview-hash>.`, 'docs/guides/repair.md#explicit-only-repair-kinds');
const approved = await loadApprovedSet<ApprovedPage>(engine, { command: 'file-drift', hash: opts.expect, previewCommand: command });
if (approved.items.some(page => page.selection !== selection || page.source_id !== sourceId)) throw previewChangedError(opts.expect, command);
+ // #6712 wave: soft deletes of pages whose file is gone honor the sync mass-delete valve, as `repair ghost-pages` does.
+ if (opts.prefer === 'file' && approved.items.length > MASS_RECONCILE_MIN_PAGES * MASS_RECONCILE_RATIO) {
+ const planned = readArtifact(opts.expect, command);
+ const deletes = approved.items.filter(page => 'soft_delete' in (planned.get(page.slug) ?? {})).length;
+ if (deletes > MASS_RECONCILE_MIN_PAGES * MASS_RECONCILE_RATIO) {
+ const scan = await scanGhostSource(engine, sourceId, { candidateLimit: GHOST_REPAIR_LIMIT });
+ const refusal = ghostScanRefusal(scan);
+ if (refusal) throw refusal;
+ if (massGhosts(deletes, scan.file_backed) && !massReconcileAllowed()) throw massRefusal(sourceId, deletes, scan.file_backed);
+ }
+ }
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 assessmentAt = new Date().toISOString();
- const pages: ArtifactPage[] = [];
+ 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; };
@@ -316,6 +370,17 @@ export const fileDriftRepair: RepairHandler = {
try {
await authorizeReconcile(engine, sourceId, slug);
const live = await liveFileDrift(engine, sourceId, slug);
+ if (live.reason === 'canonical_file_missing') {
+ const gone = await fileGonePage(engine, sourceId, slug, opts, assessmentAt);
+ if ('skip' in gone) {
+ count(gone.skip);
+ if (gone.skip !== 'not_selected') listing.push({ item: `${sourceId}:${slug}`, class: gone.skip.startsWith('unknown_') ? 'unknown' : gone.skip, detail: gone.detail });
+ continue;
+ }
+ pages.push(gone.page);
+ 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 (live.still_present !== true) {
count(live.still_present === false ? 'no_drift' : `unknown_${live.reason}`);
@@ -335,7 +400,8 @@ export const fileDriftRepair: RepairHandler = {
}
});
const hash = previewHash({ kind: 'file-drift-v1', brain_id: scope.brain_id, source_id: sourceId, selection,
- pages: pages.map(page => [page.slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash, page.preview.result_digest]) });
+ pages: pages.map(page => 'soft_delete' in page ? [page.slug, page.soft_delete.ghost.revision, ABSENT_FILE_HASH, 'soft_delete']
+ : [page.slug, page.preview.preconditions.revision, page.preview.preconditions.raw_file_hash, page.preview.result_digest]) });
let artifact: string | undefined;
if (pages.length) {
await assertReconcileOutputPath(engine, sourceId, artifactDirectory());
@@ -346,7 +412,8 @@ 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,
details: { prefer: opts.prefer, ...(artifact ? { artifact } : {}),
- pages: pages.map(page => ({ slug: page.slug, ...(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, 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 }),
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> {
@@ -356,7 +423,11 @@ 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;
- try {
+ 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 } };
+ } else try {
await asLocalCli(ctx.engine, () => runReconcileApply(ctx.engine, { source_id: page.source_id, slug: page.slug, preview: artifact.preview, request_id: requestId,
...(artifact.prefer === 'file' ? { keep_file_bytes: true } : {}) }));
outcome = { applied: true, outcome: 'repaired', detail: { request_id: requestId, prefer: artifact.prefer } };
diff --git a/src/core/repair/ghost-pages.ts b/src/core/repair/ghost-pages.ts
index 6327e488d8..d3c9d91619 100644
--- a/src/core/repair/ghost-pages.ts
+++ b/src/core/repair/ghost-pages.ts
@@ -101,7 +101,7 @@ export function ghostScanRefusal(scan: GhostSourceScan): OperationError | null {
{ reason: scan.reason, fix: writerStatusFix(scan.source_id), docs: DOCS });
}
-function massRefusal(sourceId: string, ghosts: number, fileBacked: number): OperationError {
+export function massRefusal(sourceId: string, ghosts: number, fileBacked: number): OperationError {
return opError('ghost_mass_delete_refused', `Refusing to soft-delete ${ghosts} of ${fileBacked} file-backed page(s) of source ${sourceId} (more than ${Math.round(MASS_RECONCILE_RATIO * 100)}%).`,
`That many missing files almost always means the checkout is the wrong path, unmounted or half-cloned, not that the files were deleted; nothing was changed. Check the checkout on the owner host first. If removing these pages is genuinely intended, ask the user, then rerun the same apply command with GBRAIN_ALLOW_MASS_RECONCILE=1.`,
{ fix: writerStatusFix(sourceId), docs: DOCS });
@@ -163,7 +163,7 @@ export const ghostPagesRepair: RepairHandler = {
},
async apply(ctx, entry): Promise<RepairItemOutcome> {
const { ghost, owner, hash, last } = entry as GhostItem;
- const outcome = await retireGhost(ctx, ghost, owner);
+ const outcome = await retireGhost(ctx, ghost, owner, () => repairRequestId(ctx, 'ghost-pages', ghost, ghost.revision));
if (last) await clearApprovedSet(ctx.engine, { command: 'ghost-pages', hash });
return outcome;
},
@@ -185,15 +185,15 @@ async function stillApproved(engine: BrainEngine, ghost: GhostPage, owner: Ghost
return null;
}
-async function retireGhost(ctx: OperationContext, ghost: GhostPage, owner: GhostOwner): Promise<RepairItemOutcome> {
+/** Soft-deletes one approved ghost; a managed brain submits it under `requestId()` (also `gbrain repair file-drift --prefer file` on a page whose file is gone, #6712 wave). */
+export async function retireGhost(ctx: OperationContext, ghost: GhostPage, owner: GhostOwner, requestId: () => Promise<string>): Promise<RepairItemOutcome> {
const engine = ctx.engine;
const skip = await stillApproved(engine, ghost, owner);
if (skip) return skip;
if (await managedPersistenceEnabled(engine)) {
const authority = (await maintenancePreflight(engine, ghost.source_id))!;
try {
- await submitMaintenanceIntent(engine, authority, ghost.slug, { kind: GHOST_PAGES_INTENT, expected_revision: ghost.revision, ghost, owner },
- await repairRequestId(ctx, 'ghost-pages', ghost, ghost.revision));
+ await submitMaintenanceIntent(engine, authority, ghost.slug, { kind: GHOST_PAGES_INTENT, expected_revision: ghost.revision, ghost, owner }, await requestId());
} catch (error) {
if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return changed(error.message);
if (error instanceof OperationError && error.code === 'source_changed') return restored(ghost);
diff --git a/test/repair-file-drift-deleted-6712.test.ts b/test/repair-file-drift-deleted-6712.test.ts
index aeada8815f..9139e73c21 100644
--- a/test/repair-file-drift-deleted-6712.test.ts
+++ b/test/repair-file-drift-deleted-6712.test.ts
@@ -148,6 +148,7 @@ for (const backend of testBackends()) describe(`#6712 wave: deleted-file repair
expect([recreate.affected, dropMoved.affected, dropBack.affected]).toEqual([1, 1, 1]);
const local = page('notes/a', 'Written back by hand.');
+ mkdirSync(join(root, 'notes'), { recursive: true });
writeFileSync(join(root, 'notes/a.md'), local);
await bumpRevision(sourceId, 'notes/b');
writeFileSync(join(root, 'notes/c.md'), page('notes/c', 'Restored by hand.'));