Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 4b: the level read's HEAD lookups and probe entry stop holding the event loop
garrytan1649d8481804
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex fb2cf8f2b6..0350f5f51d 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -1,6 +1,7 @@-import { execFileSync } from 'node:child_process';+import { execFile, execFileSync } from 'node:child_process';import { lstatSync, readFileSync, realpathSync } from 'node:fs';import { join, relative, resolve, sep } from 'node:path';+import { promisify } from 'node:util';import type { BrainEngine } from '../engine.ts';import type { SyncOpts } from '../../commands/sync.ts';import { parseMarkdown } from '../markdown.ts';@@ -97,6 +98,11 @@ export function syncGit(root: string, args: string[]): string {return execFileSync('git', ['-c', 'core.quotepath=false', '-C', root, ...args],{ env: gitChildEnv(), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });}+/** `syncGit` without blocking the event loop while Git runs (a level read: a synchronous spawn held timers for 200+ ms on a loaded host). */+const execFileAsync = promisify(execFile);+export async function syncGitAsync(root: string, args: string[]): Promise<string> {+ return (await execFileAsync('git', ['-c', 'core.quotepath=false', '-C', root, ...args], { env: gitChildEnv(), encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2 })).stdout;+}/*** A sync file or root failed a confinement or identity check. These helpers* know no source id, so the read-only fix lists every registered root.diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.tsindex 66ac36c7cc..96783153ba 100644--- a/src/core/persistence/sync-git-stream.ts+++ b/src/core/persistence/sync-git-stream.ts@@ -309,7 +309,7 @@ interface ReadFile { path: string; sha256: string; localOid: string; foldedOid:* disk probe exactly as the same disk does with a pristine index.*/export async function probeDirtiness(root: string, gitRoot: string, paths: string[], tree: Map<string, GitTreeEntry>,- index: Map<string, GitIndexEntry>, opts: { batch?: number; working?: boolean } = {}): Promise<Map<string, DirtinessProbe>> {+ index: Map<string, GitIndexEntry>, opts: { batch?: number; working?: boolean; step?: LoopYield } = {}): Promise<Map<string, DirtinessProbe>> {const batch = Math.max(1, opts.batch ?? 2000);const results = new Map<string, DirtinessProbe>();const firstOid = tree.values().next().value?.oid ?? index.values().next().value?.oid ?? '';@@ -317,7 +317,7 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strinlet realRoot: string | null = null;let realGitRoot: string | null = null;try { realRoot = realpathSync.native(root); realGitRoot = realpathSync.native(gitRoot); } catch {}- const step = loopYield();+ const step = opts.step ?? loopYield();for (let start = 0; start < paths.length; start += batch) {const decided = new Map<string, Dp | null>();const read: ReadFile[] = [];@@ -347,6 +347,7 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strinconst [rawOids, attrs] = await Promise.all([hashRaw(gitRoot, read.map(file => file.path)), readAttributes(gitRoot, undecided)]);const lfs: Array<{ file: ReadFile; treeOid: string; executableMatches: boolean }> = [];for (const [i, file] of read.entries()) {+ if (step.due()) await step.pause();const rawOid = rawOids?.[i] === file.localOid ? file.localOid : null;const settle = (dp: Dp) => { results.set(file.path, { dp, rawOid, rawSha256: file.sha256 }); };const prior = decided.get(file.path);diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 04d751e156..9da787cec7 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -17,7 +17,7 @@import { realpathSync } from 'node:fs';import { relative, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { hardenedGitStream, hardenedGitSync, hardenedStreamComplete, NulRecordSplitter } from '../hardened-git.ts';+import { hardenedGitStream, hardenedStreamComplete, NulRecordSplitter } from '../hardened-git.ts';import { matchesAnyGlob, isSyncable } from '../sync.ts';import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';import { resolveSlugRootMode } from '../sync-anchor.ts';@@ -28,7 +28,7 @@ import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { currentCompanyBrainSync, getCompanyBrainProfile } from '../company-brain/profile.ts';import { sha256 } from './digest.ts';import { sourceMirrorReadOnly } from './mirror-read-only.ts';-import { colonFileRefusal, COLON_REFUSAL_MESSAGES, readSyncFile, resolveManagedSyncContext, syncExcludePatterns, syncGit, type ManagedSyncContext, type SyncFileRefusal } from './sync-discovery.ts';+import { colonFileRefusal, COLON_REFUSAL_MESSAGES, readSyncFile, resolveManagedSyncContext, syncExcludePatterns, syncGitAsync, type ManagedSyncContext, type SyncFileRefusal } from './sync-discovery.ts';import { isWindowsColonTarget } from './native-file-target.ts';import { confirmedSyncDelta } from '../sync-rename-identity.ts';import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, SYNC_IMPORT_PROVENANCE_OP, syncImportParser, syncImportParsers,@@ -523,9 +523,20 @@ async function readPassRow(exec: Exec, sourceId: string, incarnation: string): Preturn row?.value ?? null;}-function revParse(gitRoot: string, rev: string): string | null {- const out = hardenedGitSync(gitRoot, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`], { timeoutMs: 10_000, maxBytes: 4096 });- return out.ok ? out.stdout.toString('utf8').trim() || null : null;+/** HEAD's commit and whether HEAD is detached (master's rule, sync-discovery.ts: a detached HEAD forces working mode). */+async function readLevelHead(gitRoot: string, sourceId: string): Promise<{ head: string; detached: boolean }> {+ const abbrev = syncGitAsync(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);+ abbrev.catch(() => undefined);+ const head = await revParse(gitRoot, 'HEAD');+ if (!head) throw new Error(`source ${sourceId}: HEAD does not name a commit, so there is no level to read`);+ return { head, detached: (await abbrev).trim() === 'HEAD' };+}++/** A commit id, through a child process the event loop keeps running beside (a synchronous spawn held timers for 200+ ms on a loaded host). */+async function revParse(gitRoot: string, rev: string): Promise<string | null> {+ const chunks: Buffer[] = [];+ const out = await hardenedGitStream(gitRoot, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`], { timeoutMs: 10_000, maxBytes: 4096, onChunk: chunk => { chunks.push(chunk); } });+ return out.ok ? Buffer.concat(chunks).toString('utf8').trim() || null : null;}/**@@ -595,10 +606,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst step = turnYield();t = timer();- const head = revParse(gitRoot, 'HEAD');- if (!head) throw new Error(`source ${sourceId}: HEAD does not name a commit, so there is no level to read`);- // Master's rule (sync-discovery.ts): a detached HEAD forces working mode.- const detached = syncGit(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';+ const { head, detached } = await readLevelHead(gitRoot, sourceId);const working = detached || (input.workingTree ?? workingConfig === 'true');const mode: 'committed' | 'working' = working ? 'working' : 'committed';timings.rev_parse = t();@@ -691,7 +699,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst attestationStatements = unproven.length ? await readAttestations(engine, engineKind, sourceId, incarnation, pages, unproven) : 0;timings.A = t();- const baselineCommit = (context.source.last_commit && revParse(gitRoot, context.source.last_commit)) || null;+ const baselineCommit = (context.source.last_commit && await revParse(gitRoot, context.source.last_commit)) || null;// The baseline tree, read once when a page needs it (no record revision; design §2.3) or the bootstrap's legacy walk does,// so the classification itself never waits.let baselineTree: Map<string, GitTreeEntry> | null | undefined;@@ -812,8 +820,8 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stif (candidates.length) {t = timer();const candidateIndex = new Map<string, GitIndexEntry>();- for (const path of candidates) { const entry = indexed(path); if (entry) candidateIndex.set(path, entry); }- const probed = await probeDirtiness(root, gitRoot, candidates, tree, candidateIndex);+ for (const path of candidates) { if (step.due()) await step.pause(); const entry = indexed(path); if (entry) candidateIndex.set(path, entry); }+ const probed = await probeDirtiness(root, gitRoot, candidates, tree, candidateIndex, { step });timings.Dp = (timings.Dp ?? 0) + t();t = timer();for (const [k, path] of candidates.entries()) {@@ -1108,7 +1116,7 @@ export async function idleTickProbe(engine: BrainEngine, input: { sourceId: striconst context = input.context ?? await resolveManagedSyncContext(engine, { sourceId: input.sourceId, noPull: true, dryRun: true });timings.context = t();t = timer();- const head = revParse(context.gitRoot, 'HEAD');+ const head = await revParse(context.gitRoot, 'HEAD');timings.rev_parse = t();// The pass row, the request probe above its watermark and the open-set probe are one statement (one round trip).t = timer();