Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): a remote probe starts only with its full two-second slot (#6499)
garrytanb7dc8ba6fa3c
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex b5e596962c..37f8f04fb5 100644--- a/docs/architecture/key-files/workspace-push-and-backup.md+++ b/docs/architecture/key-files/workspace-push-and-backup.md@@ -7,5 +7,5 @@ and the backup coverage verdicts that read its status records. Operatorguide: [backup check](../../operations/backup-check.md).Key files:-- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).+- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. `budgetAllowsProbe` starts a probe only with its full two-second slot inside the deadline (a sub-slot leftover defers the root as `budget_exhausted` and the sweep keeps that root's first-pass `verified` evidence); an `unavailable` verification carries `cause: 'timeout' | 'exit'` (#6499). Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799: `isSupersededPushStatus(entry)` / `livePushStatuses(entries)` drop a record the managed topology has superseded (code or reason prefix `writer_coordinator_required`, or a `repoRoot` that is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (`test/workspace-push-superseded-status.test.ts`); the hook call sites read `livePushStatuses(readPushStatuses())`.diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.mdindex 029c560936..2964ce5e73 100644--- a/docs/operations/backup-check.md+++ b/docs/operations/backup-check.md@@ -112,7 +112,10 @@ time. Evidence expires after one hour even if the configured coverage intervalis longer. Reuse retains its original timestamp and requires unchanged sourceidentity, physical Git directory, HEAD, branch, origin, push-status identity anda clean tree. Roots beyond the budget report `budget_exhausted`; successive-sweeps can cover them. Background and stdio refreshes use local probes only;+sweeps can cover them. A probe starts only when its full two-second slot is+still inside the eight-second budget: a root that would get less is deferred+(`budget_exhausted`, and earlier `verified` evidence for it is kept) rather+than probed on the leftover and recorded as `unavailable`. Background and stdio refreshes use local probes only;remote MCP doctor reads aggregate cache only, with no engine or Git access.### Remote verification and your Git configuration@@ -134,8 +137,8 @@ export is not used, and the remote's host key must already be in `known_hosts`.| `verified` | The remote branch HEAD matches a clean local HEAD. | Nothing. || `missing_ref` | The remote answered but has no such branch. | `git push -u origin <branch>`, then `gbrain backup check`. || `mismatch` | The remote HEAD differs from the local HEAD, or the tree changed during the probe. | Push or pull until they match, then `gbrain backup check`. |-| <a id="remote-unavailable"></a>`unavailable` | `git ls-remote` failed: no network, authentication refused, or an unknown host key. The probe passes only `HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, `HTTPS_PROXY`/`https_proxy`, `HTTP_PROXY`/`http_proxy`, `NO_PROXY`/`no_proxy` (and `USERPROFILE`, `APPDATA`, `SystemRoot` on Windows). | Run `git -C <root> ls-remote origin` in the same shell; credentials must come from your Git config, a credential helper, `~/.ssh/config` or the SSH agent, not from a prompt or `GIT_SSH_COMMAND`. |-| `budget_exhausted` | The sweep's eight-probe or eight-second budget ran out first. | Run `gbrain backup check` again. |+| <a id="remote-unavailable"></a>`unavailable` | `git ls-remote` failed: no network, authentication refused, or an unknown host key. `cause` says which kind: `timeout` (the remote did not answer within its full two-second slot) or `exit` (git exited with an error). The probe passes only `HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, `HTTPS_PROXY`/`https_proxy`, `HTTP_PROXY`/`http_proxy`, `NO_PROXY`/`no_proxy` (and `USERPROFILE`, `APPDATA`, `SystemRoot` on Windows). | Run `git -C <root> ls-remote origin` in the same shell; credentials must come from your Git config, a credential helper, `~/.ssh/config` or the SSH agent, not from a prompt or `GIT_SSH_COMMAND`. |+| `budget_exhausted` | The sweep's eight-probe or eight-second budget ran out first, or this remote would not have received its full two-second slot. | Run `gbrain backup check` again. || `stale`, `not_checked` | Earlier evidence expired or no probe ran yet. | `gbrain backup check`. |When does the compute actually run? On any of: `gbrain backup check`, a stalediff --git a/src/core/backup/coverage.ts b/src/core/backup/coverage.tsindex 0880d10b86..10cc59f62a 100644--- a/src/core/backup/coverage.ts+++ b/src/core/backup/coverage.ts@@ -44,7 +44,7 @@ import {type BackupComputedBy,type BackupStatus,} from './status-file.ts';-import { assessBackupRepository, BACKUP_REMOTE_PROBE_CAP, type RemoteProbeBudget } from './repository.ts';+import { assessBackupRepository, BACKUP_REMOTE_PROBE_CAP, budgetAllowsProbe, type RemoteProbeBudget } from './repository.ts';/** No silent caps: at most this many deduped git roots are probed per run;* anything beyond is logged as skipped. */@@ -323,14 +323,16 @@ export async function computeBackupCoverage(});for (const { root, index } of ordered) {const asset = assets[index];- if (remoteBudget.remaining <= 0 || (remoteBudget.deadline !== undefined && Date.now() >= remoteBudget.deadline)) {+ if (!budgetAllowsProbe(remoteBudget)) {if (asset.verification?.state !== 'verified') {asset.verification = { ...asset.verification, state: 'budget_exhausted' };}continue;}await yieldLoop();- assets[index] = await assessBackupRepository(root, asset.kind as 'source_repo' | 'bootstrap_workspace', asset.id, now, remoteBudget);+ const probed = await assessBackupRepository(root, asset.kind as 'source_repo' | 'bootstrap_workspace', asset.id, now, remoteBudget);+ // A deferred probe (the slot closed between the pre-check and the call) keeps first-pass verified evidence; a real transport failure still supersedes it.+ assets[index] = probed.verification?.state === 'budget_exhausted' && asset.verification?.state === 'verified' ? asset : probed;}}diff --git a/src/core/backup/repository.ts b/src/core/backup/repository.tsindex c2de66b09d..b1b54be363 100644--- a/src/core/backup/repository.ts+++ b/src/core/backup/repository.ts@@ -14,6 +14,17 @@ export const BACKUP_REMOTE_TIMEOUT_MS = 2_000;export interface RemoteProbeBudget { remaining: number; deadline?: number }+/**+ * A remote probe starts only when its full `BACKUP_REMOTE_TIMEOUT_MS` slot is+ * still inside the sweep deadline. A probe started on the leftover sub-slot+ * would be killed mid-handshake and record a healthy slow remote as+ * `unavailable` (#6499); deferring it reports `budget_exhausted` instead.+ */+export function budgetAllowsProbe(budget: RemoteProbeBudget, nowMs: number = Date.now()): boolean {+ if (budget.remaining <= 0) return false;+ return budget.deadline === undefined || budget.deadline - nowMs >= BACKUP_REMOTE_TIMEOUT_MS;+}+/** Variables that locate the user's own git config, credentials and network path. */export const BACKUP_GIT_ENV_ALLOWLIST = ['HOME', 'PATH', 'XDG_CONFIG_HOME', 'SSH_AUTH_SOCK', 'GIT_CONFIG_GLOBAL','HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'NO_PROXY', 'no_proxy'] as const;@@ -115,8 +126,7 @@ export async function assessBackupRepository(return asset;}budget.deadline ??= Date.now() + BACKUP_REMOTE_BUDGET_MS;- const remainingMs = budget.deadline - Date.now();- if (budget.remaining <= 0 || remainingMs <= 0) {+ if (!budgetAllowsProbe(budget)) {asset.verification = { state: 'budget_exhausted', repository_fingerprint: fingerprint };return asset;}@@ -126,11 +136,13 @@ export async function assessBackupRepository(execFile('git', ['-C', root, '-c', 'protocol.allow=never', '-c', 'protocol.file.allow=always','-c', 'protocol.https.allow=always', '-c', 'protocol.http.allow=always', '-c', 'protocol.ssh.allow=always','-c', 'http.followRedirects=false', '-c', 'credential.interactive=false', 'ls-remote', '--exit-code', '--refs', 'origin', ref], {- encoding: 'utf8', timeout: Math.min(BACKUP_REMOTE_TIMEOUT_MS, remainingMs), maxBuffer: 64 * 1024,+ encoding: 'utf8', timeout: BACKUP_REMOTE_TIMEOUT_MS, maxBuffer: 64 * 1024,env: { ...backupGitEnv(), GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', SSH_ASKPASS_REQUIRE: 'never', GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=2' },}, (error, stdout) => error ? reject(error) : resolve(stdout));- }).catch(error => {- asset.verification = { state: error.code === 2 ? 'missing_ref' : 'unavailable', checked_at: now.toISOString(), repository_fingerprint: fingerprint };+ }).catch((error: { code?: unknown; killed?: boolean }) => {+ asset.verification = error.code === 2+ ? { state: 'missing_ref', checked_at: now.toISOString(), repository_fingerprint: fingerprint }+ : { state: 'unavailable', cause: error.killed ? 'timeout' : 'exit', checked_at: now.toISOString(), repository_fingerprint: fingerprint };return null;});if (output === null) return asset;diff --git a/src/core/backup/status-file.ts b/src/core/backup/status-file.tsindex f18582ed70..848d36d8d0 100644--- a/src/core/backup/status-file.ts+++ b/src/core/backup/status-file.ts@@ -72,6 +72,8 @@ export interface BackupAssetVerdict {configured_remote?: boolean;verification?: {state: 'verified' | 'not_checked' | 'unavailable' | 'missing_ref' | 'mismatch' | 'budget_exhausted' | 'stale';+ /** Why an `unavailable` probe failed: the full two-second slot ran out, or git exited with an error. */+ cause?: 'timeout' | 'exit';checked_at?: string;local_commit?: string;remote_commit?: string;diff --git a/test/backup-verification.serial.test.ts b/test/backup-verification.serial.test.tsindex 2546957d81..ca4461a75d 100644--- a/test/backup-verification.serial.test.ts+++ b/test/backup-verification.serial.test.ts@@ -296,3 +296,73 @@ test('the remote probe reads the user git config through HOME, so an insteadOf rexpect(result.state).toBe('ok');});}, 15_000);++// #6499: a probe is started only with its full two-second slot; a sub-slot leftover defers the root as budget_exhausted.+type ExecFileStub = (file: string, args: string[], options: { timeout: number }, callback: (error: Error | null, stdout: string) => void) => unknown;++/** A remote that answers correctly after `answerMs`, killed the way execFile kills a timed-out child when the slot is shorter. */+function slowRemote(answerMs: number, timeouts: number[]): ExecFileStub {+ return (_file, args, options, callback) => {+ timeouts.push(options.timeout);+ const head = git(args[args.indexOf('-C') + 1], 'rev-parse', 'HEAD');+ const ref = args[args.length - 1];+ const timers: ReturnType<typeof setTimeout>[] = [];+ const finish = (error: Error | null, stdout: string) => { for (const t of timers) clearTimeout(t); callback(error, stdout); };+ timers.push(setTimeout(() => finish(null, `${head}\t${ref}\n`), answerMs));+ timers.push(setTimeout(() => finish(Object.assign(new Error('killed'), { killed: true, signal: 'SIGTERM', code: null }), ''), options.timeout));+ return {};+ };+}++test('a remote that would not get its full slot is deferred as budget_exhausted, never probed on a sub-slot (#6499)', async () => {+ const roots = await Promise.all(Array.from({ length: 5 }, async (_, i) => (await repository(`slow-${i}`)).root));+ const timeouts: number[] = [];+ const probe = spyOn(childProcess, 'execFile').mockImplementation(slowRemote(1_700, timeouts) as unknown as typeof childProcess.execFile);+ try {+ const result = await computeBackupCoverage(engine(roots), verified);+ expect(timeouts).toEqual([BACKUP_REMOTE_TIMEOUT_MS, BACKUP_REMOTE_TIMEOUT_MS, BACKUP_REMOTE_TIMEOUT_MS, BACKUP_REMOTE_TIMEOUT_MS]);+ const states = result.assets.filter(a => a.kind === 'source_repo').map(a => a.verification?.state);+ expect(states.filter(s => s === 'verified')).toHaveLength(4);+ expect(states).toContain('budget_exhausted');+ expect(states).not.toContain('unavailable');+ } finally { probe.mockRestore(); }+}, 20_000);++test('a deferred probe keeps first-pass verified evidence; a transport failure still supersedes it (#6499)', async () => {+ const roots = await Promise.all(Array.from({ length: 5 }, async (_, i) => (await repository(`keep-${i}`)).root));+ const first = await getBackupStatus(engine(roots), { ...verified, forceRefresh: true });+ expect(first.assets.filter(a => a.verification?.state === 'verified')).toHaveLength(5);+ const timeouts: number[] = [];+ const probe = spyOn(childProcess, 'execFile').mockImplementation(slowRemote(1_700, timeouts) as unknown as typeof childProcess.execFile);+ try {+ const second = await getBackupStatus(engine(roots), { ...verified, forceRefresh: true, now: new Date(now.getTime() + 1000) });+ expect(timeouts).toHaveLength(4);+ expect(second.assets.filter(a => a.kind === 'source_repo').map(a => a.verification?.state)).toEqual(['verified', 'verified', 'verified', 'verified', 'verified']);+ expect(second.totals.recoverable_repos).toBe(5);+ } finally { probe.mockRestore(); }+ const failing = spyOn(childProcess, 'execFile').mockImplementation(((_f: string, _a: string[], options: { timeout: number }, callback: (error: Error | null, stdout: string) => void) => {+ timeouts.push(options.timeout);+ setTimeout(() => callback(Object.assign(new Error('fatal: could not read from remote'), { code: 128 }), ''), 10);+ return {};+ }) as unknown as typeof childProcess.execFile);+ try {+ const third = await getBackupStatus(engine(roots), { ...verified, forceRefresh: true, now: new Date(now.getTime() + 2000) });+ expect(third.assets.filter(a => a.kind === 'source_repo').every(a => a.verification?.state === 'unavailable' && a.verification.cause === 'exit')).toBe(true);+ expect(third.totals.recoverable_repos).toBe(0);+ } finally { failing.mockRestore(); }+}, 30_000);++test('assessBackupRepository with less than a full slot left starts no git process; a killed full-slot probe says cause: timeout (#6499)', async () => {+ const { root } = await repository('direct');+ const calls: number[] = [];+ const probe = spyOn(childProcess, 'execFile').mockImplementation(slowRemote(5_000, calls) as unknown as typeof childProcess.execFile);+ try {+ const deferred = await assessBackupRepository(root, 'source_repo', 'source-id', now, { remaining: 1, deadline: Date.now() + 1_000 });+ expect(calls).toEqual([]);+ expect(deferred.verification).toMatchObject({ state: 'budget_exhausted' });+ expect(deferred.verification).not.toHaveProperty('cause');+ const killed = await assessBackupRepository(root, 'source_repo', 'source-id', now, { remaining: 1 });+ expect(calls).toEqual([BACKUP_REMOTE_TIMEOUT_MS]);+ expect(killed.verification).toMatchObject({ state: 'unavailable', cause: 'timeout' });+ } finally { probe.mockRestore(); }+}, 15_000);