Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): #6712 PR 4b pass defects in the remaining pass-era rows
garrytan8f094b10454c
diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.tsindex e17d52b2dd..34f2bff0dc 100644--- a/src/commands/sync/report.ts+++ b/src/commands/sync/report.ts@@ -112,8 +112,9 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = pcase 'dry_run':break; // already printed in performSynccase 'blocked_by_failures': {- if (result.runId) {- write(`Sync BLOCKED at ${result.toCommit}: committed counts are cumulative for run ${result.runId}.`);+ if (result.runId || (result.pass && result.failures?.length)) {+ write(result.runId ? `Sync BLOCKED at ${result.toCommit}: committed counts are cumulative for run ${result.runId}.`+ : `Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed.`);for (const failure of result.failures ?? []) write(` ${formatManagedSyncFailure(failure)}`);const retries = [...new Set((result.failures ?? []).map(failure => managedSyncRetryCommand(failure)))];write(retries.lengthdiff --git a/src/core/persistence/sync-admission.ts b/src/core/persistence/sync-admission.tsindex 9c3a74fbf8..7249882733 100644--- a/src/core/persistence/sync-admission.ts+++ b/src/core/persistence/sync-admission.ts@@ -67,11 +67,27 @@ export async function readSyncAdmissionSetting(engine: Exec): Promise<SyncAdmissreturn { ...setting, set_at: iso(raw_set_at) };}+/** The raw setting row: the stored config value and the dating row's value and `set_at`. */+export interface SyncAdmissionSettingRow { stored: string | null; row_value: string | null; set_at: string | null }++/**+ * The setting's columns and joins for a read that folds it in (`sync status` rides its source read, keeping its statement+ * budget): `$k`..`$k+2` bind `SYNC_ADMISSION_SETTING_PARAMS`, and the columns are `admission_stored`, `admission_row_value`+ * and `admission_set_at`.+ */+export const syncAdmissionSettingSql = (k: number) => ({+ columns: `ac.value AS admission_stored, ao.completed_keys->0->>'value' AS admission_row_value, ao.completed_keys->0->>'set_at' AS admission_set_at`,+ joins: `LEFT JOIN config ac ON ac.key=$${k} LEFT JOIN op_checkpoints ao ON ao.op=$${k + 1} AND ao.fingerprint=$${k + 2}` });+export const SYNC_ADMISSION_SETTING_PARAMS = [SYNC_ADMISSION_KEY, SYNC_ADMISSION_SET_OP, SET_FINGERPRINT];+async function readSetting(engine: Exec): Promise<Omit<SyncAdmissionSetting, 'set_at'> & { raw_set_at: string | null }> {- const [row] = await engine.executeRaw<{ stored: string | null; row_value: string | null; set_at: string | null }>(+ const [row] = await engine.executeRaw<SyncAdmissionSettingRow>(`SELECT c.value AS stored, o.completed_keys->0->>'value' AS row_value, o.completed_keys->0->>'set_at' AS set_atFROM (SELECT 1) one LEFT JOIN config c ON c.key=$1 LEFT JOIN op_checkpoints o ON o.op=$2 AND o.fingerprint=$3`,- [SYNC_ADMISSION_KEY, SYNC_ADMISSION_SET_OP, SET_FINGERPRINT]);+ SYNC_ADMISSION_SETTING_PARAMS);+ return settingOf(row);+}+function settingOf(row: SyncAdmissionSettingRow | undefined): Omit<SyncAdmissionSetting, 'set_at'> & { raw_set_at: string | null } {const stored = row?.stored ?? null;return { value: parseSyncAdmission(stored), stored, raw_set_at: stored !== null && row?.row_value === stored ? row.set_at : null };}@@ -92,10 +108,10 @@ export async function writeSyncAdmission(engine: Pick<BrainEngine, 'transaction'* `sync status`'s `admission` of one source incarnation (design §8). `effective` is always true for `normal`; otherwise* it is false while the source's pass row is `open` with `started_at` before `set_at` and its `lease_token` holds the* live drain lease, or while a destructive request of the incarnation admitted before `set_at` is still queued,- * running or recovering.+ * running or recovering. `read` is the setting row a caller already read with `syncAdmissionSettingSql`.*/-export async function syncAdmissionStatus(engine: Exec, sourceId: string, incarnation: string): Promise<SyncAdmissionStatus> {- const { value, raw_set_at } = await readSetting(engine);+export async function syncAdmissionStatus(engine: Exec, sourceId: string, incarnation: string, read?: SyncAdmissionSettingRow): Promise<SyncAdmissionStatus> {+ const { value, raw_set_at } = read ? settingOf(read) : await readSetting(engine);const set_at = iso(raw_set_at);if (value === 'normal') return { value, set_at, effective: true };const [row] = await engine.executeRaw<{ pinned: boolean; destructive: boolean }>(`SELECTdiff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 692f1e11a0..1fac77e000 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -340,14 +340,25 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stif (!prior || (prior.deleted && !row.deleted) || (prior.deleted === row.deleted && Number(row.id) > Number(prior.id))) byOrigin.set(key, row);}const domain = new Set<string>([...tree.keys(), ...untracked, ...(mode === 'working' ? [...index.keys()].filter(eligible) : []), ...[...byOrigin.keys()].filter(eligible), ...[...markers.keys()].map(gitPathOf).filter(eligible)]);- // Spellings of one origin that differ only by case or separator: the domain holds each path once, so a count is enough.+ // Spellings of one origin that differ only by case or separator (the domain holds each path once).const fold = (path: string) => path.replaceAll('\\', '/').toLowerCase();- const spellings = new Map<string, number>();- // Only spellings that are files at L count (discovery's case-only respelling whose old file this sync removes is no refusal).+ const spellings = new Map<string, string[]>();+ // Files at L count, and so does a live page's separator-spelled origin; a case-only respelling whose old file this sync+ // removes is no refusal (discovery's one exception).for (const path of domain) {- if (!tree.has(path) && !(mode === 'working' && (untracked.has(path) || index.has(path)))) continue;+ const live = byOrigin.get(path);+ if (!tree.has(path) && !(mode === 'working' && (untracked.has(path) || index.has(path))) && !(live && !live.deleted && live.source_path.includes('\\'))) continue;const folded = fold(path);- spellings.set(folded, (spellings.get(folded) ?? 0) + 1);+ spellings.set(folded, [...spellings.get(folded) ?? [], path]);+ }+ // As discovery does, only spellings that name one page are twins: a live origin's page slug, else the slug its path names.+ const twins = new Set<string>();+ for (const paths of spellings.values()) {+ if (paths.length < 2) continue;+ const slugOf = (path: string) => { const live = byOrigin.get(path); return live && !live.deleted ? live.slug : resolveSlugForPath(originOf(path)); };+ const bySlug = new Map<string, string[]>();+ for (const path of paths) bySlug.set(slugOf(path), [...bySlug.get(slugOf(path)) ?? [], path]);+ for (const group of bySlug.values()) if (group.length > 1) for (const path of group) twins.add(path);}const reconcilable = [...byOrigin.entries()].filter(([path, row]) => !row.deleted && eligible(path)).length;timings.domain = t();@@ -409,7 +420,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stpublished: !!attested?.hash && probe?.rawSha256 === attested.hash,hold: hold ? { atLevel: holdAtLevel(hold, level, probe?.rawSha256 ?? null) && !moved.has(path), rescreenDue: holdRescreenDue(hold, retry.has(hold.path)), retried: retry.has(hold.path) } : null,marker: marker ?? virtualMarker, baseline: needsBaseline ? await baselineOf(path) : null,- spelling: (spellings.get(fold(path)) ?? 0) > 1,+ spelling: twins.has(path),episodeUnsatisfied: input.pass ? !!input.pass.episodeFullId && !!row && !row.deleted && record?.full_episode !== input.pass.episodeFullId: input.full === true && !!row && !row.deleted,fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true,diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 5c94d534c7..580008d63c 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -51,7 +51,7 @@ import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';import { publicFailureDetail } from './publication-failure.ts';-import { dependentHold, fileDriftHold, sharedOriginSurvivor, fileChangedAfterAdmission, headCommittedBytes, idempotentDeletionProof, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';+import { dependentHold, fileDriftHold, sharedOriginSurvivor, fileChangedAfterAdmission, headCommittedBytes, liveRevision, idempotentDeletionProof, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';import { faultPoint } from './fault-points.ts';import { syncCursorOptions } from './sync-slices.ts';import { pipelined } from '../page-state/transactions.ts';@@ -1448,8 +1448,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP}// #6712 PR 4b (design v3.2 §2): a pass's write refused because its file changed after admission is the level moving, not a// page failure: the entry is passed over and the next round classifies the new level (a level that never settles ends the- // pass not_converged). A pinned-worktree conflict is not: it settles as a worktree_dirty hold below.- if (cursor.passId && fileChangedAfterAdmission(done)) {+ // pass not_converged). A pinned-worktree conflict is not: it settles as a worktree_dirty hold below. So is an import whose+ // page identity another writer changed after the freeze (a repair created the page at its slug): its page moved.+ if (cursor.passId && (fileChangedAfterAdmission(done) || (done.error_code === 'page_identity_changed'+ && await liveRevision(engine, context.sourceId, pending) !== (pending.intent.expected_revision == null ? null : String(pending.intent.expected_revision))))) {cursor = await saveCursor(engine, key, cursor, committedPast({ ...cursor, counts: { ...cursor.counts } }, pending));assertActive();continue;diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 63007507e6..ba48d0b435 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -45,6 +45,7 @@ import { sha256 } from './digest.ts';import { passResumeArgs } from './sync-pass-readers.ts';import { passConvergence, passStatusNext, passStatusState } from './sync-pass-status.ts';import { MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, type PassRow } from './sync-pass-row.ts';+import { SYNC_ADMISSION_SETTING_PARAMS, syncAdmissionSettingSql, syncAdmissionStatus } from './sync-admission.ts';import type { DeletesWithheld } from './sync-markers.ts';import { listIdentityDowngrades } from '../sync-identity-downgrades.ts';@@ -242,11 +243,14 @@ function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHoexport async function readSyncStatus(engine: BrainEngine, sourceId: string, opts: { detail?: boolean } = {}): Promise<SyncStatus> {const detail = opts.detail !== false;// #6712 PR 4b (design §9): the pass row and the withheld-delete record ride the source read (primary-key probes), so the plain status keeps its statement budget.- const [source] = await engine.executeRaw<{ incarnation: string; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null }>(- `SELECT s.incarnation::text AS incarnation, p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld FROM sources s+ const admissionSql = syncAdmissionSettingSql(4);+ const [source] = await engine.executeRaw<{ incarnation: string; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;+ admission_stored: string | null; admission_row_value: string | null; admission_set_at: string | null }>(+ `SELECT s.incarnation::text AS incarnation, p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns} FROM sources sLEFT JOIN op_checkpoints p ON p.op=$2 AND p.fingerprint=s.id||':'||s.incarnation::textLEFT JOIN op_checkpoints w ON w.op=$3 AND w.fingerprint=s.id||':'||s.incarnation::text- WHERE s.id=$1 AND s.archived IS NOT TRUE`, [sourceId, MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP]);+ ${admissionSql.joins}+ WHERE s.id=$1 AND s.archived IS NOT TRUE`, [sourceId, MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, ...SYNC_ADMISSION_SETTING_PARAMS]);if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');const selected = await cursorHeader(engine, sourceId, source.incarnation, failures[0]?.cursor_key ?? null);@@ -322,7 +326,8 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts: { status: 'unknown' as const, reason: 'not_read: run sync status with --detail', recovery_next: recovery.status === 'ok' && recovery.first ? recoveryAction(sourceId, recovery.first) : undefined };const connectorLastError = await (await import('./connector-status.ts')).readConnectorLastError(engine, sourceId);const [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });- const admission = await (await import('./sync-admission.ts')).syncAdmissionStatus(engine, sourceId, source.incarnation);+ const admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,+ { stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at });const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume) : null;return { source_id: sourceId, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,