Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(#6712 PR 4b lane A): route non-company managed sync through the live pass

garrytana00f317671b9
diff --git a/src/core/persistence/sync-pass-batch.ts b/src/core/persistence/sync-pass-batch.ts
index 21d8a91da8..a01c7900bc 100644
--- a/src/core/persistence/sync-pass-batch.ts
+++ b/src/core/persistence/sync-pass-batch.ts
@@ -58,6 +58,20 @@ export function passRequestId(passId: string, path: string, level: string | null
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
+/**
+ * The converged watermark a pass records (design v3.2 §2.2): the worktree's highest request `sequence`, and the requests
+ * (`r:<id>`) and Git effects (`e:<id>`) still open, at most `cap` (null above it: no idle until a full round re-reads).
+ */
+export async function readConvergedWatermark(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, selfRequestId: string | null, cap: number):
+ Promise<{ request_hwm: string; open_at_stamp: string[] | null }> {
+ const [hwm] = await tx.executeRaw<{ hwm: string | null }>('SELECT max(sequence)::text AS hwm FROM persistence_requests WHERE worktree_id=$1::uuid', [worktreeId]);
+ const open = await tx.executeRaw<{ id: string }>(`(SELECT 'r:'||request_id::text AS id FROM persistence_requests
+ WHERE worktree_id=$1::uuid AND state IN ('queued','running','recovering') AND request_id IS DISTINCT FROM $2::uuid LIMIT $3)
+ UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)`, [worktreeId, selfRequestId, cap + 1]);
+ return { request_hwm: hwm?.hwm ?? '0', open_at_stamp: open.length > cap ? null : open.map(row => row.id) };
+}
+
/** A round batch's entry: the discovery shape plus the level `L` it was classified at (the request identity's third part). */
export interface PassEntry extends SyncEntry { level: string | null }
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 3202a2e8ae..73d541a0f8 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -20,12 +20,12 @@ import type { Cursor, RetryWait } from './sync-run.ts';
import { syncExcludePatterns, syncGit, type ManagedSyncContext, type SyncSlugCollision } from './sync-discovery.ts';
import type { SyncAuthority, SyncProcessingOptions } from './sync-authority.ts';
import type { PassStamp, SyncCursorOptions } from './sync-prepare.ts';
-import { passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,
+import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,
type PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';
import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';
import { passIdleProbe, readShadowLevel, type ShadowLevel, type ShadowPath } from './sync-pass.ts';
import { syncPassKind } from './sync-classify.ts';
-import { PASS_BATCH_KEY_PREFIX, setPassBatch, SyncAdmissionPaused, type PassEntry } from './sync-pass-batch.ts';
+import { PASS_BATCH_KEY_PREFIX, readConvergedWatermark, SyncAdmissionPaused, type PassEntry } from './sync-pass-batch.ts';
import { assertDrainLease, currentDrainLease } from './sync-lease.ts';
import { digest } from './digest.ts';
import { readSyncTail } from './sync-tail-record.ts';
@@ -73,7 +73,7 @@ const parserFingerprint = () => digest(['x.md', 'x.ts', 'x.png'].map(path => syn
*/
async function retireLegacyCursors(engine: BrainEngine, input: { sourceId: string; incarnation: string; remote: boolean; assertActive: () => void }):
Promise<{ wait?: RetryWait; hostRequired?: true; episode?: PassEpisode }> {
- const resolution = await resolveManagedCursor(engine, { sourceId: input.sourceId, incarnation: input.incarnation, company: null, assertActive: input.assertActive, foldIn: !input.remote });
+ const resolution = await resolveManagedCursor(engine, { sourceId: input.sourceId, incarnation: input.incarnation, company: undefined, assertActive: input.assertActive, foldIn: !input.remote });
if (resolution.waitFor) return { wait: { ...resolution.waitFor, retry_after_ms: 5000 } };
const [row] = await engine.executeRaw<{ header: { runId?: string; done?: boolean; processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions & { exclude?: string[]; includeHidden?: string[]; strategy?: string; srcSubpath?: string; workingTree?: boolean } } | null }>(
"SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [resolution.key]);
@@ -221,9 +221,10 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const requested = input.processingOptions;
if (opts.full && !obligations.episode?.full_id) obligations.episode = { opened_at: startedAt, full_id: passId, selection,
inherited: { noEmbed: requested.noEmbed, noExtract: requested.noExtract, noSchemaPack: requested.noSchemaPack, from: obligations.episode?.inherited.from ?? 'flag' } };
- else if (!obligations.episode && (requested.noEmbed || requested.noExtract || requested.noSchemaPack)) obligations.episode = { opened_at: startedAt, selection,
- inherited: { noEmbed: requested.noEmbed, noExtract: requested.noExtract, noSchemaPack: requested.noSchemaPack, from: 'flag' } };
- const episode = obligations.episode;
+ // A pass that admits under an opt-out opens an episode carrying it (design §6), when it admits its first batch.
+ const optOutEpisode: PassEpisode | null = !obligations.episode && (requested.noEmbed || requested.noExtract || requested.noSchemaPack) ? { opened_at: startedAt, selection,
+ inherited: { noEmbed: requested.noEmbed, noExtract: requested.noExtract, noSchemaPack: requested.noSchemaPack, from: 'flag' } } : null;
+ let episode = obligations.episode;
// A flagless pass keeps the open episode's opt-outs (#6712 PR 1's inherited_options contract).
const processingOptions: SyncProcessingOptions = { noEmbed: requested.noEmbed || !!episode?.inherited.noEmbed, noExtract: requested.noExtract || !!episode?.inherited.noExtract,
noSchemaPack: requested.noSchemaPack || !!episode?.inherited.noSchemaPack };
@@ -299,10 +300,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const drain = async (entries: PassEntry[], stamp?: PassStamp): Promise<SyncResult | null> => {
const key = `${PASS_BATCH_KEY_PREFIX}${passId}:${batchNo++}`;
const batch = batchCursor(entries, stamp);
- setPassBatch(key, batch, JSON.stringify({ runId: passId, index: 0 }));
- let drained: SyncResult | Cursor;
- try { drained = await input.drainBatch(key, batch, sliceBase); }
- finally { setPassBatch(key, null); }
+ const drained = await input.drainBatch(key, batch, sliceBase);
if ('entries' in drained) {
const c = drained.counts;
Object.assign(counts, { added: counts.added + c.added, modified: counts.modified + c.modified, deleted: counts.deleted + c.deleted, renamed: counts.renamed + (c.renamed ?? 0),
@@ -336,7 +334,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const r = entry.result;
if (r.settled) continue;
if (r.inFlight) { inFlight.push(entry); continue; }
- if (S.has(settledKey(entry.path, entry.state.level))) { mismatch.push(entry); continue; }
+ if (S.has(settledKey(entry.path, entry.state.level))) {
+ // A hold this pass wrote or re-screened at L is that path's fate here, even when its code re-screens every pass.
+ if (entry.state.hold?.atLevel) continue;
+ mismatch.push(entry); continue;
+ }
if (r.action === 'delete') {
if (admission !== 'normal') { S.set(settledKey(entry.path, entry.state.level), 'paused_deletes'); counts.pausedDeletes++; continue; }
deletes.push(entry);
@@ -357,6 +359,24 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (!candidates) {
if (mismatch.length || owed.length) break;
if (remote) { await save('blocked', 'reconcile_host_required'); return result('blocked_by_failures', 'reconcile_host_required'); }
+ if (round === 1 && configured && context.source.last_commit === head && !episode && !retry.length && !tail) {
+ // v3 §3.3: a pass that finds nothing at last_commit = T admits no checkpoint; it keeps master's up_to_date (only
+ // last_sync_at), and its full round refreshes the converged watermark so the next tick can be idle.
+ const at = new Date().toISOString();
+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {
+ assertActive();
+ await assertDrainLease(tx, sourceId);
+ await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);
+ const watermark = await readConvergedWatermark(tx, context.binding.worktree_id, null, OPEN_AT_STAMP_CAP);
+ value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,
+ last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };
+ Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, stuck_since: null });
+ value.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, remaining: 0, duration_ms: Date.now() - started, counts: { ...counts } };
+ await writePassRow(tx, value);
+ }, principalAttribution(authority.writer.principal)));
+ await clearPassFailures(engine, sourceId, incarnation);
+ return { ...result('up_to_date'), fromCommit: remote ? null : head };
+ }
const closesEpisode = !!episode && configured;
const stamp: PassStamp = { leaseToken: lease.token, incarnation, configured, stampChunker: configured && (context.source.last_commit === null || (closesEpisode && !!episode?.full_id)),
closesEpisode, retryTaken: [...retry], releasedHolds: [], selectionFp, parserFp, pack, full: kind === 'full',
@@ -364,6 +384,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
await save('open', null);
const stopped = await drain([], stamp);
if (stopped) return stop(stopped);
+ value.telemetry = { ...value.telemetry, outcome: 'synced', stop_reason: configured ? null : 'selection_scoped', remaining: 0 };
await clearPassFailures(engine, sourceId, incarnation);
return result(configured && context.source.last_commit === null ? 'first_sync' : 'synced', configured ? undefined : 'selection_scoped');
}
@@ -372,6 +393,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
for (const entry of [...built.skipped, ...built.collisions.flatMap(c => c.skipped.map(sourcePath => imports.find(i => entryPaths(level, i.path).sourcePath === sourcePath)!))].filter(Boolean)) {
S.set(settledKey(entry.path, entry.state.level), 'collision'); counts.collisions++;
}
+ if (optOutEpisode && !value.obligations.episode && built.entries.length) value.obligations.episode = episode = optOutEpisode;
for (let i = 0; i < built.entries.length; i += PASS_BATCH_MAX) {
const chunk = built.entries.slice(i, i + PASS_BATCH_MAX);
const stopped = await drain(chunk);
@@ -405,7 +427,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
/** A converged or idle pass clears what earlier stops recorded: the pass row's failure key and the incarnation's cursor key. */
async function clearPassFailures(engine: BrainEngine, sourceId: string, incarnation: string): Promise<void> {
await clearManagedSyncFailureAfterSuccess(engine, passFingerprint(sourceId, incarnation));
- await clearManagedSyncFailureAfterSuccess(engine, managedCursorKey(incarnation, null));
+ await clearManagedSyncFailureAfterSuccess(engine, managedCursorKey(incarnation, undefined));
}
export type { SyncAdmission };
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 8beede7a90..463e19e6bc 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -50,6 +50,7 @@ import { recordPassTail, recordSyncTail } from './sync-tail-record.ts';
import { readPassRow, writePassRow, OPEN_AT_STAMP_CAP, type ManagedSyncPassValue } from './sync-pass-row.ts';
import { admissionAllows, readSyncAdmission } from './sync-admission.ts';
import { syncLockId } from '../db-lock.ts';
+import { readConvergedWatermark } from './sync-pass-batch.ts';
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { chunkerStamp } from '../chunkers/code.ts';
import { clearGitHold, clearGitHoldRetryPaths, countGitHolds, recordSyncImportProvenance, syncDiskProvenance, syncImportParser, syncImportParserFor, type SyncImportProvenanceBase } from './sync-holds.ts';
@@ -516,14 +517,10 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn
await recordPassTail(tx, row.source_id, p.passId!, { changed: stamp.changed, extract: stamp.extract });
for (const path of stamp.releasedHolds) await releaseHold(tx, path);
if (stamp.retryTaken.length) await clearGitHoldRetryPaths(tx, row.source_id, stamp.incarnation, stamp.retryTaken);
- const [hwm] = await tx.executeRaw<{ hwm: string | null }>('SELECT max(sequence)::text AS hwm FROM persistence_requests WHERE worktree_id=$1::uuid', [row.worktree_id]);
- const openIds = await tx.executeRaw<{ id: string }>(`(SELECT 'r:'||request_id::text AS id FROM persistence_requests
- WHERE worktree_id=$1::uuid AND state IN ('queued','running','recovering') AND request_id<>$2::uuid LIMIT $3)
- UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
- WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)`, [row.worktree_id, row.request_id, OPEN_AT_STAMP_CAP + 1]);
+ const watermark = await readConvergedWatermark(tx, row.worktree_id!, row.request_id, OPEN_AT_STAMP_CAP);
const value: ManagedSyncPassValue = structuredClone(pass.value);
const at = new Date().toISOString(), prior = value.obligations.converged;
- value.obligations.converged = { target: p.target, at, request_hwm: hwm?.hwm ?? '0', open_at_stamp: openIds.length > OPEN_AT_STAMP_CAP ? null : openIds.map(open => open.id),
+ value.obligations.converged = { target: p.target, at, ...watermark,
parser_fp: stamp.parserFp, pack: stamp.pack, selection_fp: stamp.selectionFp, last_full_at: stamp.full || !prior ? at : prior.last_full_at,
passes_since_full: stamp.full || !prior ? 0 : prior.passes_since_full + 1 };
if (stamp.closesEpisode) delete value.obligations.episode;
@@ -540,7 +537,7 @@ async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p:
const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>(
"SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE", [p.cursorKey]);
// #6513: validation passed under this run; a replacement that landed since is the same supersession, not an index lag.
- const replaced = checkpointCursorReplaced(p, cursor?.completed_keys[0]?.runId, row.source_id);
+ const replaced = checkpointCursorReplaced({ kind: p.kind, runId: p.runId ?? '' }, cursor?.completed_keys[0]?.runId, row.source_id);
if (replaced) throw syncPublicationRefusal(replaced.code, replaced.message, row, p, replaced.cause);
if (!cursor || cursor.completed_keys[0].runId !== p.runId || cursor.completed_keys[0].index !== p.total || cursor.completed_keys[0].total !== p.total) {
throw syncPublicationRefusal('revision_conflict', 'The sync cursor is not fully committed.', row, p,
@@ -573,7 +570,7 @@ async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p:
if (settled && (p.from === null || p.syncOptions?.full === true)) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);
await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);
// #6712 PR 2 (L5): the tail (statistics, links) runs after the lease is released; it is owed from this commit on.
- await recordSyncTail(tx, row.source_id, p.cursorKey, p.runId);
+ await recordSyncTail(tx, row.source_id, p.cursorKey!, p.runId!);
for (const path of p.releasedHolds ?? []) await releaseHold(tx, path);
return { status: 'synced', source_id: row.source_id, committed_pages: p.total };
}
@@ -650,7 +647,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
async () => {
const cursor = await shared;
// #6513: a checkpoint whose cursor another run replaced is superseded, not conflicted; a page keeps `revision_conflict`.
- const replaced = checkpointCursorReplaced(p, cursor?.run_id, row.source_id);
+ const replaced = checkpointCursorReplaced({ kind: p.kind, runId: p.runId ?? '' }, cursor?.run_id, row.source_id);
if (replaced) throw syncPublicationRefusal(replaced.code, replaced.message, row, p, replaced.cause);
if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id) && !(screening?.unsaved && cursor.request_id == null)))) {
throw cursorFenceRefusal(row, p, cursor);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 7c4130ee54..756841abbc 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -68,7 +68,7 @@ import { withSyncTail } from './sync-tail.ts';
import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';
import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
-import { assertPassAdmission, isPassBatchKey, passBatchStep, passRequestId, readPassBatch, type PassEntry } from './sync-pass-batch.ts';
+import { assertPassAdmission, isPassBatchKey, passBatchStep, passRequestId, readPassBatch, setPassBatch, type PassEntry } from './sync-pass-batch.ts';
import type { PassStamp } from './sync-prepare.ts';
import { runSyncPass } from './sync-pass-run.ts';
@@ -1700,7 +1700,12 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
// runs keep the frozen manifest and its cursor.
if (!company && !opts.dryRun) {
return await runSyncPass(engine, { opts, slice, context, authority, processingOptions, syncOptions, assertActive, signal, state, runStartedAt,
- drainBatch: async (batchKey, batch, sliceBase) => { key = batchKey; return drainCursor(batch, await preparationConfigView(engine), false, sliceBase); } });
+ drainBatch: async (batchKey, batch, sliceBase) => {
+ key = batchKey;
+ setPassBatch(batchKey, batch, JSON.stringify(header(batch)));
+ try { return await drainCursor(batch, await preparationConfigView(engine), false, sliceBase); }
+ finally { setPassBatch(batchKey, null); }
+ } });
}
const resolved = await resolvePassCursor(engine, { sourceId: context.sourceId, incarnation: context.incarnation, company, remote: authority.writer.remote, dryRun: !!opts.dryRun, assertActive, state });
key = resolved.key;
@@ -1784,7 +1789,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
`The unfinished sync cursor of source ${cursor.sourceId} was written under an older binding (its owner epoch, topology generation, worktree or root changed since), so this run stopped without importing; the retry rediscovers against the current binding.`);
}
if (opts.dryRun) return dryRun(cursor);
- return await drainCursor(cursor, startupConfig, retried !== null);
+ return await drainCursor(cursor, startupConfig, retried !== null) as SyncResult;
} catch (error) {
assertSyncDispatchActive();
if (live.cursor) cursor = live.cursor;