Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6712 PR 4b a blocked pass's fence receipt converts in place under the hold policy, and doctor reads the blocked pass

garrytan511a10981d03
diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.ts
index 2cab76f690..54616a7f50 100644
--- a/src/commands/doctor/checks/git-holds.ts
+++ b/src/commands/doctor/checks/git-holds.ts
@@ -106,7 +106,8 @@ function fenceAutoSentence(auto: FenceAutoRepair | undefined): string {
}
/**
- * Sources whose unfinished managed sync cursor is stopped on a failed content refusal (fixed by the next sync, which converts it in place).
+ * Sources whose unfinished managed sync cursor, or (#6712 PR 4b, design v3.2 §3.7) whose newest pass ended `blocked`, is stopped on a
+ * failed content refusal (fixed by the next sync, which converts it in place).
* `fence` marks a source whose refusal is a facts or takes fence (#6188); it is held and repaired by `gbrain repair fences`, not by frontmatter repair.
*/
export async function contentBlockedSources(engine: BrainEngine): Promise<Array<{ source_id: string; fence: boolean }>> {
@@ -114,6 +115,9 @@ export async function contentBlockedSources(engine: BrainEngine): Promise<Array<
r.error_code, r.error_message, r.error_detail FROM op_checkpoints c JOIN persistence_requests r ON r.request_id::text = c.completed_keys->0->'pending'->>'requestId'
AND r.source_id = c.completed_keys->0->>'sourceId'
WHERE c.op = 'managed-sync' AND COALESCE(c.completed_keys->0->>'done','false') <> 'true' AND r.state IN ('failed','conflict','cancelled')
+ UNION ALL SELECT c.completed_keys->0->>'source_id', r.error_code, r.error_message, r.error_detail FROM op_checkpoints c
+ JOIN persistence_requests r ON r.request_id::text = c.completed_keys->0->'obligations'->'blocked'->>'request_id' AND r.source_id = c.completed_keys->0->>'source_id'
+ WHERE c.op = 'managed-sync-pass' AND c.completed_keys->0->'telemetry'->>'outcome' = 'blocked' AND r.state IN ('failed','conflict','cancelled')
ORDER BY 1`).catch(() => []);
const out = new Map<string, boolean>();
for (const row of rows) {
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index b293762003..7b0eba5a4c 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -23,7 +23,7 @@ import type { Cursor, RetryWait } from './sync-run.ts';
import { getWriteRequestById } from './journal.ts';
import type { WriteRequest } from './model.ts';
import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';
-import { recordedStop, replaysUnchangedRefusal } from './sync-stop-class.ts';
+import { fileUnchangedSinceFreeze, recordedStop, replaysUnchangedRefusal } from './sync-stop-class.ts';
import { adoptLegacyPage, syncExcludePatterns, syncGit, type LegacyIdentity, type ManagedSyncContext, type SyncDiscovery, type SyncEntry, type SyncSlugCollision } from './sync-discovery.ts';
import { assertSyncDispatchActive, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
@@ -490,20 +490,32 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
try {
// A page refusal the last pass stopped on replays, with no new request, while what decided it is unchanged (#6712 PR 3, L7).
- // Under the hold policy the next pass re-admits it instead, and its refusal settles as a hold.
+ // Under the hold policy the replay settles that receipt as a hold in place (converted_from_failed, as the cursor's resume
+ // did), so no failed receipt is left behind a newer request for the same bytes.
const blocked = obligations.blocked;
delete obligations.blocked;
- if (blocked && (await readSyncHoldPolicy(engine)).mode === 'fail') {
+ if (blocked) {
const [row] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE source_id=$1 AND request_id=$2', [sourceId, blocked.request_id]);
const failed = row ? await getWriteRequestById(engine, row.id) : null;
const intent = failed?.intent as unknown as SyncIntent | null | undefined;
- const recorded = failed && intent && ['failed', 'conflict', 'cancelled'].includes(failed.state) ? await recordedStop(engine, passFingerprint(sourceId, incarnation), blocked.pass_id) : null;
+ const stopped = failed && intent && ['failed', 'conflict', 'cancelled'].includes(failed.state) ? intent : null;
+ const holds = stopped ? (await readSyncHoldPolicy(engine)).mode !== 'fail' : false;
+ // sync.holds=fail replays while what refused it is unchanged; under the hold policy, while the file has the bytes it froze
+ // (a legacy or compacted receipt included): its settle holds, re-freezes or records it, and the receipt is converted.
+ const recorded = stopped && !holds ? await recordedStop(engine, passFingerprint(sourceId, incarnation), blocked.pass_id) : null;
assertActive();
- if (failed && intent && recorded && replaysUnchangedRefusal(failed, recorded, { root: context.root, intent, target: intent.target ?? '', head: () => head })) {
+ if (failed && stopped && (holds ? fileUnchangedSinceFreeze(context.root, stopped) : recorded && replaysUnchangedRefusal(failed, recorded, { root: context.root, intent: stopped, target: stopped.target ?? '', head: () => head }))) {
+ const intent = stopped;
obligations.blocked = blocked;
- const replay: Cursor = { ...batchCursor([]), runId: blocked.pass_id, pending: { requestId: failed.request_id, slug: failed.slug, pageId: failed.page_id, intent } };
+ // The refused entry rides the replay, so a hold settles that receipt where the policy holds.
+ const refused: PassEntry[] = intent.path ? [{ path: intent.path, sourcePath: intent.sourcePath ?? intent.path, action: intent.kind === 'managed_sync_delete' ? 'delete' : 'import',
+ working: intent.working === true, slug: failed.slug, pageId: failed.page_id, revision: intent.expected_revision == null ? null : String(intent.expected_revision), level: intent.level ?? null }] : [];
+ // A replay that stops again is recorded under the stopped pass's run, which the next pass's replay check reads; one the
+ // hold policy settles is this pass's hold.
+ const replay: Cursor = { ...batchCursor(refused), runId: holds ? passId : blocked.pass_id, replayOf: blocked.pass_id, pending: { requestId: failed.request_id, slug: failed.slug, pageId: failed.page_id, intent } };
const drained = await input.drainBatch(`${PASS_BATCH_KEY_PREFIX}${passId}:${batchNo++}`, replay, sliceBase);
if (!('entries' in drained)) return await stop(drained);
+ delete obligations.blocked;
}
}
for (let round = 1; round <= PASS_MAX_ROUNDS; round++) {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 7ec2a99134..28aa2f14a6 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -148,7 +148,9 @@ export interface Cursor extends SyncDiscovery { runId: string; index: number; au
*/
passId?: string; stamp?: PassStamp; fullEpisode?: string; failureKey?: string; resumeArgs?: string[];
/** #5751 on a pass: the batch indexes a legacy kernel waiver (`contextual_mode`, `canonical_file_differs`) passed; they record no import, so the pass settles them for itself. */
- legacyWaived?: number[]; }
+ legacyWaived?: number[];
+ /** #6712 PR 4b: a pass's replay of the request its last blocked pass stopped on carries that pass's id, under which the stop was recorded. */
+ replayOf?: string; }
export interface CursorProgress { startedAt: number; startIndex: number; lastAt: number; lastIndex: number }
/**
* #6278 (1.5): the breaker state a run carries in its cursor. `stalled` lists the `preparation_stalled` receipts this run
@@ -645,6 +647,11 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:
const fault = stalled || fence ? null : await receiptPageFaultHold(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, entry, pending, done });
const observedAt = run.observedAt ?? new Date().toISOString();
if (!stalled && !fence && !fault && page && fileChangedAfterAdmission(done)) return deferChangedEntry(engine, { cursor, key, pending, assertActive, observedAt, waitMs, base });
+ // #6188 on a pass's replay: a compacted fence-family receipt (its message gone) converts only when the re-screen of the current bytes holds them.
+ if (!stalled && !fence && !fault && cursor.replayOf && done.compacted === true && done.error_message == null && ['invalid_params', 'take_row_collision'].includes(done.error_code ?? '')) {
+ const again = await freezeEntry(engine, { ...base, index: indexOf(cursor, pending) }, key, assertActive, run);
+ return 'hold' in again ? holdUnderGate(engine, { cursor, key, pending, hold: again.hold, assertActive, observedAt, waitMs, base }) : null;
+ }
if (!stalled && !fence && !fault) return null;
const hold = stalled ? preparationStalledHold(entry, pending.slug, pending.pageId, done, pending.intent.content ?? null, pending.intent.blobOid, resumeArgsOf(cursor, run))
: fence ? prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content!, pending.intent.blobOid) : fault!;
@@ -745,7 +752,7 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;
const revived = await reviveCheckpoint(engine, input);
if (revived) { input.assertActive(); return { cursor: revived }; }
const fault = receiptClass(done);
- if (fault === 'transport' || isSyncKnockOn(done) || (fault === 'systemic' && resumableStop(done) && pending.intent.kind !== 'managed_sync_checkpoint' && await stopRecorded(engine, cursor.failureKey ?? key, cursor.runId))) {
+ if (fault === 'transport' || isSyncKnockOn(done) || (fault === 'systemic' && resumableStop(done) && pending.intent.kind !== 'managed_sync_checkpoint' && await stopRecorded(engine, cursor.failureKey ?? key, cursor.replayOf ?? cursor.runId))) {
const refrozen = await refreezeInPlace(engine, input);
if (refrozen) { input.assertActive(); return { cursor: refrozen }; }
}
diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.ts
index f7deee1f10..1e178bf2c7 100644
--- a/test/persistence-sync-fence-holds.test.ts
+++ b/test/persistence-sync-fence-holds.test.ts
@@ -244,7 +244,10 @@ test('a legacy stored-row receipt holds the same bytes from the receipt; a compa
// ...but an arbitrary invalid_params receipt, compacted or not, is never a fence hold: once the file is clean, the next
// plain sync retries it (#6712 PR 3, L7: no --retry-failed) and nothing is held or converted.
- for (const compacted of [false, true]) {
+ // #6712 PR 4b (design v3.2 §3.3, §6): only a pass at the configured selection (its mode included) stamps last_commit, so the
+ // brain is configured for working-tree sync while these working-tree runs check the first sync.
+ await engine.setConfig('sync.include_working_tree', 'true');
+ try { for (const compacted of [false, true]) {
await engine.setConfig('sync.holds', 'fail');
const u = await source(engine, { 'notes/ok.md': note('Ok') });
u.write('notes/draft.md', MALFORMED);
@@ -259,7 +262,7 @@ test('a legacy stored-row receipt holds the same bytes from the receipt; a compa
expect(retried.held ?? []).toEqual([]);
expect(retried.converted_from_failed ?? []).not.toContain(arbitrary!.request_id);
expect(await u.holds()).toEqual([]);
- }
+ } } finally { await engine.unsetConfig('sync.include_working_tree'); }
}), 240_000);
test('dry run lists the fence hold a real run would write and writes nothing', () => each(async engine => {
@@ -392,8 +395,10 @@ test('TE1: a stored take whose prior fence did not parse is updated by its norma
await tx.executeRaw("UPDATE pages SET compiled_truth=$3 WHERE source_id=$1 AND slug=$2", [s.id, 'people/probe', bad.split('---\n').slice(2).join('---\n')]);
await tx.executeRaw("INSERT INTO takes(page_id,row_num,claim,kind,holder,weight) SELECT id,2,'Second take','assessment','brain',0.7 FROM pages WHERE source_id=$1 AND slug=$2", [s.id, 'people/probe']);
}, TEST_WRITE_ATTRIBUTION));
- // That older writer recorded no import provenance (a recorded database-only edit is held #6712 file_drift instead).
- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'page_id'=(SELECT id::text FROM pages WHERE source_id=$2 AND slug=$3)", [SYNC_IMPORT_PROVENANCE_OP, s.id, 'people/probe']);
+ // That older writer was a sync import that recorded its import at the revision it wrote. #6712 PR 4b (design v3.2 §2.3 row 19,
+ // §2.7): an unrecorded database-only edit, followed by a file edit, is a Decision (file_drift), never imported over.
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,revision}',to_jsonb((SELECT knowledge_revision::text FROM pages WHERE source_id=$2 AND slug=$3)))
+ WHERE op=$1 AND completed_keys->0->>'page_id'=(SELECT id::text FROM pages WHERE source_id=$2 AND slug=$3)`, [SYNC_IMPORT_PROVENANCE_OP, s.id, 'people/probe']);
s.write('people/probe.md', bad); commit(s.root, 'invented kind');
const result = await s.sync();
expect(result).toMatchObject({ status: 'synced', fences_normalized: { count: 1, by_class: { kind_map: 1 } } });