Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6712 PR 4b lane A): working-mode levels and idle ticks through the lane W stat cache
garrytanbd17fb96dafa
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 73d541a0f8..2b1becc3fa 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -23,7 +23,8 @@ import type { PassStamp, SyncCursorOptions } 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';-import { passIdleProbe, readShadowLevel, type ShadowLevel, type ShadowPath } from './sync-pass.ts';+import { passIdleProbe, readShadowLevel, workingIdleChange, type ShadowLevel, type ShadowPath } from './sync-pass.ts';+import { recallWorkingStatCache, rememberWorkingStatCache } from './sync-git-stream.ts';import { syncPassKind } from './sync-classify.ts';import { PASS_BATCH_KEY_PREFIX, readConvergedWatermark, SyncAdmissionPaused, type PassEntry } from './sync-pass-batch.ts';import { assertDrainLease, currentDrainLease } from './sync-lease.ts';@@ -237,19 +238,22 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrreadSyncTail(engine, sourceId), readGitHoldRetryPaths(engine, sourceId, incarnation), readGitSourceHolds(engine, { sourceIds: [sourceId] })]);assertActive();const holds = (sourceHolds[0]?.holds ?? []).filter(hold => hold.incarnation === incarnation);+ // Working mode (design §2.2): the stat cache this process kept from the round its last stamp used; a cold process has none.+ const cacheKey = passFingerprint(sourceId, incarnation);+ const working = mode === 'working' && converged ? await workingIdleChange(context, recallWorkingStatCache(cacheKey)) : { changed: mode === 'working', cache: null };const kindOf = syncPassKind({ converged: converged ? { target: converged.target, parserFp: converged.parser_fp, pack: converged.pack, selectionFp: converged.selection_fp,passesSinceFull: converged.passes_since_full, lastFullAt: Date.parse(converged.last_full_at) } : null,head, parserFp, pack, selectionFp, now: started, openEpisode: !!episode, owedTail: tail !== null, retryRow: retry.length > 0,notConvergedStreak: obligations.not_converged_streak, mismatchStreak: Object.keys(obligations.mismatch).length,requestNewer: probe?.newer === true, openAtStampFinished: !!converged && (converged.open_at_stamp === null || (probe?.stillOpen ?? 0) < converged.open_at_stamp.length),- // Lane W ships the working-mode stat cache; until then a working pass always reads the level.- workingChange: mode === 'working', rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.includes(hold.path))), full: opts.full === true });+ workingChange: working.changed, rescreenDueHold: holds.some(hold => holdRescreenDue(hold, retry.includes(hold.path))), full: opts.full === true });const kind: PassKind = admission === 'classify_only' && kindOf.kind === 'idle' ? 'idle' : kindOf.kind;const value: ManagedSyncPassValue = { source_id: sourceId, incarnation, lease_token: lease.token, obligations,telemetry: { pass_id: passId, target: head, started_at: startedAt, ended_at: null, kind, round: 0, outcome: 'open', stop_reason: null, candidates: 0, settled: 0, remaining: 0,counts: {}, duration_ms: null, timings_ms: {} } };const bootstrap = !prior;+ if (kind === 'idle' && working.cache) rememberWorkingStatCache(cacheKey, working.cache);if (kind === 'idle') {// Master's up_to_date (a complete check that found nothing): only last_sync_at, plus the pass row's count.const at = new Date().toISOString();@@ -276,6 +280,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst sliceBase = { started: performance.now(), pages: 0 };let batchNo = 0, waits = 0, candidatesFirst = 0;let lastMismatch: ShadowPath[] = [];+ let lastLevel: ShadowLevel | null = null;+ const rememberLevel = () => { if (lastLevel?.workingCache) rememberWorkingStatCache(cacheKey, lastLevel.workingCache); };const save = async (outcome: PassOutcome, stopReason: string | null) => {const ended = outcome !== 'open';@@ -326,6 +332,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrassertActive();if (!level) throw new Error(`Source ${sourceId} became a company-brain source during its sync pass.`);levelSlugMode = level.slugMode;+ lastLevel = level;value.telemetry.timings_ms = level.timings_ms;if (bootstrap && round === 1) await writeLegacyMarkers(engine, level);const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];@@ -374,6 +381,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prvalue.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)));+ rememberLevel();await clearPassFailures(engine, sourceId, incarnation);return { ...result('up_to_date'), fromCommit: remote ? null : head };}@@ -385,6 +393,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst stopped = await drain([], stamp);if (stopped) return stop(stopped);value.telemetry = { ...value.telemetry, outcome: 'synced', stop_reason: configured ? null : 'selection_scoped', remaining: 0 };+ rememberLevel();await clearPassFailures(engine, sourceId, incarnation);return result(configured && context.source.last_commit === null ? 'first_sync' : 'synced', configured ? undefined : 'selection_scoped');}diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 9d3dd5de27..23e9e7aa79 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -33,7 +33,7 @@ import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHotype GitHoldRecord, type SyncImportProvenance } from './sync-holds.ts';import { movedDriftHolds, sameParser } from './sync-prescreen.ts';import { syncOriginPath } from './sync-origin.ts';-import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, type GitTreeEntry } from './sync-git-stream.ts';+import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, workingChanged, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.ts';import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';import { readManagedMode } from './ownership.ts';@@ -77,6 +77,8 @@ export interface ShadowLevel {selection: SyncSelection;/** Re-screen-due hold paths (Git-root paths): a hold-only round's candidates. */rescreenDue: string[];+ /** Working mode: the stat cache this round's rehash left (`hashWorkingLevel`); the stamp's round is the one a pass remembers. */+ workingCache: WorkingStatCache | null;/** Live file-backed pages whose origin is eligible: the mass-delete valve's denominator (#2828). */reconcilable: number;timings_ms: Record<string, number>;@@ -198,6 +200,19 @@ function revParse(gitRoot: string, rev: string): string | null {return out.ok ? out.stdout.toString('utf8').trim() || null : null;}+/**+ * #6712 PR 4b (design v3.2 §2.2): a working-mode idle tick's check. Every path the cache vouches for, plus `U` (untracked)+ * and the index's paths in scope, is re-stat'd (`workingChanged`); no cache (a cold process) reads as changed.+ */+export async function workingIdleChange(context: Pick<ManagedSyncContext, 'root' | 'gitRoot'>, cache: WorkingStatCache | null): Promise<{ changed: boolean; cache: WorkingStatCache | null }> {+ if (!cache) return { changed: true, cache: null };+ const scope = relative(realpathSync.native(context.gitRoot), realpathSync.native(context.root)).split(sep).join('/');+ const [untracked, index] = await Promise.all([readUntracked(context.gitRoot, scope), readIndexLevel(context.gitRoot)]);+ const inScope = (path: string) => !scope || path.startsWith(`${scope}/`);+ const checked = workingChanged(cache, [...untracked, ...[...index.keys()].filter(inScope)]);+ return { changed: checked.cache === null || checked.changed.length > 0, cache: checked.cache };+}+/** Working mode's `U`: untracked, not ignored files (index and exclude files only; no worktree conversion). */async function readUntracked(gitRoot: string, scope: string): Promise<string[]> {const paths: string[] = [];@@ -315,7 +330,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st// Working mode rehashes every path (the full round's unconditional rehash); committed mode probes candidates only.t = timer();- const probes = mode === 'working' ? (await hashWorkingLevel(root, gitRoot, [...domain], tree)).probes : new Map();+ const hashed = mode === 'working' ? await hashWorkingLevel(root, gitRoot, [...domain], tree) : null;+ const probes = hashed?.probes ?? new Map();timings.Dp = t();const levelOf = (path: string, probe: { dp: string; rawOid: string | null } | undefined): string | null => {@@ -428,7 +444,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: streturn { sourceId, incarnation, root, gitRoot, scope, slugMode, mode, head, baselineCommit, full: input.full === true, kind: kind.kind, kindBlockers: kind.blockers,paths, reconcilable, timings_ms: timings, statements: statements + attestationStatements + 3, pack: pack?.identity ?? null,selection: { exclude: [...exclude].sort(), includeHidden: [...includeHidden].sort(), strategy, srcSubpath: scope || null, mode },- rescreenDue: holds.filter(hold => holdRescreenDue(hold, retry.has(hold.path))).map(hold => toGit(hold.path)) };+ rescreenDue: holds.filter(hold => holdRescreenDue(hold, retry.has(hold.path))).map(hold => toGit(hold.path)), workingCache: hashed?.cache ?? null };}/** `workingTreeFilePresent` (sync-discovery.ts) for a Git-root path: a file that exists, or one that cannot be read (fail closed). */