Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6712 PR 4b the pass reports size_states and #5751 legacy skips, settles a legacy-waived path for itself, and stamps the E33 fence trend

garrytan448665ce4de2
diff --git a/src/core/persistence/sync-cursor-moves.ts b/src/core/persistence/sync-cursor-moves.ts
index c24aa5823e..f3539ee130 100644
--- a/src/core/persistence/sync-cursor-moves.ts
+++ b/src/core/persistence/sync-cursor-moves.ts
@@ -19,6 +19,7 @@ export function waivedCursor(cursor: Cursor, waived: NoopWaiver, index = cursor.
waived: { imports: prior.imports + (waived.kind === 'import' ? 1 : 0), deletes: prior.deletes + (waived.kind === 'delete' ? 1 : 0) } } };
if (waived.kernel.includes('contextual_mode')) next.counts.skippedContextualMode = (next.counts.skippedContextualMode ?? 0) + 1;
if (waived.kernel.includes('canonical_file_differs')) next.counts.skippedCanonicalBytes = (next.counts.skippedCanonicalBytes ?? 0) + 1;
+ if (cursor.passId && waived.kernel.length) next.legacyWaived = [...cursor.legacyWaived ?? [], index];
return next;
}
/** #6643: the cursor's settled indexes with its current entry added (it passes that entry without a commit). */
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 6f95d253d9..b293762003 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -26,7 +26,7 @@ import { managedSyncWriteDiagnostic } from './sync-write-diagnostic.ts';
import { 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 type { PassStamp, SyncCursorOptions, SyncIntent } from './sync-prepare.ts';
+import { recordPassFenceTrend, type PassStamp, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
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';
@@ -53,6 +53,7 @@ import { passResumeArgs } from './sync-pass-readers.ts';
import { applyPassRound, finishPassApply, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';
import { passCostDecision, passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';
import { currentEmbeddingPricePerMTok } from '../embedding.ts';
+import { SIZE_STATE_SAMPLE, type SyncSizeStates } from '../page-embedding-budget.ts';
import { massReconcileAllowed } from '../sync-reconcile.ts';
/** Rounds a pass runs before it stops `not_converged` (design §3.1). */
@@ -389,7 +390,17 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const counts = { added: 0, modified: 0, deleted: 0, renamed: 0, chunks: 0, waivedImports: 0, waivedDeletes: 0, held: 0, pausedDeletes: 0, collisions: 0, episodeReleased: 0, costDeferred: costDeferred ? 1 : 0 };
const collisions: SyncSlugCollision[] = [];
+ // What the batches report beside their counts, as a cursor run reported it: committed pages' size states and #5751's legacy skips.
+ let sizeStates: SyncSizeStates | undefined;
+ const legacySkips = { contextualMode: 0, canonicalBytes: 0 };
+ const foldReport = (sizes: SyncSizeStates | undefined, skips: { contextualMode?: number; canonicalBytes?: number } | undefined) => {
+ if (sizes?.total) sizeStates = { total: (sizeStates?.total ?? 0) + sizes.total, pages: [...sizeStates?.pages ?? [], ...sizes.pages].slice(0, SIZE_STATE_SAMPLE) };
+ legacySkips.contextualMode += skips?.contextualMode ?? 0; legacySkips.canonicalBytes += skips?.canonicalBytes ?? 0;
+ };
const S = new Map<string, string>();
+ // #5751: (path, level) keys a legacy kernel waiver passed. The waiver records no import, so the path classifies as before;
+ // it is settled for this pass (never re-admitted, never a settle mismatch) and re-screened by the next one.
+ const legacyWaived = new Set<string>();
const settledKey = (path: string, level: string | null) => `${path}\0${level ?? ''}`;
// The entries this round's batches settled before the round folds its candidates into S: a slice that yields mid-round
// (writer_yield) reports them (yieldSettled); a blocked stop reports S as it replays.
@@ -416,6 +427,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
added: counts.added, modified: counts.modified, deleted: counts.deleted, renamed: counts.renamed, chunksCreated: counts.chunks, embedded: 0, pagesAffected: [],
filesImported: sliceBase.pages, bankedFiles: sliceBase.pages, waived: { imports: counts.waivedImports, deletes: counts.waivedDeletes }, prescreened: 0,
...(collisions.length ? { slugCollisions: collisions } : {}), ...(identityDowngrades.length ? { identityDowngrades } : {}), ...(inherited.length ? { inherited_options: inherited } : {}), ...(reason ? { reason } : {}),
+ ...(sizeStates ? { size_states: sizeStates } : {}), ...(legacySkips.contextualMode || legacySkips.canonicalBytes ? { legacySkips: { ...legacySkips } } : {}),
pass: { pass_id: passId, kind, round: value.telemetry.round, outcome: value.telemetry.outcome, stop_reason: value.telemetry.stop_reason, candidates: candidatesFirst,
settled: S.size + yieldSettled, remaining: value.telemetry.remaining, not_converged_streak: value.obligations.not_converged_streak } });
try {
@@ -452,6 +464,11 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
chunks: counts.chunks + c.chunks, waivedImports: counts.waivedImports + (c.waived?.imports ?? 0), waivedDeletes: counts.waivedDeletes + (c.waived?.deletes ?? 0), held: counts.held + (c.held ?? 0) });
sliceBase.pages += drained.index;
roundSettled += drained.index;
+ foldReport(c.sizeStates, { contextualMode: c.skippedContextualMode, canonicalBytes: c.skippedCanonicalBytes });
+ for (const index of drained.legacyWaived ?? []) {
+ const entry = drained.entries[index] as PassEntry;
+ legacyWaived.add(settledKey(lastLevel?.scope ? `${lastLevel.scope}/${entry.path}` : entry.path, entry.level ?? null));
+ }
return null;
}
return drained;
@@ -461,6 +478,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
renamed: counts.renamed + drained.renamed, chunks: counts.chunks + drained.chunksCreated, waivedImports: counts.waivedImports + (drained.waived?.imports ?? 0),
waivedDeletes: counts.waivedDeletes + (drained.waived?.deletes ?? 0) });
sliceBase.pages += drained.filesImported ?? 0;
+ foldReport(drained.size_states, drained.legacySkips);
if (drained.reason === 'writer_yield') yieldSettled = roundSettled + (drained.managedCursor?.index ?? 0);
const outcome: PassOutcome = drained.status === 'blocked_by_failures' ? 'blocked' : 'resumable';
const blockedOn = drained.managedWrite?.path ? drained.managedWrite.write_request.request_id : null;
@@ -521,7 +539,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (r.inFlight) { inFlight.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;
+ if (entry.state.hold?.atLevel || legacyWaived.has(settledKey(entry.path, entry.state.level))) continue;
// Design §3.1: admitted at most once more per (path, level) in this pass, then counted as a settle mismatch.
const again = settledKey(entry.path, entry.state.level);
if (readmitted.has(again)) { mismatch.push(entry); continue; }
@@ -579,6 +597,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);
// Holds on paths that left the level go with it here too, as a stamp releases them.
for (const path of level.releasableHolds) await clearGitHold(tx, { sourceId, incarnation, path, observedAt: startedAt });
+ await recordPassFenceTrend(tx, { worktreeId: context.binding.worktree_id, sourceId, passId, since: converged?.request_hwm ?? null });
const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, 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 };
@@ -599,7 +618,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (closure?.released) counts.episodeReleased = closure.released;
const stamp: PassStamp = { leaseToken: lease.token, incarnation, configured, stampChunker: configured && (context.source.last_commit === null || (closesEpisode && !!episode?.full_id && closure!.stampChunker)),
closesEpisode, retryTaken: [...retry], releasedHolds: level.releasableHolds, selectionFp, parserFp, pack, full: kind === 'full',
- changed: counts.added + counts.modified + counts.deleted + counts.renamed, extract: !processingOptions.noExtract, since: value.telemetry.started_at };
+ changed: counts.added + counts.modified + counts.deleted + counts.renamed, extract: !processingOptions.noExtract, since: value.telemetry.started_at,
+ ...(legacyWaived.size ? { rescreen: true as const } : {}) };
await save('open', null);
const stopped = await drain([], stamp);
if (stopped) return stop(stopped);
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index a3031bba65..c5cc107b85 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -53,11 +53,12 @@ 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';
+import { addFencesNormalized, clearGitHold, clearGitHoldRetryPaths, countGitHolds, recordSyncImportProvenance, type FencesTally, syncDiskProvenance, syncImportParser, syncImportParserFor, type SyncImportProvenanceBase } from './sync-holds.ts';
import { clearSyncSlice, writeSyncSlice, type SyncSliceState } from './sync-slices.ts';
import { CHECKPOINT_MOVED_MESSAGE, emptySyncScope, pinnedSlugModeMismatch, slugModeMismatchCause } from './sync-slug-mode.ts';
import { readPagePurgeTombstones } from './page-purge.ts';
import { fenceWhere } from '../fence-repair/refusal.ts';
+import { recordSyncRunTrend } from '../fence-repair/census-store.ts';
import { fencesNormalizeEnabled } from '../fence-repair/config.ts';
import { describeFixes } from '../fence-repair/report.ts';
import { fenceFixesWire } from '../fence-repair/tier1.ts';
@@ -128,6 +129,8 @@ export interface PassStamp {
changed: number; extract: boolean;
/** When the pass pinned, on the database clock: the tail reads the pages its requests imported since then. */
since?: string;
+ /** #5751: the pass settled paths only by a legacy kernel waiver (they record no import), so the next tick re-screens them: no idle. */
+ rescreen?: true;
}
/**
* #5984: the source-wide part of sync validation (managed mode, configured
@@ -517,12 +520,13 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn
if (stamp.stampChunker) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);
}
await recordPassTail(tx, row.source_id, p.passId!, { changed: stamp.changed, extract: stamp.extract, ...(stamp.since ? { since: stamp.since } : {}) });
+ await recordPassFenceTrend(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, passId: p.passId!, since: pass.value.obligations.converged?.request_hwm ?? null });
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 watermark = await readConvergedWatermark(tx, { worktreeId: row.worktree_id!, sourceId: row.source_id, incarnation: row.source_incarnation }, 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, ...watermark,
+ value.obligations.converged = { target: p.target, at, ...watermark, ...(stamp.rescreen ? { open_at_stamp: null } : {}),
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;
@@ -534,6 +538,21 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn
return { status: 'synced', source_id: row.source_id, pass_id: p.passId, configured: stamp.configured };
}
+/**
+ * #6188 (E33) on a live pass: the stamp records the source's fences_normalized trend row (one per pass, keyed by its id) from
+ * the sync imports committed since the previous stamp's watermark. A pass that stopped before its stamp is counted by the
+ * next stamp, once, so a completed pass always has its trend row and a normalization is never counted twice.
+ */
+export async function recordPassFenceTrend(tx: Pick<BrainEngine, 'executeRaw'>, scope: { worktreeId: string; sourceId: string; passId: string; since: string | null }): Promise<void> {
+ const rows = await tx.executeRaw<{ path: string | null; fences: Array<{ class: string }> }>(`SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences
+ FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed'
+ AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence`,
+ [scope.worktreeId, scope.sourceId, scope.since ?? '0']);
+ let tally: FencesTally | undefined;
+ for (const row of rows) if (row.path && row.fences.length) tally = addFencesNormalized(tally, row.path, row.fences);
+ if (tally) await recordSyncRunTrend(tx, { sourceId: scope.sourceId, runId: scope.passId, day: new Date().toISOString().slice(0, 10), count: tally.count, byClass: tally.by_class, writers: tally.dirs });
+}
+
/** The checkpoint request's publication: the whole run committed, so `last_commit` (and the slug-root pin) advance under the guard. */
async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>): Promise<Record<string, unknown>> {
const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>(
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index e4e958b102..7ec2a99134 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -146,7 +146,9 @@ export interface Cursor extends SyncDiscovery { runId: string; index: number; au
* the pass's stamp (no entries; its checkpoint publishes the stamp). `fullEpisode`: the open `--full` episode its imports
* record. `failureKey`: the key a recorded failure of the batch is filed under (the pass row's fingerprint).
*/
- passId?: string; stamp?: PassStamp; fullEpisode?: string; failureKey?: string; resumeArgs?: string[]; }
+ 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[]; }
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
diff --git a/test/persistence-sync-legacy-files-5751.test.ts b/test/persistence-sync-legacy-files-5751.test.ts
index f7a4a299f1..2335dd37cf 100644
--- a/test/persistence-sync-legacy-files-5751.test.ts
+++ b/test/persistence-sync-legacy-files-5751.test.ts
@@ -97,7 +97,10 @@ test('#5751 unchanged legacy working-tree files admit nothing on any run, and th
test('#5751 a run mixing skipped legacy files and a new file commits its checkpoint', async () => each(async engine => {
const f = await legacyFixture(engine);
writeFileSync(join(f.root, 'fresh.md'), '---\ntitle: Fresh\n---\nA new untracked observation.\n');
- const result = await performManagedSync(engine, f.working);
+ // #6712 PR 4b (design v3.2 §3.3, §6): only a pass at the configured selection (mode included) stamps last_commit, so the
+ // source is configured for working-tree sync, as a brain that syncs its working tree is.
+ await engine.setConfig('sync.include_working_tree', 'true');
+ const result = await performManagedSync(engine, f.working).finally(() => engine.unsetConfig('sync.include_working_tree'));
await disposePersistenceConsumer(engine);
expect(result).toMatchObject({ status: 'first_sync', added: 2, legacySkips: { contextualMode: 1, canonicalBytes: 1 } });
expect((await admitted(engine, f.id)).sort()).toEqual(['fresh', 'seed']);