Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b lane D): file_drift hold side/state meta, deleted-side target reader
garrytanbeefc55b3045
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex a40917271f..b7aeee370c 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -17,7 +17,8 @@ import { localHostId } from './identity.ts';import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';import { isUnboundSourcePage } from './unbound-source.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';-import { digest, requireUuid, sha256, stableJson } from './digest.ts';+import { digest, gitBlobOid, requireUuid, sha256, stableJson } from './digest.ts';+import { SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';import { reconcileCanonical, strictReconcileKeys, validateReconcileJson, type ReconcileConflict, type ReconcileDecision } from './reconcile-merge.ts';import type { ParsedPage } from '../import-file.ts';import type { AutoDecision } from './reconcile-additive.ts';@@ -96,6 +97,62 @@ export function canonicalDeletionState(root: string, path: string): 'in_head' |if (!listed.ok) return 'unknown';return listed.stdout.toString('utf8').split('\0').some(entry => entry.split('\t')[1] === repoPath) ? 'in_head' : 'gone';}+/**+ * #6712 PR 4b: the deleted side of a held `file_drift` file that is present (design v3.2 §4, classifier row 9). A deleted page+ * still at the origin is `tombstone_edited` (the newest one; `pageId` names the held one when it is still there); with no+ * page row left, a `deleted` marker at the origin (`sync-origin-deleted`) is `purged_differs`. The result pins what a+ * resolution is bound to: the file's bytes, the tombstone's id and revision, the marker's value.+ */+export interface DeletedDriftTarget {+ state: 'tombstone_edited' | 'purged_differs';+ root: string;+ /** Absolute path of the file, and its source-relative spelling. */+ path: string;+ relative_path: string;+ source_path: string;+ raw: Buffer;+ raw_file_hash: string;+ tombstone: { page_id: number; slug: string; revision: string } | null;+ marker_digest: string | null;+}+/** Why a held path no longer has a deleted side to resolve; a fresh sync re-classifies it. */+export type DeletedDriftChange = 'file_gone' | 'live_page' | 'no_deletion' | 'deleted_same';+export async function readDeletedDriftTarget(engine: BrainEngine, sourceId: string, input: { path: string; sourcePath: string; pageId?: number | null }):+ Promise<DeletedDriftTarget | { changed: DeletedDriftChange }> {+ 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.');+ }+ const root = realpathSync(join(binding.local_path, binding.relative_path));+ const path = join(root, ...input.path.split('/'));+ if (!isWriteTargetContained(path, root)) throw opError('source_changed', 'The held file is outside its registered source.',+ `Nothing changed. ${input.path} resolves outside source '${sourceId}''s checkout (a symlinked directory or a moved checkout); inspect the owner before previewing again.`);+ try {+ const info = lstatSync(path);+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) throw opError('source_changed', 'The held file is not an ordinary file; repair does not replace it.',+ `Nothing changed. Make ${input.path} in '${sourceId}' a regular file (not a symlink, directory or hard link), then preview again.`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { changed: 'file_gone' };+ throw error;+ }+ const raw = readFileSync(path);+ const pin = { root, path, relative_path: input.path, source_path: input.sourcePath, raw, raw_file_hash: sha256(raw) };+ const claims = await engine.executeRaw<{ id: number; slug: string; deleted: boolean }>(+ `SELECT id, slug, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND source_path=$2 ORDER BY deleted_at DESC NULLS FIRST, id DESC`, [sourceId, input.sourcePath]);+ if (claims.some(row => !row.deleted)) return { changed: 'live_page' };+ const tombstone = claims.find(row => Number(row.id) === input.pageId) ?? claims[0];+ if (tombstone) {+ const snapshot = await engine.readPageSnapshot(tombstone.slug, { sourceId, includeDeleted: true });+ if (!snapshot || Number(snapshot.page.id) !== Number(tombstone.id) || !snapshot.page.deleted_at) staleReconcile('the deleted page changed during the preview');+ return { state: 'tombstone_edited', ...pin, tombstone: { page_id: Number(tombstone.id), slug: tombstone.slug, revision: snapshot.revision }, marker_digest: null };+ }+ const [marker] = await engine.executeRaw<{ value: { kind?: string; blob_oids?: unknown } | null }>('SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',+ [SYNC_ORIGIN_DELETED_OP, `${sourceId}:${binding.source_incarnation}:${input.sourcePath}`]);+ if (!marker?.value || marker.value.kind === 'legacy') return { changed: 'no_deletion' };+ const held = Array.isArray(marker.value.blob_oids) ? marker.value.blob_oids : [];+ if (held.includes(gitBlobOid(raw, 'sha1')) || held.includes(gitBlobOid(raw, 'sha256'))) return { changed: 'deleted_same' };+ return { state: 'purged_differs', ...pin, tombstone: null, marker_digest: digest(marker.value) };+}/** 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)) {diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex a99b0ac37f..85a0d52759 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -83,6 +83,11 @@ export interface PreparationStallMeta {sync_argv: string[];}export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | FenceReason;+/** #6712 PR 4b: the sides a `file_drift` Decision can be about, and the states of a deleted side (design v3.2 §4). */+export const FILE_DRIFT_SIDES = ['both', 'unknown', 'deleted'] as const;+export type FileDriftSide = typeof FILE_DRIFT_SIDES[number];+export const FILE_DRIFT_DELETED_STATES = ['tombstone_edited', 'purged_differs', 'file_gone'] as const;+export type FileDriftDeletedState = typeof FILE_DRIFT_DELETED_STATES[number];export interface GitHoldMeta {reason?: GitHoldReason;@@ -106,6 +111,14 @@ export interface GitHoldMeta {page_revision?: string;/** #6712 PR 1 `file_drift`: which side moved since the page's last recorded import (`unknown`: no usable record); `page_revision` is the page's revision when held. */sides?: 'database' | 'both' | 'unknown';+ /**+ * #6712 PR 4b `file_drift`: which side a Decision is about (design v3.2 §4): `both` (the file and the page moved), `unknown`+ * (no import record says which), `deleted` (one side is a deletion, named by `state`). Absent on holds an older gbrain+ * wrote; `fileDriftSide` reads those from `sides`.+ */+ side?: FileDriftSide;+ /** #6712 PR 4b `file_drift` with `side: 'deleted'`: which deletion the file disagrees with (design v3.2 §4). */+ state?: FileDriftDeletedState;/** #6517 `file_drift`: the page survived a shared-origin delete that kept its file; the fix leads with importing the file. */shared_origin?: true;/** #6340 `concurrent_write`: the revision the entry was frozen against (the page's live revision is `page_revision`). */@@ -206,6 +219,9 @@ export interface GitHoldItem {fence?: FenceHoldLocation;/** #6377 `frontmatter_slug_conflict`: the content-repair lane's last verdict or attempt (codes and slugs). */content_repair?: ContentHoldRepairState;+ /** #6712 PR 4b `file_drift`: the Decision's side, and for a deleted side its state (`GitHoldMeta.side` / `state`). */+ side?: FileDriftSide;+ state?: FileDriftDeletedState;message: string;slug: string | null;/** True when a page exists and keeps its last good revision; false when the file's page is missing. */@@ -569,6 +585,47 @@ export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?:return { argv: frontmatter, commands: [frontmatter.join(' ')], text: frontmatterText };}+/**+ * #6712 PR 4b: the side of a `file_drift` hold. A hold an older gbrain wrote carries only `sides`: `both` and `unknown` read+ * as that side; a `database` hold (a one-sided database move sync no longer holds) has none, so no `--held --side` selects it.+ */+export function fileDriftSide(meta: Pick<GitHoldMeta, 'side' | 'sides'>): FileDriftSide | undefined {+ return meta.side ?? (meta.sides === 'both' || meta.sides === 'unknown' ? meta.sides : undefined);+}++/** #6712 PR 4b: what `gbrain repair file-drift --prefer <prefer>` does to a page of this side and state, as every surface names it. */+export function fileDriftActionVerb(side: FileDriftSide, state: FileDriftDeletedState | undefined, prefer: 'file' | 'database'): string {+ if (side !== 'deleted') return prefer === 'database' ? 'rewrite the file from the page' : 'import the file into the page';+ if (state === 'tombstone_edited') return prefer === 'database' ? 'keep the deletion and remove the file' : 'restore and import';+ if (state === 'purged_differs') return prefer === 'database' ? 'remove the file' : 'import as a new page';+ return prefer === 'database' ? 'recreate the file' : 'soft-delete the page';+}++/** #6712 PR 4b: the bulk preview of the held `file_drift` pages of one side (and deleted state), narrowed to `path` when given. */+export function heldDriftPreviewArgv(sourceId: string, side: FileDriftSide, state: FileDriftDeletedState | undefined, prefer: 'file' | 'database', path?: string): string[] {+ return ['gbrain', 'repair', 'file-drift', '--source', sourceId, '--held', '--side', side, ...(side === 'deleted' && state ? ['--state', state] : []),+ ...(path ? ['--only', path] : []), '--prefer', prefer];+}++/** #6712 PR 4b: the Decision for a `file_drift` hold whose one side is a deletion; each option names its action verb. */+function deletedDriftFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'meta'> & Partial<Pick<GitHoldRecord, 'slug'>>, state: FileDriftDeletedState): Action {+ const source = record.source_id;+ const slug = record.slug ?? '<slug>';+ const revision = record.meta.page_revision ? ` (revision ${record.meta.page_revision})` : '';+ const preview = (prefer: 'database' | 'file') => heldDriftPreviewArgv(source, 'deleted', state, prefer, record.path);+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };+ const what = state === 'tombstone_edited' ? `Page ${slug} was deleted${revision} and ${record.path} then changed, so sync held the file instead of restoring the page or dropping the edit. `+ : state === 'purged_differs' ? `The page of ${record.path} was purged and the file differs from what the brain held, so sync held the file instead of importing it as a new page. `+ : `${record.path} is gone from the last commit but page ${slug} changed${revision}, so sync held the deletion instead of removing a page that changed. `;+ const options = `This preview (writes nothing) shows --prefer database: ${fileDriftActionVerb('deleted', state, 'database')}; ${preview('file').join(' ')} previews --prefer file: `+ + `${fileDriftActionVerb('deleted', state, 'file')}. `;+ return { argv: preview('database'), consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#deleted-canonical-files',+ why: `${what}${options}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 };+}+/*** The exact next step for one hold: the repair preview for frontmatter, the* split or exclude for size, and for a fence hold the step its state calls@@ -617,13 +674,14 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cverify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };}case 'file_drift': {+ if (record.meta.side === 'deleted' && record.meta.state) return deletedDriftFix(record, record.meta.state);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})` : ''}`;const preview = (prefer: 'database' | 'file') => ['gbrain', 'repair', 'file-drift', '--source', source, '--slug', slug, '--prefer', prefer];const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };- const held = `${by} since ${record.path} was last imported, so sync held the file instead of overwriting the database version (${record.meta.sides === 'database' ? 'the file did not change in Git'- : record.meta.sides === 'both' ? 'the file changed too' : 'no import record says which side changed'}). `;+ const held = `${by} since ${record.path} was last imported, so sync held the file instead of overwriting the database version (${record.meta.sides === 'database' && !record.meta.side ? 'the file did not change in Git'+ : fileDriftSide(record.meta) === 'both' ? 'the file changed too' : 'no import record says which side changed'}). `;const decide = 'Decide with the user which version wins, run the apply command the preview prints, then sync again. The rest of the source is not blocked.';// #6517: a shared-origin delete kept the file for this surviving page, and its receipt names importing the file.const shared = record.meta.shared_origin === true;@@ -719,6 +777,8 @@ export function gitHoldItem(record: GitHoldRecord, auto?: FenceAutoRepair): GitH...(record.meta.key ? { key: record.meta.key } : {}), ...(record.meta.line !== undefined ? { line: record.meta.line } : {}),...(fence ? { fence } : {}),...(record.code === 'frontmatter_slug_conflict' && record.meta.content_repair ? { content_repair: record.meta.content_repair } : {}),+ ...(record.code === 'file_drift' && fileDriftSide(record.meta) ? { side: fileDriftSide(record.meta) } : {}),+ ...(record.code === 'file_drift' && record.meta.side === 'deleted' && record.meta.state ? { state: record.meta.state } : {}),message: record.message, slug: record.slug, stale: record.page_id !== null, held_since: record.held_at,fix: gitHoldFix(record, auto), docs: gitHoldDocs(record.code, record.meta.reason, record.meta) };}