Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): ordinary checks continue pending remote evidence (#6687, #6614)
time-attacka34121c791de
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex 37f8f04fb5..2e4cf56d30 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. `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/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. An ordinary (non-forced) `getBackupStatus` re-probes before the one-hour sweep clock expires when the cached verdict still has pending repository evidence (a configured remote left `budget_exhausted`, relabelled `stale`, or `verified` older than the evidence window), at most once per `BACKUP_CONTINUATION_THROTTLE_MS` (60 s); real failures (`unavailable`, `mismatch`, `missing_ref`) are not retried per check (#6614, #6687; `test/backup-pending-continuation.serial.test.ts`). `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/src/core/backup/coverage.ts b/src/core/backup/coverage.tsindex 10cc59f62a..eea16f2fbb 100644--- a/src/core/backup/coverage.ts+++ b/src/core/backup/coverage.ts@@ -37,6 +37,7 @@ import {saveBackupStatus,currentBackupEvidence,isVerifiedRecoverable,+ isRepoAsset,assetBlocksRecovery,BACKUP_VERIFICATION_MAX_AGE_MS,BACKUP_RECOVERY_SCOPE,@@ -426,6 +427,26 @@ function operatingOnHostBrain(): boolean {}}+/** Minimum gap between two continuation sweeps, so a burst of doctor calls shares one probe pass. */+export const BACKUP_CONTINUATION_THROTTLE_MS = 60_000;++/**+ * #6614/#6687: a cached verdict still owes remote probes when a configured+ * repository was cut off by the per-call budget or holds verified evidence+ * older than the evidence window. Real failures (unavailable, mismatch,+ * missing_ref) are not pending, so they are not retried on every check.+ */+function hasPendingRepoEvidence(cached: BackupStatus | null, nowMs: number): boolean {+ return (cached?.assets ?? []).some((a) => {+ if (!isRepoAsset(a) || a.configured_remote !== true) return false;+ const state = a.verification?.state;+ if (state === 'budget_exhausted' || state === 'stale') return true;+ if (state !== 'verified') return false;+ const age = nowMs - Date.parse(a.verification?.checked_at ?? '');+ return !Number.isFinite(age) || age < 0 || age > BACKUP_VERIFICATION_MAX_AGE_MS;+ });+}+export async function getBackupStatus(engine: BrainEngine,opts: BackupCoverageOpts & { forceRefresh?: boolean },@@ -435,7 +456,8 @@ export async function getBackupStatus(const nowMs = (opts.now ?? new Date()).getTime();const remoteAge = nowMs - Date.parse(cached?.remote_check_at ?? '');const remoteDue = opts.localGitProbes === true && opts.verifyRemoteRefs === true- && (!Number.isFinite(remoteAge) || remoteAge < 0 || remoteAge > BACKUP_VERIFICATION_MAX_AGE_MS);+ && (!Number.isFinite(remoteAge) || remoteAge < 0 || remoteAge > BACKUP_VERIFICATION_MAX_AGE_MS+ || (remoteAge >= BACKUP_CONTINUATION_THROTTLE_MS && hasPendingRepoEvidence(cached, nowMs)));if (!opts.forceRefresh && cached && !isBackupStatusStale(cached, nowMs) && !remoteDue) return currentBackupEvidence(cached, nowMs);try {const fresh = await computeBackupCoverage(engine, { ...opts, previousStatus: cached ?? undefined });diff --git a/test/backup-pending-continuation.serial.test.ts b/test/backup-pending-continuation.serial.test.tsnew file mode 100644index 0000000000..f93dc1d425--- /dev/null+++ b/test/backup-pending-continuation.serial.test.ts@@ -0,0 +1,84 @@+import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test';+import * as childProcess from 'node:child_process';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { getBackupStatus } from '../src/core/backup/coverage.ts';+import { __setBackupStatusPathForTests, loadBackupStatus, saveBackupStatus } from '../src/core/backup/status-file.ts';+import { checkBackupCoverage } from '../src/commands/doctor/checks/backup-coverage.ts';+import { BACKUP_REMOTE_PROBE_CAP } from '../src/core/backup/repository.ts';+import { makeGitFixture } from './helpers/git-fixture.ts';++let tmp: string; let oldHome: string | undefined;+const now = new Date('2026-09-22T12:00:00Z');+const verified = { localGitProbes: true, verifyRemoteRefs: true, now };+beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), 'w17-backup-')); oldHome = process.env.GBRAIN_HOME; process.env.GBRAIN_HOME = tmp; __setBackupStatusPathForTests(join(tmp, 'status.json')); });+afterEach(() => { if (oldHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = oldHome; __setBackupStatusPathForTests(null); rmSync(tmp, { recursive: true, force: true }); });+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+async function repository(name: string) {+ const root = join(tmp, name); const remote = join(tmp, `${name}.git`);+ mkdirSync(root); await makeGitFixture(root); git(root, 'branch', '-M', 'main');+ writeFileSync(join(root, 'note.md'), '# x\n'); git(root, 'add', '.'); git(root, 'commit', '-m', 'f');+ git(tmp, 'init', '--bare', '-b', 'main', remote); git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-u', 'origin', 'main');+ return root;+}+const engine = (roots: string[]) => ({ kind: 'pglite', executeRaw: async (sql: string) => sql.includes('FROM pages') ? [{ n: 1 }]+ : roots.map((root, i) => ({ id: `fixture-${i}`, name: 'fixture', local_path: root, archived: false, config: {} })) }) as unknown as BrainEngine;+function spyLsRemote() {+ const run = childProcess.execFile; const commands: string[][] = [];+ const probe = spyOn(childProcess, 'execFile').mockImplementation(((file: string, args: string[], o: unknown, cb: unknown) => { if (args.includes('ls-remote')) commands.push(args); return (run as Function)(file, args, o, cb); }) as typeof childProcess.execFile);+ return { commands, restore: () => probe.mockRestore() };+}++test('#6614 ordinary (non-forced) checks continue budget_exhausted roots inside the hour', async () => {+ const roots = await Promise.all(Array.from({ length: BACKUP_REMOTE_PROBE_CAP + 2 }, (_, i) => repository(`r${i}`)));+ const first = await getBackupStatus(engine(roots), verified);+ expect(first.assets.filter(a => a.verification?.state === 'budget_exhausted')).toHaveLength(2);+ const spy = spyLsRemote();+ try {+ const second = await getBackupStatus(engine(roots), { ...verified, now: new Date(now.getTime() + 60_000) });+ expect(second.totals.recoverable_repos).toBe(roots.length);+ expect(spy.commands.length).toBeGreaterThan(0);+ const before = spy.commands.length;+ const third = await getBackupStatus(engine(roots), { ...verified, now: new Date(now.getTime() + 180_000) });+ expect(spy.commands.length).toBe(before);+ expect(third.totals.recoverable_repos).toBe(roots.length);+ } finally { spy.restore(); }+}, 30_000);++test('continuation is throttled and never retries real remote failures', async () => {+ const roots = await Promise.all(Array.from({ length: BACKUP_REMOTE_PROBE_CAP + 2 }, (_, i) => repository(`t${i}`)));+ await getBackupStatus(engine(roots), verified);+ const spy = spyLsRemote();+ try {+ await getBackupStatus(engine(roots), { ...verified, now: new Date(now.getTime() + 30_000) });+ expect(spy.commands).toHaveLength(0);+ } finally { spy.restore(); }++ const root = await repository('broken');+ git(root, 'remote', 'set-url', 'origin', join(tmp, 'missing.git'));+ const failed = await getBackupStatus(engine([root]), { ...verified, forceRefresh: true });+ expect(failed.assets[0].verification?.state).toBe('unavailable');+ const retry = spyLsRemote();+ try {+ await getBackupStatus(engine([root]), { ...verified, now: new Date(now.getTime() + 120_000) });+ expect(retry.commands).toHaveLength(0);+ } finally { retry.restore(); }+}, 30_000);++test('#6687 doctor relabels a retained verified row stale and never re-probes while remote_check_at is fresh', async () => {+ const root = await repository('one');+ saveBackupStatus(await getBackupStatus(engine([root]), { ...verified, forceRefresh: true }));+ const s = loadBackupStatus()!;+ // a later sweep kept this verified row (budget ran out) but stamped the sweep clock 40 min later+ saveBackupStatus({ ...s, remote_check_at: new Date(now.getTime() + 40 * 60_000).toISOString(), checked_at: new Date(now.getTime() + 40 * 60_000).toISOString() });+ const spy = spyLsRemote();+ try {+ const at = new Date(now.getTime() + 65 * 60_000);+ const check = await checkBackupCoverage(engine([root]), { localOnly: true, now: at });+ expect(spy.commands.length).toBeGreaterThan(0);+ expect(check.status).toBe('ok');+ } finally { spy.restore(); }+}, 30_000);