Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): classic sync runs its Git reads asynchronously (GBRA-133 2b.3)
garrytanad1f7e62fe70
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.tsindex 2c231369e2..6a82f69b44 100644--- a/src/commands/sync/preflight.ts+++ b/src/commands/sync/preflight.ts@@ -24,12 +24,12 @@ import type { SlugRootMode } from '../../core/sync-anchor.ts';import { buildLosslessWorkingTreeManifest, computeLosslessSyncDelta, mergeSyncManifests, type LosslessDelta } from '../../core/sync-delta.ts';import { confirmRenameIdentities, redecideHeldRename, type ConfirmedManifest } from '../../core/sync-rename-identity.ts';import {- git,+ gitAsync,isWithinRoot,gitRelativePath,- discoverGitRoot,+ discoverGitRootAsync,createSyncBaselineCommit,- isDetachedHead,+ isDetachedHeadAsync,hasOriginRemote,unique,} from '../../core/sync-git.ts';@@ -87,7 +87,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOpif (lastCommit) {let objectPresent = true;try {- git(gitContextRoot, ['cat-file', '-t', lastCommit]);+ await gitAsync(gitContextRoot, ['cat-file', '-t', lastCommit]);} catch {objectPresent = false;}@@ -104,7 +104,7 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOp// failure mode (#1970) is visible in the logs.let isAncestor = true;try {- git(gitContextRoot, ['merge-base', '--is-ancestor', lastCommit, headCommit]);+ await gitAsync(gitContextRoot, ['merge-base', '--is-ancestor', lastCommit, headCommit]);} catch {isAncestor = false;}@@ -492,7 +492,7 @@ async function discoverSyncGitRoot(// function's docstring. `!opts.dryRun`: a preview must never write.let gitContextRoot: string;try {- gitContextRoot = realpathSync(discoverGitRoot(repoPath));+ gitContextRoot = realpathSync(await discoverGitRootAsync(repoPath));} catch (err) {if (company) throw err;if (@@ -524,7 +524,7 @@ async function discoverSyncGitRoot(// this ever reaches a baseline on a repo that turns out to have commits.let reprobedRoot: string | null = null;try {- reprobedRoot = discoverGitRoot(repoPath);+ reprobedRoot = await discoverGitRootAsync(repoPath);} catch {reprobedRoot = null;}@@ -535,9 +535,9 @@ async function discoverSyncGitRoot(throw err;} else {serr(`[gbrain] auto-recovery: git-initializing brain dir ${repoPath} (no git repo found).`);- git(repoPath, ['init', '--quiet']);+ await gitAsync(repoPath, ['init', '--quiet']);createSyncBaselineCommit(repoPath);- gitContextRoot = realpathSync(discoverGitRoot(repoPath));+ gitContextRoot = realpathSync(await discoverGitRootAsync(repoPath));}}return gitContextRoot;@@ -556,7 +556,7 @@ async function pullAndResolveHead(// Detect detached HEAD up front so the working-tree fallback fires for both// the default sync and `--no-pull` callers. Only the actual git pull is// gated on opts.noPull or opts.dryRun.- const detachedHead = !company && isDetachedHead(gitContextRoot);+ const detachedHead = !company && await isDetachedHeadAsync(gitContextRoot);if (detachedHead && !opts.noPull) {// Print the caller's repoPath spelling (not the realpathed git root) —// it's what the operator recognizes, and tests pin it.@@ -662,7 +662,7 @@ async function pullAndResolveHead(// Get current HEADlet headCommit: string;try {- headCommit = company?.plan.revision?.commit ?? git(gitContextRoot, ['rev-parse', 'HEAD']);+ headCommit = company?.plan.revision?.commit ?? await gitAsync(gitContextRoot, ['rev-parse', 'HEAD']);} catch {// #2964: unborn-HEAD recovery. `.git` exists (discoverGitRoot succeeded// above) but there are zero commits — e.g. a prior self-heal `git init`@@ -688,7 +688,7 @@ async function pullAndResolveHead(}serr(`[gbrain] auto-recovery: repo has no commits yet, creating baseline commit ${gitContextRoot}.`);createSyncBaselineCommit(gitContextRoot);- headCommit = git(gitContextRoot, ['rev-parse', 'HEAD']);+ headCommit = await gitAsync(gitContextRoot, ['rev-parse', 'HEAD']);}// #2964: self-heal deliberately does NOT special-case db_only/.gitignore@@ -805,7 +805,7 @@ async function resolveCheckpointPin(let pinReachable = false;try {if (company && storedTarget !== company.plan.revision!.commit) throw new Error('Approved revision mismatch');- if (!company) git(gitContextRoot, ['merge-base', '--is-ancestor', storedTarget, headCommit]);+ if (!company) await gitAsync(gitContextRoot, ['merge-base', '--is-ancestor', storedTarget, headCommit]);pinReachable = true;} catch {pinReachable = false;@@ -890,7 +890,7 @@ async function resolveWorkingTreeScope(let workingTreeManifest: ConfirmedManifest;let workingTreeBytes: BytePaths = NO_BYTE_PATHS;try {- const tree: LosslessDelta = company ? { manifest: { added: [], modified: [], deleted: [], renamed: [] }, ...NO_BYTE_PATHS } : buildLosslessWorkingTreeManifest(gitContextRoot);+ const tree: LosslessDelta = company ? { manifest: { added: [], modified: [], deleted: [], renamed: [] }, ...NO_BYTE_PATHS } : await buildLosslessWorkingTreeManifest(gitContextRoot);workingTreeManifest = tree.manifest;workingTreeBytes = tree;} catch (e) {@@ -1022,7 +1022,7 @@ async function computeFilteredDelta(// #6729: inexact renames keep their page identity only when confirmed, before the company fold, the unsyncable fold// and the hold replay read the manifest; the already-confirmed working-tree manifest merges after.// GBRA-133: read as bytes (diff --raw -z), so a name is exactly Git's; names that are not page paths and gitlinks ride beside the manifest.- const delta = computeLosslessSyncDelta(gitContextRoot, lastCommit, pin);+ const delta = await computeLosslessSyncDelta(gitContextRoot, lastCommit, pin);if (delta.status === 'unavailable') {serr(`[sync] delta ${lastCommit.slice(0, 8)}..${pin.slice(0, 8)} unavailable ` +diff --git a/src/core/bounded-child-exec.ts b/src/core/bounded-child-exec.tsindex ff52034a43..7d9c38ff5e 100644--- a/src/core/bounded-child-exec.ts+++ b/src/core/bounded-child-exec.ts@@ -33,6 +33,8 @@ export interface BoundedExecOptions {maxBuffer?: number;signal?: AbortSignal;termGraceMs?: number;+ /** 'buffer' returns stdout and stderr as raw bytes (NUL-delimited git listings); default 'utf8'. */+ encoding?: 'utf8' | 'buffer';}/**@@ -51,11 +53,14 @@ export interface BoundedExecOptions {* uninterruptible I/O or memory reclaim acts on SIGTERM only seconds later, so* git callers pass a longer `termGraceMs` (#6932).*/-export function execFileBounded(file: string, args: string[], options: BoundedExecOptions): Promise<{ error: ExecFileException | null; stdout: string; stderr: string }> {- const { timeout, signal, termGraceMs = BOUNDED_EXEC_TERM_GRACE_MS, ...rest } = options;+export function execFileBounded(file: string, args: string[], options: BoundedExecOptions & { encoding: 'buffer' }): Promise<{ error: ExecFileException | null; stdout: Buffer; stderr: Buffer }>;+export function execFileBounded(file: string, args: string[], options: BoundedExecOptions): Promise<{ error: ExecFileException | null; stdout: string; stderr: string }>;+export function execFileBounded(file: string, args: string[], options: BoundedExecOptions): Promise<{ error: ExecFileException | null; stdout: string | Buffer; stderr: string | Buffer }> {+ const { timeout, signal, termGraceMs = BOUNDED_EXEC_TERM_GRACE_MS, encoding = 'utf8', ...rest } = options;+ const empty = encoding === 'buffer' ? Buffer.alloc(0) : '';return new Promise(resolve => {let settled = false;- const finish = (error: ExecFileException | null, stdout: string, stderr = '') => {+ const finish = (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer = empty) => {if (settled) return;settled = true;clearTimeout(timer);@@ -68,12 +73,12 @@ export function execFileBounded(file: string, args: string[], options: BoundedExconst settleStopped = () => {clearTimeout(escalation);clearInterval(poll);- finish(stopped, '', '');+ finish(stopped, empty, empty);};- const child = execFile(file, args, { ...rest, encoding: 'utf8' }, (error, stdout, stderr) => {+ const child = execFile(file, args, { ...rest, encoding: encoding as BufferEncoding }, (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => {clearTimeout(escalation);clearInterval(poll);- if (stopped) finish(stopped, '', '');+ if (stopped) finish(stopped, empty, empty);else finish(error, stdout, stderr);});const stop = (message: string, code: string) => {diff --git a/src/core/minions/source-filesystem.ts b/src/core/minions/source-filesystem.tsindex 1059e8b089..d8b6482a6d 100644--- a/src/core/minions/source-filesystem.ts+++ b/src/core/minions/source-filesystem.ts@@ -8,11 +8,12 @@ import { closeSync, constants, fstatSync, ftruncateSync, lstatSync, openSync, reimport { dirname, isAbsolute, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { LockStolenError, LockUnavailableError, withRefreshingLock } from '../db-lock.ts';-import { discoverGitRoot } from '../sync-git.ts';+import { discoverGitRoot, discoverGitRootAsync } from '../sync-git.ts';import { authorityDigest, currentRemoteJobAuthority, currentJobSignal } from './submission-authority.ts';import { assertLegacyFilesystemWriter, assertManagedFilesystemWrite } from '../persistence/filesystem-guard.ts';-const heldRoots = new AsyncLocalStorage<ReadonlyArray<{ root: string; active: boolean }>>();+/** `resolved` keeps the lock root each path resolved to when the lock was taken, so a nested check spawns no git. */+const heldRoots = new AsyncLocalStorage<ReadonlyArray<{ root: string; active: boolean; resolved?: ReadonlyMap<string, string> }>>();const filesystemSignal = new AsyncLocalStorage<AbortSignal>();const filesystemLeases = new AsyncLocalStorage<Array<{ key: string; lost: boolean }>>();export function currentSourceFilesystemSignal(): AbortSignal | undefined {@@ -29,28 +30,42 @@ export function assertSourceFilesystemActive(allowCallerAbort = false): void {// Some Bun versions drop an asynchronously created AbortSignal reason.if (signal?.aborted) throw signal.reason ?? new DOMException('Source filesystem work cancelled or lock lease lost', 'AbortError');}-function lockRoot(path: string): string {+function lockCandidate(path: string): string {let canonical = resolve(path);try { canonical = realpathSync(canonical); } catch { /* local initialization may create it */ }try { if (statSync(canonical).isFile()) canonical = dirname(canonical); } catch { /* nonexistent local target */ }+ return canonical;+}+function lockRoot(path: string): string {+ const canonical = lockCandidate(path);try { return realpathSync(discoverGitRoot(canonical)); } catch { return canonical; }}+/** GBRA-133 2b.3: `lockRoot` without blocking the event loop (every sync takes this lock, in residents too). */+async function lockRootAsync(path: string): Promise<string> {+ const canonical = lockCandidate(path);+ try { return realpathSync(await discoverGitRootAsync(canonical)); } catch { return canonical; }+}+function holdsLockOn(canonical: string): boolean {+ return [...heldRoots.getStore() ?? []].some(held => held.active && encloses(held.root, canonical));+}function encloses(root: string, path: string): boolean {const rel = relative(root, path);return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);}export function hasSourceFilesystemLock(path: string): boolean {- const canonical = lockRoot(path);- return [...heldRoots.getStore() ?? []].some(held => held.active && encloses(held.root, canonical));+ const held = heldRoots.getStore() ?? [];+ if (!held.some(entry => entry.active)) return false;+ const known = held.find(entry => entry.resolved?.has(path))?.resolved?.get(path);+ return holdsLockOn(known ?? lockRoot(path));}-async function registeredLockRoot(engine: BrainEngine, path: string): Promise<string> {- let root = lockRoot(path);+async function registeredLockRoot(engine: BrainEngine, pathRoot: string): Promise<string> {+ let root = pathRoot;const sources = await engine.executeRaw<{ local_path: string }>(`SELECT local_path FROM sources WHERE local_path IS NOT NULL AND local_path <> ''`);// A registered non-Git parent can contain a Git source. Canonicalize every// registered source through the same worktree rule, then choose the outermost// ancestor so overlapping sources agree regardless of which one starts first.for (const source of sources) {- const candidate = lockRoot(source.local_path);+ const candidate = await lockRootAsync(source.local_path);if (encloses(candidate, root)) root = candidate;}return root;@@ -58,9 +73,10 @@ async function registeredLockRoot(engine: BrainEngine, path: string): Promise<stexport async function withSourceFilesystemLock<T>(engine: BrainEngine, path: string, fn: () => Promise<T>, opts: { signal?: AbortSignal; waitMs?: number } = {}): Promise<T> {await assertLegacyFilesystemWriter(engine, path);assertSourceFilesystemActive();- if (hasSourceFilesystemLock(path)) return fn();- const root = await registeredLockRoot(engine, path);- const rootContext = { root, active: true };+ const pathRoot = await lockRootAsync(path);+ if (holdsLockOn(pathRoot)) return fn();+ const root = await registeredLockRoot(engine, pathRoot);+ const rootContext = { root, active: true, resolved: new Map([[path, pathRoot]]) };const held = [...heldRoots.getStore() ?? [], rootContext];const key = `gbrain-fs:${authorityDigest(root)}`;const inheritedSignal = currentSourceFilesystemSignal();diff --git a/src/core/source-health.ts b/src/core/source-health.tsindex 43aedf4b3d..01765e26ce 100644--- a/src/core/source-health.ts+++ b/src/core/source-health.ts@@ -22,6 +22,7 @@* local_path (preserves the v0.41.27.0 trust boundary).*/import { execFileSync } from './spawn.ts';+import { execFileBounded } from './bounded-child-exec.ts';import type { BrainEngine } from './engine.ts';import { parseSourceConfig, type SourceRow } from './sources-load.ts';import { isSourceUnchangedSinceSync } from './git-head.ts';@@ -152,24 +153,35 @@ export function newestCommitMs(localPath: string | null): number | null {export function commitTimeMs(localPath: string | null, sha: string | null): number | null {if (!localPath || !sha) return null;try {- const out = execFileSync('git', ['-C', localPath, 'show', '-s', '--format=%ct', sha], {+ return parseCommitTime(execFileSync('git', ['-C', localPath, 'show', '-s', '--format=%ct', sha], {env: gitChildEnv(),encoding: 'utf8',timeout: 10_000,stdio: ['ignore', 'pipe', 'ignore'],- }).trim();- if (!out) return null;- // `git show -s --format=%ct <sha>` prints only the committer epoch for the- // resolved commit; take the first line in case the sha resolves to an- // annotated-tag-ish ref that prints extra lines.- const first = out.split('\n')[0]?.trim();- const ms = Number(first) * 1000;- return Number.isFinite(ms) ? ms : null;+ }));} catch {return null; // not a git repo / unknown sha / git unavailable / timeout}}+/** GBRA-133 2b.3: `commitTimeMs` without blocking the event loop (the classic sync's anchor write in a resident). */+export async function commitTimeMsAsync(localPath: string | null, sha: string | null): Promise<number | null> {+ if (!localPath || !sha) return null;+ const r = await execFileBounded('git', ['-C', localPath, 'show', '-s', '--format=%ct', sha], { env: gitChildEnv(), timeout: 10_000 });+ return r.error ? null : parseCommitTime(r.stdout);+}++function parseCommitTime(stdout: string): number | null {+ const out = stdout.trim();+ if (!out) return null;+ // `git show -s --format=%ct <sha>` prints only the committer epoch for the+ // resolved commit; take the first line in case the sha resolves to an+ // annotated-tag-ish ref that prints extra lines.+ const first = out.split('\n')[0]?.trim();+ const ms = Number(first) * 1000;+ return Number.isFinite(ms) ? ms : null;+}+/*** Resolve the staleness-ceiling in seconds.*diff --git a/src/core/sync-delta.ts b/src/core/sync-delta.tsindex 5695aa882c..75c39bddb8 100644--- a/src/core/sync-delta.ts+++ b/src/core/sync-delta.ts@@ -32,6 +32,7 @@* That is the #1970 property this module preserves.*/import { execFileSync } from './spawn.ts';+import { execFileBounded } from './bounded-child-exec.ts';import { buildSyncManifest, type SyncManifest } from './sync.ts';import { GIT_READ_ENV, gitChildEnv } from './git-env.ts';import { classifyGitPathBytes, displayBytePath, type UnsupportedPathReason } from './sync-byte-paths.ts';@@ -160,11 +161,15 @@ export function computeSyncDelta(return { status: 'ok', manifest: detached ? mergeSyncManifests(manifest, detached) : manifest };}-/** Runs a read-only git subcommand in `repoPath` and returns its stdout bytes untouched (throws on failure). */-export type GitBytesRunner = (repoPath: string, args: string[]) => Buffer;+/** Runs a read-only git subcommand in `repoPath` and returns its stdout bytes untouched (throws or rejects on failure). */+export type GitBytesRunner = (repoPath: string, args: string[]) => Buffer | Promise<Buffer>;-const DEFAULT_GIT_BYTES_RUNNER: GitBytesRunner = (repoPath, args) =>- execFileSync('git', ['-C', repoPath, ...args], { env: gitChildEnv(GIT_READ_ENV), timeout: 30_000, maxBuffer: 100 * 1024 * 1024 });+/** GBRA-133 2b.3: async, so a classic sync a resident runs in-process never blocks its event loop on the diff or listing. */+const DEFAULT_GIT_BYTES_RUNNER: GitBytesRunner = async (repoPath, args) => {+ const r = await execFileBounded('git', ['-C', repoPath, ...args], { env: gitChildEnv(GIT_READ_ENV), timeout: 30_000, maxBuffer: 100 * 1024 * 1024, encoding: 'buffer' });+ if (r.error) throw r.error;+ return r.stdout;+};let _gitBytesRunner: GitBytesRunner = DEFAULT_GIT_BYTES_RUNNER;@@ -257,16 +262,16 @@ export function parseRawDiffZ(out: Buffer): LosslessDelta {}/** `computeSyncDelta` read as bytes (classic sync); the same anchor and diff ladder. */-export function computeLosslessSyncDelta(repoPath: string, fromCommit: string, toCommit: string): LosslessDeltaResult {+export async function computeLosslessSyncDelta(repoPath: string, fromCommit: string, toCommit: string): Promise<LosslessDeltaResult> {const run = _gitBytesRunner;try {- run(repoPath, ['cat-file', '-t', fromCommit]);+ await run(repoPath, ['cat-file', '-t', fromCommit]);} catch {return { status: 'unavailable', reason: 'anchor_missing' };}let out: Buffer;try {- out = run(repoPath, ['diff', '--raw', '-z', '-M', `${fromCommit}..${toCommit}`]);+ out = await run(repoPath, ['diff', '--raw', '-z', '-M', `${fromCommit}..${toCommit}`]);} catch {return { status: 'unavailable', reason: 'diff_failed' };}@@ -274,10 +279,10 @@ export function computeLosslessSyncDelta(repoPath: string, fromCommit: string, t}/** `buildDetachedWorkingTreeManifest` read as bytes (classic sync): tracked changes against HEAD plus untracked files. */-export function buildLosslessWorkingTreeManifest(repoPath: string): LosslessDelta {+export async function buildLosslessWorkingTreeManifest(repoPath: string): Promise<LosslessDelta> {const run = _gitBytesRunner;- const delta = parseRawDiffZ(run(repoPath, ['diff', '--raw', '-z', '-M', 'HEAD']));- for (const raw of splitNul(run(repoPath, ['ls-files', '-z', '--others', '--exclude-standard']))) {+ const delta = parseRawDiffZ(await run(repoPath, ['diff', '--raw', '-z', '-M', 'HEAD']));+ for (const raw of splitNul(await run(repoPath, ['ls-files', '-z', '--others', '--exclude-standard']))) {if (raw.length === 0) continue;const parsed = classifyGitPathBytes(raw);if ('path' in parsed) delta.manifest.added.push(parsed.path);diff --git a/src/core/sync-git.ts b/src/core/sync-git.tsindex 3ef268d2cf..85b432d45b 100644--- a/src/core/sync-git.ts+++ b/src/core/sync-git.ts@@ -5,6 +5,7 @@*/import { lstatSync, realpathSync } from 'fs';import { execFileSync } from './spawn.ts';+import { execFileBounded } from './bounded-child-exec.ts';import { basename, dirname, isAbsolute, join, relative, sep } from 'path';import type { BrainEngine } from './engine.ts';import { resolveSlugForPath, DEFAULT_SOURCE_ID } from './sync.ts';@@ -331,6 +332,30 @@ export function git(}).trim();}+/**+ * GBRA-133 2b.3: `git()` without blocking the event loop, for the classic sync a resident (serve, the jobs worker,+ * autopilot) runs in-process on a commit. Same invocation, environment, timeout and buffer. A failure rejects like+ * `execFileSync` throws (`status`, `signal`, `stdout`, `stderr`), and git's stderr reaches this process's stderr unless+ * silenced, as `execFileSync` passes it through. `raw` keeps the output untrimmed (NUL-delimited listings).+ */+export async function gitAsync(+ repoPath: string,+ args: string[],+ { configs = [], timeoutMs = 30000, silenceStderr = false, raw = false }: { configs?: string[]; timeoutMs?: number; silenceStderr?: boolean; raw?: boolean } = {},+): Promise<string> {+ noteGitCommand(args);+ const r = await execFileBounded('git', buildGitInvocation(repoPath, args, configs), {+ env: gitChildEnv(readOnlyEnv(args)), timeout: timeoutMs, maxBuffer: 100 * 1024 * 1024,+ });+ if (r.stderr && !silenceStderr) process.stderr.write(r.stderr);+ if (r.error) {+ const code = (r.error as { code?: unknown }).code;+ throw Object.assign(new Error(r.error.message), { status: typeof code === 'number' ? code : null, signal: r.error.signal ?? null,+ code, stdout: r.stdout, stderr: r.stderr });+ }+ return raw ? r.stdout : r.stdout.trim();+}+/*** git() minus the trim — REQUIRED for NUL-delimited listings (`ls-files -z`,* `ls-tree -z`): a filename that begins with a space is the FIRST entry of@@ -368,13 +393,25 @@ export function discoverGitRoot(inputPath: string): string {if (knownOutsideGitRepo(inputPath)) throw new Error('outside a git repository');return git(inputPath, ['rev-parse', '--show-toplevel'], [], 30000, { silenceStderr: true });} catch (error) {- noteGitFailure(inputPath, error);- throw new Error(- `Not inside a git repository: ${inputPath}. GBrain sync requires a git-initialized repo (or a subdirectory of one).`,- );+ throw notAGitRepository(inputPath, error);}}+/** `discoverGitRoot` without blocking the event loop (GBRA-133 2b.3). */+export async function discoverGitRootAsync(inputPath: string): Promise<string> {+ try {+ if (knownOutsideGitRepo(inputPath)) throw new Error('outside a git repository');+ return await gitAsync(inputPath, ['rev-parse', '--show-toplevel'], { silenceStderr: true });+ } catch (error) {+ throw notAGitRepository(inputPath, error);+ }+}++function notAGitRepository(inputPath: string, error: unknown): Error {+ noteGitFailure(inputPath, error);+ return new Error(`Not inside a git repository: ${inputPath}. GBrain sync requires a git-initialized repo (or a subdirectory of one).`);+}+/*** #2964: snapshot the CURRENT on-disk state of a gbrain-owned brain dir as* a baseline commit — used both right after a self-healing `git init` (no@@ -658,6 +695,11 @@ export function isDetachedHead(repoPath: string): boolean {}}+/** `isDetachedHead` without blocking the event loop (GBRA-133 2b.3). */+export async function isDetachedHeadAsync(repoPath: string): Promise<boolean> {+ return gitAsync(repoPath, ['symbolic-ref', '--quiet', 'HEAD']).then(() => false, () => true);+}+export function unique<T>(items: T[]): T[] {return [...new Set(items)];}diff --git a/src/core/sync-upstream.ts b/src/core/sync-upstream.tsindex c58b25c7a3..7dc46d7a15 100644--- a/src/core/sync-upstream.ts+++ b/src/core/sync-upstream.ts@@ -9,6 +9,7 @@* A missing or older-than-24 h observation is "upstream unknown", never fresh.*/import { execFileSync } from './spawn.ts';+import { execFileBounded } from './bounded-child-exec.ts';import { statSync } from 'node:fs';import type { BrainEngine } from './engine.ts';import { ERROR_CATALOGUE } from './error-catalogue.ts';@@ -30,6 +31,12 @@ function git(root: string, args: string[]): string | null {}}+/** GBRA-133 2b.3: `git()` without blocking the event loop; the observation runs after every sync, in residents too. */+async function gitAsync(root: string, args: string[]): Promise<string | null> {+ const r = await execFileBounded('git', ['-C', root, ...args], { env: gitChildEnv(), timeout: 10_000 });+ return r.error ? null : r.stdout.trim() || null;+}+function mtime(path: string | null): number {if (!path) return 0;try { return statSync(path).mtimeMs; } catch { return 0; }@@ -41,16 +48,16 @@ export function tracksUpstream(root: string): boolean {}/** Reads the checkout's upstream state; null when it has no upstream or none was ever fetched or pushed. */-export function observeUpstream(root: string, syncedCommit: string | null): UpstreamObservation | null {- const commit = git(root, ['rev-parse', '--verify', '-q', '@{upstream}^{commit}']);- const ref = commit && git(root, ['rev-parse', '--symbolic-full-name', '@{upstream}']);+export async function observeUpstream(root: string, syncedCommit: string | null): Promise<UpstreamObservation | null> {+ const commit = await gitAsync(root, ['rev-parse', '--verify', '-q', '@{upstream}^{commit}']);+ const ref = commit && await gitAsync(root, ['rev-parse', '--symbolic-full-name', '@{upstream}']);if (!commit || !ref) return null;const checkedMs = Math.max(- mtime(git(root, ['rev-parse', '--path-format=absolute', '--git-path', 'FETCH_HEAD'])),- mtime(git(root, ['rev-parse', '--path-format=absolute', '--git-path', `logs/${ref}`])),+ mtime(await gitAsync(root, ['rev-parse', '--path-format=absolute', '--git-path', 'FETCH_HEAD'])),+ mtime(await gitAsync(root, ['rev-parse', '--path-format=absolute', '--git-path', `logs/${ref}`])),);if (checkedMs === 0) return null;- const count = syncedCommit ? git(root, ['rev-list', '--count', `${syncedCommit}..${commit}`]) : null;+ const count = syncedCommit ? await gitAsync(root, ['rev-list', '--count', `${syncedCommit}..${commit}`]) : null;return { checkedAt: new Date(checkedMs), commit, behind: count === null ? null : Number(count) };}@@ -61,7 +68,7 @@ export async function recordUpstreamObservation(engine: BrainEngine, sourceId: s'SELECT local_path,last_commit FROM sources WHERE id=$1', [sourceId]);const root = repoPath ?? source?.local_path;if (!source || !root) return;- const observed = observeUpstream(root, source.last_commit);+ const observed = await observeUpstream(root, source.last_commit);if (!observed) return;await engine.executeRaw('UPDATE sources SET upstream_checked_at=$2::timestamptz,upstream_commit=$3,upstream_behind=$4 WHERE id=$1',[sourceId, observed.checkedAt.toISOString(), observed.commit, observed.behind]);diff --git a/test/import-cancellation.serial.test.ts b/test/import-cancellation.serial.test.tsindex 8c82350cc5..b107bd3d3a 100644--- a/test/import-cancellation.serial.test.ts+++ b/test/import-cancellation.serial.test.ts@@ -127,6 +127,9 @@ for (const mode of ['caller', 'job', 'log-ingest', 'lease', 'caller-and-lease']const result = await originalImport(...args); calls++;if (mode === 'lease' || mode === 'caller-and-lease') {if (mode === 'caller-and-lease') controller.abort();+ // The lease is lost after the first import (another holder's token, already expired so the next test can take it);+ // the next renewal sees it.+ await engine.executeRaw("UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid(), ttl_expires_at=now() - interval '1 hour', last_refreshed_at=now() - interval '1 hour' WHERE id LIKE 'gbrain-fs:%'");await new Promise(resolve => setTimeout(resolve, 80));} else if (mode !== 'log-ingest') controller.abort();return result;@@ -137,7 +140,7 @@ for (const mode of ['caller', 'job', 'log-ingest', 'lease', 'caller-and-lease']return result;});const lockSpy = spyOn(locks, 'withRefreshingLock').mockImplementation((eng, key, fn, opts) =>- originalLock(eng, key, fn, key.startsWith('gbrain-fs:') && mode.includes('lease') ? { ...opts, ttlMinutes: 0.0005 } : opts));+ originalLock(eng, key, fn, key.startsWith('gbrain-fs:') && mode.includes('lease') ? { ...opts, refreshIntervalMs: 5 } : opts));const sync = () => performSync(engine, { repoPath: root, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 1, signal: controller.signal });try {if (mode === 'job') {diff --git a/test/pathological/s-classic-byte-paths.test.ts b/test/pathological/s-classic-byte-paths.test.tsindex 62e82679f3..01bb0d1419 100644--- a/test/pathological/s-classic-byte-paths.test.ts+++ b/test/pathological/s-classic-byte-paths.test.ts@@ -233,7 +233,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {await withClassic(databaseUrl, async r => {r.write('notes/trail.md ', md('trail')); r.commitAll('odd');const { computeLosslessSyncDelta } = await import('../../src/core/sync-delta.ts');- const delta = computeLosslessSyncDelta(r.root, (await r.lastCommit())!, r.head());+ const delta = await computeLosslessSyncDelta(r.root, (await r.lastCommit())!, r.head());expect(delta.status === 'ok' && delta.manifest.added.sort()).toEqual(['notes/trail.md ', 'ok/healthy-1.md']);const obs = await observe(r, 'ok/healthy-1');expect({ thrown: obs.thrown, healthy: obs.healthy, cursorAtHead: obs.cursorAtHead, ledger: obs.ledger }).toEqual({ thrown: null, healthy: true, cursorAtHead: true, ledger: [] });diff --git a/test/sync-resumable-import.serial.test.ts b/test/sync-resumable-import.serial.test.tsindex 888119263b..80386f8fda 100644--- a/test/sync-resumable-import.serial.test.ts+++ b/test/sync-resumable-import.serial.test.ts@@ -154,12 +154,13 @@ describe('#1794 — resumable incremental sync (pinned target)', () => {for (let i = 0; i < 30; i++) files[`p${i}.md`] = pageMd(`P${i}`);const c1 = commitPages(repoPath, files, 'thirty pages');- // Abort once the checkpoint shows at least one banked path.+ // Abort once the checkpoint shows at least one banked path, while the import loop still runs (all 30 banked means the+ // loop is done, and an abort then lands in the bookmark window, which this test does not cover).const ac = new AbortController();const fp = syncFingerprint({ lastCommit: c0 });const poll = setInterval(() => {loadOpCheckpoint(engine, { op: 'sync', fingerprint: fp })- .then((paths) => { if (paths.length >= 1 && !ac.signal.aborted) ac.abort(); })+ .then((paths) => { if (paths.length >= 1 && paths.length < 30 && !ac.signal.aborted) ac.abort(); }).catch(() => {});}, 1);const aborted = await performSync(engine, { repoPath, noPull: true, noEmbed: true, signal: ac.signal });