Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(advisor): remote backup coverage judges cached evidence age (#6942)
time-attack4db084418ce1
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.mdindex bc7f4394d2..2679915b77 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). 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 and the advisor's remote collector use the aggregate cache only, read through `currentBackupEvidence`. 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/src/core/advisor/collect-backup-coverage.ts b/src/core/advisor/collect-backup-coverage.tsindex a96702c2c2..cd364c9778 100644--- a/src/core/advisor/collect-backup-coverage.ts+++ b/src/core/advisor/collect-backup-coverage.ts@@ -13,7 +13,7 @@*/import { getBackupStatus } from '../backup/coverage.ts';-import { backupCheckDisabled, backupNagGate, blockingAssetReasons, loadBackupStatus } from '../backup/status-file.ts';+import { backupCheckDisabled, backupNagGate, blockingAssetReasons, currentBackupEvidence, loadBackupStatus } from '../backup/status-file.ts';import type { AdvisorCollector, AdvisorFinding } from './types.ts';export const collectBackupCoverage: AdvisorCollector = {@@ -29,8 +29,10 @@ export const collectBackupCoverage: AdvisorCollector = {if (!local) {// Remote: cache-only read, aggregate wording, no nag writes (D4 — no// git subprocesses on a remote surface, ever).- const s = loadBackupStatus();- if (!s || s.overall !== 'warn') return [];+ const raw = loadBackupStatus();+ if (!raw) return [];+ const s = currentBackupEvidence(raw, ctx.now.getTime());+ if (s.overall !== 'warn') return [];// #5505: count the reasons that hold the warn, not only no_remote.const byReason = new Map<string, number>();for (const { reason } of blockingAssetReasons(s, 'aggregate')) byReason.set(reason, (byReason.get(reason) ?? 0) + 1);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 71d3aae633..d5d83a49ef 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -906,6 +906,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },// Fix wave 20 lane 3.{ since: '0.60.307.0', text: 'The bundled `gbrain-base-v2` schema pack (the `init` default, also inherited by `company-brain`) is now version 1.5.0 and declares the `code` page type the code importer stamps and the `extract_receipt` page type the extract receipt writer stamps under `extracts/` (#6818), so neither makes doctor `schema_pack_consistency` warn `page_type_undeclared` and `unify-types` no longer retypes those pages to `note`. Existing pages keep their type; no data changes. The active pack identity reads `[email protected]+<hash>`.' },+ { since: '0.60.307.0', text: 'The `advisor` MCP operation now judges the cached backup verdict the way the doctor does: a remote readback older than one hour, a future-dated cache or a degraded compute reports the `backup_coverage_aggregate` warning instead of no finding. It still reads the cache only and names reason counts, never source ids.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/test/advisor-backup-coverage.serial.test.ts b/test/advisor-backup-coverage.serial.test.tsindex 6681a2c924..d5c4da69e6 100644--- a/test/advisor-backup-coverage.serial.test.ts+++ b/test/advisor-backup-coverage.serial.test.ts@@ -301,7 +301,7 @@ describe('collectBackupCoverage remote (remote:true)', () => {warnCache({overall: 'ok',totals: { assets: 1, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 1, pages_at_risk: 0 },- assets: [{ kind: 'source_repo', id: 'fine-src', state: 'ok' }],+ assets: [{ kind: 'source_repo', id: 'fine-src', state: 'ok', verification: { state: 'verified', checked_at: '2026-06-01T00:00:00Z' } }],}),);const { engine } = makeEngine();@@ -319,6 +319,62 @@ describe('collectBackupCoverage remote (remote:true)', () => {});});+// ── #6942: the remote branch reads the cache through currentBackupEvidence ──++describe('collectBackupCoverage remote — cached evidence age (#6942)', () => {+ const NOW = Date.parse('2026-06-01T00:00:00Z');+ const iso = (ms: number) => new Date(ms).toISOString();+ const hour = 60 * 60 * 1000;+ function verifiedOkCache(verifiedAt: number, over: Partial<BackupStatus> = {}): BackupStatus {+ return warnCache({+ overall: 'ok',+ checked_at: iso(verifiedAt),+ totals: { assets: 1, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 1, pages_at_risk: 0 },+ assets: [{+ kind: 'source_repo',+ id: 'xylophone-secret-source-991',+ state: 'ok',+ verification: { state: 'verified', checked_at: iso(verifiedAt) },+ }],+ ...over,+ });+ }+ const noEngine = { executeRaw: async () => { throw new Error('remote collect must not query the engine'); } } as unknown as AdvisorContext['engine'];++ test('fresh verified proof (10 minutes old) → zero findings', async () => {+ saveBackupStatus(verifiedOkCache(NOW - 10 * 60 * 1000));+ expect(await collectBackupCoverage.collect(ctx(noEngine, { remote: true }))).toEqual([]);+ expect(existsSync(nagPath)).toBe(false);+ });++ test('expired verified proof (2 hours old) under a cached ok → aggregate warn naming the stale remote check', async () => {+ saveBackupStatus(verifiedOkCache(NOW - 2 * hour));+ const findings = await collectBackupCoverage.collect(ctx(noEngine, { remote: true }));+ expect(findings).toHaveLength(1);+ expect(findings[0]?.id).toBe('backup_coverage_aggregate');+ expect(findings[0]?.severity).toBe('warn');+ expect(findings[0]?.title).toStartWith('1 of 1 knowledge assets lack verified recovery (1 remote not verified: stale)');+ expect(JSON.stringify(findings)).not.toContain('xylophone-secret-source-991');+ expect(existsSync(nagPath)).toBe(false);+ });++ test('future-dated cache and proof → aggregate warn, never trusted as ok', async () => {+ saveBackupStatus(verifiedOkCache(NOW + 48 * hour));+ const findings = await collectBackupCoverage.collect(ctx(noEngine, { remote: true }));+ expect(findings).toHaveLength(1);+ expect(findings[0]?.id).toBe('backup_coverage_aggregate');+ expect(findings[0]?.title).toContain('remote not verified: stale');+ });++ test('degraded cache with a fresh proof → aggregate warn', async () => {+ saveBackupStatus(verifiedOkCache(NOW - 10 * 60 * 1000, { degraded: true }));+ const findings = await collectBackupCoverage.collect(ctx(noEngine, { remote: true }));+ expect(findings).toHaveLength(1);+ expect(findings[0]?.id).toBe('backup_coverage_aggregate');+ expect(findings[0]?.severity).toBe('warn');+ });+});+// ── 4. Nag ceiling — 3 surfaced batches per verdict, then quiet ──────────────describe('collectBackupCoverage nag ceiling', () => {