Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): bounded dirtiness read, configurable remote timeout, timeouts reported as unconfirmed (#6907)
garrytan99aa70f6890b
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex bc7f4394d2..58f5aecd6e 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. 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/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). #6907: the slot is `resolveBackupRemoteTimeoutMs` (env `GBRAIN_BACKUP_REMOTE_TIMEOUT_MS` > DB `backup.remote_timeout_ms` > 2 s, clamped 500-30000 ms; the budget is `max(8 s, 4 slots)`), a timed-out probe is `isRemoteTimeout` (counted in `totals.remote_timeouts`, reason "remote check timed out"), and `worktreeDirty` streams `git status --porcelain` and stops at the first non-metadata line (`test/pathological/s-6907-backup-check-bounds.test.ts`). 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_STREAM_SCAN_MAX_BYTES`, 512 MiB), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through. A blob up to `PUSH_MAX_SCAN_BYTES` (25 MiB) is read whole and scanned by `scanText` as before; a larger one is found by its index size (one `ls-files -s` plus one `cat-file --batch-check`, `stagedBlobSizes`), streamed by oid through `git cat-file blob` into `scanTextStream` (`secret-scan-stream.ts`) and fails closed when git errors, runs past 10 minutes or delivers a byte count other than the recorded size (`test/workspace-push-large-blob.serial.test.ts`: a clean 30 MiB file pushes, secrets across window seams block once each with their line, the ceiling still blocks) — 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 75a86a477f..57549de139 100644--- a/docs/operations/backup-check.md+++ b/docs/operations/backup-check.md@@ -106,7 +106,15 @@ payload includes `configured_repos`, per-asset `configured_remote` andTrusted local, non-quiet backup CLI and doctor may perform read-only remoteprobes: at most eight refs per sweep, within a shared eight-second probe budget-and two-second subprocess timeouts, without prompts, pushes or fetches. Pending+and two-second subprocess timeouts, without prompts, pushes or fetches. For a+slow remote, `gbrain config set backup.remote_timeout_ms <ms>` (database+setting; `GBRAIN_BACKUP_REMOTE_TIMEOUT_MS` wins) sets each remote probe's slot,+clamped to 500-30000 ms; the sweep budget grows to four slots when that is more+than eight seconds. A probe that runs out of its slot is counted in+`totals.remote_timeouts` and shown as "remote check timed out": the backup is+unconfirmed, not missing (#6907). The local dirtiness read stops at the first+changed path, so a tree with a very large `git status` listing reads `dirty`+instead of `unknown / probe_failed`. Pendingand oldest evidence is rotated first rather than probing the same roots eachtime. Evidence expires after one hour even if the configured coverage intervalis longer. Reuse retains its original timestamp and requires unchanged source@@ -137,7 +145,7 @@ 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>` <!-- gbrain-allow-shared-tree-git: one-time first push that creates the remote branch and sets its upstream -->, 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. `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`. |+| <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 slot, `backup.remote_timeout_ms`, default two seconds; reported as "remote check timed out" and counted in `totals.remote_timeouts`, never as a missing backup) 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`. |@@ -156,6 +164,8 @@ gbrain config set backup.check_enabled false # off (file plane)gbrain config set backup.check_interval_days 30 # default 30; set rejects values < 1GBRAIN_BACKUP_CHECK=0 # env kill switch (everything)GBRAIN_BACKUP_CHECK_DAYS=<n> # env interval override (wins over config)+gbrain config set backup.remote_timeout_ms 6000 # remote probe slot, 500-30000 ms, default 2000 (database)+GBRAIN_BACKUP_REMOTE_TIMEOUT_MS=<ms> # env slot override (wins over config)```Interval values below 1 or non-numeric (env or a hand-edited config file) falldiff --git a/src/commands/backup.ts b/src/commands/backup.tsindex 578315fd21..55a69395a7 100644--- a/src/commands/backup.ts+++ b/src/commands/backup.ts@@ -28,6 +28,7 @@ import {backupNagGate,isBackupStatusStale,isVerifiedRecoverable,+ isRemoteTimeout,loadBackupStatus,currentBackupEvidence,type BackupAssetVerdict,@@ -131,11 +132,15 @@ function renderHuman(s: BackupStatus, out: (line: string) => void): void {out(`backup coverage — ${s.overall === 'warn' ? 'WARN' : 'ok'} (checked ${age}, by ${s.computed_by})`);for (const a of s.assets) {const mark = isVerifiedRecoverable(a) ? '✓' : a.state === 'no_remote' ? '✗' : a.state === 'info' ? '·' : '⚠';- out(` ${mark} [${a.kind}] ${a.id} — ${a.state}${a.verification ? `; remote evidence: ${a.verification.state}` : ''}${a.detail ? `: ${a.detail}` : ''}`);+ out(` ${mark} [${a.kind}] ${a.id} — ${a.state}${a.verification ? `; remote evidence: ${isRemoteTimeout(a) ? 'timed out (unconfirmed, not missing)' : a.verification.state}` : ''}${a.detail ? `: ${a.detail}` : ''}`);const fix = suggestedFix(a);if (fix) out(` fix: ${fix.join(' ')}`);}out(recoveryStatement(s));+ const timeouts = s.totals.remote_timeouts ?? 0;+ if (timeouts > 0) {+ out(`note: ${timeouts} remote check(s) timed out, so those backups are unconfirmed, not missing; for a slow remote raise the slot (default 2000 ms, max 30000): gbrain config set backup.remote_timeout_ms <ms>`);+ }if (s.degraded) {out('note: the brain database was unreadable during this check — verdict is partial (not cached)');}diff --git a/src/core/backup/coverage.ts b/src/core/backup/coverage.tsindex eea16f2fbb..c66b56a30e 100644--- a/src/core/backup/coverage.ts+++ b/src/core/backup/coverage.ts@@ -37,6 +37,7 @@ import {saveBackupStatus,currentBackupEvidence,isVerifiedRecoverable,+ isRemoteTimeout,isRepoAsset,assetBlocksRecovery,BACKUP_VERIFICATION_MAX_AGE_MS,@@ -45,7 +46,7 @@ import {type BackupComputedBy,type BackupStatus,} from './status-file.ts';-import { assessBackupRepository, BACKUP_REMOTE_PROBE_CAP, budgetAllowsProbe, type RemoteProbeBudget } from './repository.ts';+import { assessBackupRepository, BACKUP_REMOTE_PROBE_CAP, BACKUP_REMOTE_TIMEOUT_KEY, budgetAllowsProbe, resolveBackupRemoteTimeoutMs, 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. */@@ -142,7 +143,7 @@ export async function computeBackupCoverage(const now = opts.now ?? new Date();const assets: BackupAssetVerdict[] = [];const remoteBudget: RemoteProbeBudget | undefined = opts.localGitProbes === true && opts.verifyRemoteRefs === true- ? { remaining: BACKUP_REMOTE_PROBE_CAP } : undefined;+ ? { remaining: BACKUP_REMOTE_PROBE_CAP, timeoutMs: resolveBackupRemoteTimeoutMs(await Promise.resolve().then(() => engine.getConfig(BACKUP_REMOTE_TIMEOUT_KEY)).catch(() => null)) } : undefined;const previousAge = now.getTime() - Date.parse(opts.previousStatus?.checked_at ?? '');const previous = opts.localGitProbes === true && opts.previousStatus && !opts.previousStatus.degraded&& Number.isFinite(previousAge) && previousAge >= 0 && !isBackupStatusStale(opts.previousStatus, now.getTime())@@ -391,6 +392,7 @@ export async function computeBackupCoverage(failing: assets.filter((a) => a.state === 'failing').length,configured_repos: assets.filter(a => a.configured_remote === true).length,recoverable_repos: assets.filter(isVerifiedRecoverable).length,+ remote_timeouts: assets.filter(isRemoteTimeout).length,pages_at_risk: pagesAtRisk,};const maturity = assets.some(assetBlocksRecovery) ? await brainMaturity(engine) : undefined;diff --git a/src/core/backup/repository.ts b/src/core/backup/repository.tsindex 7b6817c6aa..c1c1a5e148 100644--- a/src/core/backup/repository.ts+++ b/src/core/backup/repository.ts@@ -1,4 +1,4 @@-import { execFile, execFileSync } from '../spawn.ts';+import { execFile, execFileSync, spawn } from '../spawn.ts';import { createHash } from 'node:crypto';import { existsSync, realpathSync, statSync } from 'node:fs';import { buildGitEnv } from '../git-remote.ts';@@ -11,18 +11,41 @@ import { BACKUP_VERIFICATION_MAX_AGE_MS, type BackupAssetVerdict } from './statuexport const BACKUP_REMOTE_PROBE_CAP = 8;export const BACKUP_REMOTE_BUDGET_MS = 8_000;export const BACKUP_REMOTE_TIMEOUT_MS = 2_000;+export const BACKUP_REMOTE_TIMEOUT_KEY = 'backup.remote_timeout_ms';+export const BACKUP_REMOTE_TIMEOUT_MIN_MS = 500;+export const BACKUP_REMOTE_TIMEOUT_MAX_MS = 30_000;-export interface RemoteProbeBudget { remaining: number; deadline?: number }+/** `timeoutMs`: each remote probe's slot (resolveBackupRemoteTimeoutMs); default BACKUP_REMOTE_TIMEOUT_MS. */+export interface RemoteProbeBudget { remaining: number; deadline?: number; timeoutMs?: 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.+ * #6907: the remote probe slot. GBRAIN_BACKUP_REMOTE_TIMEOUT_MS wins over the+ * brain's `backup.remote_timeout_ms`; a non-number is ignored, and a number is+ * clamped to 0.5-30 s. Default 2 s.+ */+export function resolveBackupRemoteTimeoutMs(configured: string | null | undefined, env: string | undefined = process.env.GBRAIN_BACKUP_REMOTE_TIMEOUT_MS): number {+ for (const raw of [env, configured]) {+ if (raw == null || raw.trim() === '') continue;+ const ms = Number(raw);+ if (Number.isFinite(ms)) return Math.min(BACKUP_REMOTE_TIMEOUT_MAX_MS, Math.max(BACKUP_REMOTE_TIMEOUT_MIN_MS, Math.round(ms)));+ }+ return BACKUP_REMOTE_TIMEOUT_MS;+}++/** The sweep's remote budget: eight seconds, or four slots when the slot is longer. */+export function backupRemoteBudgetMs(timeoutMs: number): number {+ return Math.max(BACKUP_REMOTE_BUDGET_MS, 4 * timeoutMs);+}++/**+ * A remote probe starts only when its full 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;+ return budget.deadline === undefined || budget.deadline - nowMs >= (budget.timeoutMs ?? BACKUP_REMOTE_TIMEOUT_MS);}/** Variables that locate the user's own git config, credentials and network path. */@@ -51,6 +74,37 @@ function git(root: string, args: string[]): string {}).trim();}+/**+ * #6907: does the tree hold changes besides physical-root metadata? Reads+ * `git status --porcelain` as it streams and stops git at the first other+ * line, so a tree with a huge listing costs one line instead of overflowing a+ * buffer; a single line past the bound reads dirty (metadata names are short).+ * Fails on a timeout or a git error, like the other local probes.+ */+function worktreeDirty(root: string): Promise<boolean> {+ return new Promise((resolve, reject) => {+ const child = spawn('git', ['-C', root, 'status', '--porcelain'], { stdio: ['ignore', 'pipe', 'ignore'], env: backupGitEnv() });+ let pending = '';+ let settled = false;+ const settle = (result: boolean | Error) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ child.kill();+ if (result instanceof Error) reject(result); else resolve(result);+ };+ const timer = setTimeout(() => settle(new Error('git status timed out')), 2_000);+ child.stdout!.setEncoding('utf8');+ child.stdout!.on('data', (chunk: string) => {+ const lines = (pending + chunk).split('\n');+ pending = lines.pop()!;+ if (withoutPhysicalRootMetadata(lines.join('\n')).length > 0 || pending.length > 1024 * 1024) settle(true);+ });+ child.on('error', settle);+ child.on('close', (code: number | null) => settle(code === 0 ? withoutPhysicalRootMetadata(pending).length > 0 : new Error(`git status exited ${code}`)));+ });+}+function repositoryFingerprint(root: string, origin: string, branch: string, head: string): string {const directory = realpathSync(git(root, ['rev-parse', '--absolute-git-dir']));const stat = statSync(directory, { bigint: true });@@ -97,7 +151,7 @@ export async function assessBackupRepository(}const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);const head = git(root, ['rev-parse', '--verify', 'HEAD']);- const dirty = withoutPhysicalRootMetadata(git(root, ['status', '--porcelain'])).length > 0;+ const dirty = await worktreeDirty(root);let ahead: number | undefined;try { ahead = Number(git(root, ['rev-list', '--count', `refs/remotes/origin/${branch}..HEAD`])); } catch {}asset.state = ahead && ahead > 0 ? 'unpushed' : dirty ? 'dirty' : 'ok';@@ -126,7 +180,8 @@ export async function assessBackupRepository(}return asset;}- budget.deadline ??= Date.now() + BACKUP_REMOTE_BUDGET_MS;+ const timeoutMs = budget.timeoutMs ?? BACKUP_REMOTE_TIMEOUT_MS;+ budget.deadline ??= Date.now() + backupRemoteBudgetMs(timeoutMs);if (!budgetAllowsProbe(budget)) {asset.verification = { state: 'budget_exhausted', repository_fingerprint: fingerprint };return asset;@@ -137,8 +192,9 @@ 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: 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' },+ encoding: 'utf8', timeout: timeoutMs, 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=${Math.ceil(timeoutMs / 1000)}` },}, (error, stdout) => error ? reject(error) : resolve(stdout));}).catch((error: { code?: unknown; killed?: boolean }) => {asset.verification = error.code === 2@@ -154,7 +210,7 @@ export async function assessBackupRepository(}const stillClean = git(root, ['rev-parse', '--verify', 'HEAD']) === head&& git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']) === branch- && withoutPhysicalRootMetadata(git(root, ['status', '--porcelain'])).length === 0+ && !await worktreeDirty(root)&& git(root, ['remote', 'get-url', 'origin']) === origin&& repositoryFingerprint(root, origin, branch, head) === fingerprint;asset.verification = { state: remoteHead === head && stillClean && !dirty ? 'verified' : 'mismatch', checked_at: now.toISOString(), local_commit: head, remote_commit: remoteHead, repository_fingerprint: fingerprint };diff --git a/src/core/backup/status-file.ts b/src/core/backup/status-file.tsindex 848d36d8d0..3771cfaa87 100644--- a/src/core/backup/status-file.ts+++ b/src/core/backup/status-file.ts@@ -72,7 +72,7 @@ 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. */+ /** Why an `unavailable` probe failed: its full slot (`backup.remote_timeout_ms`, default 2 s) ran out, or git exited with an error. */cause?: 'timeout' | 'exit';checked_at?: string;local_commit?: string;@@ -91,6 +91,8 @@ export interface BackupTotals {/** Pages at risk on disk loss (db_only + undeclared DB-only signal). */pages_at_risk: number;configured_repos?: number;+ /** #6907: repositories whose remote probe ran out of time: their backup is unconfirmed, not known missing. */+ remote_timeouts?: number;}export interface BackupStatus {@@ -146,6 +148,11 @@ export function isVerifiedRecoverable(a: BackupAssetVerdict): boolean {return a.state === 'ok' && a.verification?.state === 'verified';}+/** #6907: a remote probe that ran out of its slot; nothing says the remote lacks the commits. */+export function isRemoteTimeout(a: BackupAssetVerdict): boolean {+ return a.verification?.state === 'unavailable' && a.verification.cause === 'timeout';+}+/*** True when this asset keeps the verdict in warn: an unverified repository,* or any asset counted in the no_remote / unpushed / failing totals.@@ -176,7 +183,7 @@ export function blockingAssetReasons(state: a.state,reason: a.state === 'no_remote' ? (a.configured_remote === true ? 'remote configured, nothing pushed' : 'no git remote'): a.state === 'unknown' ? (surface === 'local' || UNKNOWN_DETAIL_CODES.has(a.detail ?? '') ? a.detail ?? 'unknown' : 'unknown')- : a.state === 'ok' ? `remote not verified: ${a.verification?.state ?? 'not_checked'}`+ : a.state === 'ok' ? (isRemoteTimeout(a) ? 'remote check timed out' : `remote not verified: ${a.verification?.state ?? 'not_checked'}`): a.state,}));}diff --git a/src/core/config.ts b/src/core/config.tsindex f64a6ba6c5..1d5f9e15ea 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1311,6 +1311,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// 30 days; interval clamps to >=1 day at read time (backup/status-file.ts).'backup.check_enabled','backup.check_interval_days',+ 'backup.remote_timeout_ms', // #6907: DB plane, read by the backup coverage compute (backup/repository.ts); 500-30000, default 2000// DB-plane search-mode knobs: one row per key mode.ts reads (its// KNOB_CONFIG_KEY, hand-mirrored so this module stays import-light; pinned// equal by test/config-search-registry.test.ts). camelCase where the codediff --git a/test/e2e/s-6907-backup-check-bounds-postgres.test.ts b/test/e2e/s-6907-backup-check-bounds-postgres.test.tsnew file mode 100644index 0000000000..a1a87d8b6e--- /dev/null+++ b/test/e2e/s-6907-backup-check-bounds-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-6907-backup-check-bounds.test.ts'));diff --git a/test/pathological/s-6907-backup-check-bounds.test.ts b/test/pathological/s-6907-backup-check-bounds.test.tsnew file mode 100644index 0000000000..ed53e0103f--- /dev/null+++ b/test/pathological/s-6907-backup-check-bounds.test.ts@@ -0,0 +1,115 @@+/**+ * #6907 (GBRA-133): `gbrain backup check` on a large or slow repository.+ * - A dirty tree whose `git status --porcelain` passed 1 MiB overflowed the+ * probe's buffer (ENOBUFS) and read `unknown / probe_failed` instead of+ * `dirty`; the whole listing was read before anything was decided.+ * - The remote probe had a hard-coded two-second timeout, so a remote that+ * answers in three seconds could never be verified, and a timed-out probe+ * looked like any other unverified (not backed up) repository in totals and+ * in the human output.+ *+ * Protects: the dirtiness read stops at the first line that is not+ * physical-root metadata (a 1.3 MB listing reads dirty); the remote slot is+ * `backup.remote_timeout_ms` (env GBRAIN_BACKUP_REMOTE_TIMEOUT_MS wins),+ * clamped to 0.5-30 s, and scales the sweep budget; a timed-out probe is+ * counted in totals.remote_timeouts and named as a timeout, never as a missing+ * backup. Engine arms read the brain's config row: PGLite always, Postgres when+ * DATABASE_URL is set.+ */+import { afterAll, describe, expect, test } from 'bun:test';+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 { assessBackupRepository, resolveBackupRemoteTimeoutMs } from '../../src/core/backup/repository.ts';+import { computeBackupCoverage } from '../../src/core/backup/coverage.ts';+import { blockingAssetReasons } from '../../src/core/backup/status-file.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { pathologicalArms } from './harness.ts';++const dirs: string[] = [];+afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });+const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const tmp = (prefix: string) => { const dir = mkdtempSync(join(tmpdir(), prefix)); dirs.push(dir); return dir; };++/** A repository pushed to a local bare origin. */+function pushedRepo(): { root: string; bare: string } {+ const bare = tmp('gbrain-6907-bare-');+ git(bare, 'init', '-q', '--bare', '-b', 'main');+ const root = join(tmp('gbrain-6907-'), 'brain'); mkdirSync(root);+ git(root, 'init', '-q', '-b', 'main');+ writeFileSync(join(root, 'a.md'), '# a\n');+ git(root, 'add', '-A'); git(root, '-c', '[email protected]', '-c', 'user.name=Example', 'commit', '-qm', 'a');+ git(root, 'remote', 'add', 'origin', bare);+ git(root, 'push', '-q', '-u', 'origin', 'main');+ return { root, bare };+}++/** An HTTP smart remote for `bare` that answers after `delayMs`. */+function slowRemote(bare: string, delayMs: number) {+ return Bun.serve({+ port: 0,+ async fetch(request) {+ await Bun.sleep(delayMs);+ if (!new URL(request.url).pathname.endsWith('/info/refs')) return new Response('not found', { status: 404 });+ const refs = execFileSync('git', ['upload-pack', '--stateless-rpc', '--advertise-refs', bare]);+ return new Response(Buffer.concat([Buffer.from('001e# service=git-upload-pack\n0000'), refs]), { headers: { 'content-type': 'application/x-git-upload-pack-advertisement' } });+ },+ });+}++describe('#6907 backup check on a large or slow repository', () => {+ test('#6907 dirty: more than 1 MiB of porcelain output reads dirty, not probe_failed', async () => {+ const { root } = pushedRepo();+ const name = 'x'.repeat(90);+ for (let d = 0; d < 120; d++) {+ mkdirSync(join(root, `inbox-${d}`));+ for (let i = 0; i < 100; i++) writeFileSync(join(root, `inbox-${d}`, `${name}-${i}.md`), 'v1\n');+ }+ git(root, 'add', '-A'); git(root, '-c', '[email protected]', '-c', 'user.name=Example', 'commit', '-qm', 'bulk');+ git(root, 'push', '-q', 'origin', 'main');+ for (let d = 0; d < 120; d++) for (let i = 0; i < 100; i++) writeFileSync(join(root, `inbox-${d}`, `${name}-${i}.md`), 'v2\n');+ expect(execFileSync('git', ['-C', root, 'status', '--porcelain'], { maxBuffer: 64 << 20 }).length).toBeGreaterThan(1024 * 1024);+ const verdict = await assessBackupRepository(root, 'source_repo', 'example', new Date());+ expect({ state: verdict.state, detail: verdict.detail }).toEqual({ state: 'dirty', detail: 'uncommitted changes' });+ }, 120_000);++ test('#6907 timeout: backup.remote_timeout_ms is bounded and the environment wins', () => {+ expect(resolveBackupRemoteTimeoutMs(null, undefined)).toBe(2_000);+ expect(resolveBackupRemoteTimeoutMs('5000', undefined)).toBe(5_000);+ expect(resolveBackupRemoteTimeoutMs('5000', '7000')).toBe(7_000);+ expect(resolveBackupRemoteTimeoutMs('1', undefined)).toBe(500);+ expect(resolveBackupRemoteTimeoutMs('999999', undefined)).toBe(30_000);+ expect(resolveBackupRemoteTimeoutMs('soon', ' ')).toBe(2_000);+ });+});++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`#6907 remote timeout from the brain's config (${backend})`, () => {+ test('#6907 timeout: a 3 s remote is verified with backup.remote_timeout_ms 6000; at the default it times out and is reported as a timeout, not a missing backup', async () => {+ const home = tmp('gbrain-6907-home-');+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BACKUP_REMOTE_TIMEOUT_MS: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ const { root, bare } = pushedRepo();+ const server = slowRemote(bare, 3_000);+ try {+ git(root, 'remote', 'set-url', 'origin', `http://127.0.0.1:${server.port}/repo.git`);+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('backup-example','backup-example',$1,'{}')", [root]);+ const check = () => computeBackupCoverage(engine, { localGitProbes: true, verifyRemoteRefs: true });+ const asset = (status: Awaited<ReturnType<typeof check>>) => status.assets.find(a => a.id === 'backup-example')!;++ const timedOut = await check();+ expect(asset(timedOut).verification).toMatchObject({ state: 'unavailable', cause: 'timeout' });+ expect(timedOut.totals).toMatchObject({ remote_timeouts: 1, no_remote: 0, unpushed: 0, failing: 0 });+ expect(blockingAssetReasons(timedOut, 'aggregate').map(r => r.reason)).toEqual(['remote check timed out']);++ await engine.setConfig('backup.remote_timeout_ms', '6000');+ const verified = await check();+ expect(asset(verified)).toMatchObject({ state: 'ok', verification: { state: 'verified' } });+ expect(verified.totals).toMatchObject({ remote_timeouts: 0, recoverable_repos: 1 });+ } finally { server.stop(true); await close(); }+ });+ }, 120_000);+ });+}