Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): connector sources are not repos; warnings name the real reasons (#5531, #5505)
garrytan21b3dfd6c81a
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 7d7065193f..e911c04e6a 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -26,8 +26,8 @@- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit AND clears 3.5 bits/char. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list: a repetitive tail against 64 short claimed values meant millions of candidate objects and hundreds of MB of RSS for 64 findings, ahead of message truncation) (never an alternation RegExp — O(text × Σ|values|) on prefix-sharing values; never over emitted tokens, so a value spelling a pattern name cannot nest). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts under the embed-skip threshold. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`).- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch. `formatSensitivityDrop(drop, workspaceRoot)` renders the one content-free stderr line `gbrain compile-context` prints per dropped entry: reason `sensitivity_scan`, the pattern family, the fingerprint and the absolute `.gbrain-scan-allow` path, never the value (`test/sensitivity-scan.test.ts`).-- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v1`; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.-- `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. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.+- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v2`, which includes the `connector` asset kind; a cache with any other schema reads as absent and is recomputed; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.+- `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`.- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → 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). 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. Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`.- `src/core/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.mdindex be23e929b7..e548e3523f 100644--- a/docs/operations/backup-check.md+++ b/docs/operations/backup-check.md@@ -11,6 +11,7 @@ proof that a whole brain could be restored.|---|---|---|| Source repos (every non-archived source with a `local_path`) | Local Git discovery, deduped by root and capped at 500 roots/run; trusted local read-only `git ls-remote` verifies clean HEAD against the remote | No configured origin, dirty/unpushed work, missing/mismatched remote HEAD, stale/unknown evidence, or failed push without newer matching readback cannot count as verified recovery. || Bootstrap workspace (skills/, memory/, brain/, identity) | file plane: the install receipt's `repo_url` + the per-root push-status files | receipt without `repo_url` → warn; a failing background push → flagged row only (the push-failure banner owns that alarm) |+| Google / GitHub connector sources | persistence mode and worktree binding | none on its own: a managed unbound source (`connector_database`) and an unmanaged source whose directory is missing or not a Git repo are `connector` info rows. A bound connector, or one whose directory is a Git repo, is checked as a source repo. || DB-only brain (pages exist, nothing git-backed) | page count + absence of any git-backed asset | warn on PGLite (local disk loss risks these pages); info on Postgres (database placement and external backup are unverified) || `db_only` storage-tier pages | `gbrain.yml` per source | info row — dump with `gbrain export --dir <backup-dir>` to somewhere OUTSIDE the gitignored dirs (`--restore-only` is the wrong direction for a backup) || Harness-native skill dirs (e.g. the agent's installed skills) | skillpack bridge state | info only — these are installed COPIES; the originals live in repos |@@ -190,6 +191,15 @@ source id. Full per-asset detail (which repo, which fix) is local-only:- Unpushed workspace work: `gbrain sources push --path <workspace>`.- db_only pages: `gbrain export --dir <backup-dir>` (store the dump outsidethe gitignored dirs — another disk, another repo, anywhere durable).+- A dirty source repo (uncommitted changes): `gbrain sources push <source-id>`+ (secret-scanned commit and push), or discard the changes, then run+ `gbrain backup check`. Remote evidence is only read for a clean tree.+- Google or GitHub connector sources without a Git-backed directory (managed+ and unbound, or unmanaged with a missing or non-Git directory): they appear+ as `connector` info rows and do not keep the check in warn. Their pages come+ from the provider API, so recovery is `gbrain sync --source <id> --full`,+ within the source's configured history window. A bound connector, or one+ whose directory is a Git repo, follows the source-repo recipes above.## Recovery drill (prove the answer is real)diff --git a/src/commands/backup.ts b/src/commands/backup.tsindex 2f6f94576a..1a1207ffbe 100644--- a/src/commands/backup.ts+++ b/src/commands/backup.ts@@ -23,8 +23,10 @@ import {backupCheckDisabled,backupNagGate,isBackupStatusStale,+ isVerifiedRecoverable,loadBackupStatus,currentBackupEvidence,+ type BackupAssetVerdict,type BackupStatus,} from '../core/backup/status-file.ts';@@ -68,20 +70,36 @@ function recoveryStatement(s: BackupStatus): string {return `${repoPart}; ${riskPart}. ${s.recovery_scope ?? 'Git is not a full database backup.'}`;}+/**+ * #5505: coverage leaves dirty trees and unverified remotes without fix_argv+ * (no single mechanical fix at compute time); the CLI still names the command+ * that clears each one. A deduped root lists several source ids; any of them+ * pushes the shared repository.+ */+function suggestedFix(a: BackupAssetVerdict): string[] | null {+ if (a.fix_argv && a.fix_argv.length > 0) return a.fix_argv;+ if (a.state === 'dirty') {+ return a.kind === 'bootstrap_workspace' ? ['gbrain', 'sources', 'push', '--path', a.id] : ['gbrain', 'sources', 'push', a.id.split(', ')[0]];+ }+ if (a.state === 'ok' && !isVerifiedRecoverable(a)) return ['gbrain', 'backup', 'check'];+ return null;+}+function renderHuman(s: BackupStatus, out: (line: string) => void): void {const age = backupCacheAge(s);out(`backup coverage — ${s.overall === 'warn' ? 'WARN' : 'ok'} (checked ${age}, by ${s.computed_by})`);for (const a of s.assets) {- const mark = a.state === 'ok' && a.verification?.state === 'verified' ? '✓' : a.state === 'no_remote' ? '✗' : a.state === 'info' ? '·' : '⚠';+ 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}` : ''}`);- if (a.fix_argv && a.fix_argv.length > 0) out(` fix: ${a.fix_argv.join(' ')}`);+ const fix = suggestedFix(a);+ if (fix) out(` fix: ${fix.join(' ')}`);}out(recoveryStatement(s));if (s.degraded) {out('note: the brain database was unreadable during this check — verdict is partial (not cached)');}if (s.overall === 'warn') {- out('Fix the ✗ rows above, then run: gbrain backup check');+ out('Fix the ✗ and ⚠ rows above, then run: gbrain backup check');}}diff --git a/src/commands/doctor/checks/backup-coverage.ts b/src/commands/doctor/checks/backup-coverage.tsindex 09c975cc46..f212aee19d 100644--- a/src/commands/doctor/checks/backup-coverage.ts+++ b/src/commands/doctor/checks/backup-coverage.ts@@ -10,13 +10,31 @@ import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { getBackupStatus } from '../../../core/backup/coverage.ts';import {+ blockingAssetReasons,backupCacheAge,backupCheckDisabled,+ isBackupStatusStale,loadBackupStatus,currentBackupEvidence,type BackupStatus,} from '../../../core/backup/status-file.ts';+/** Why a verdict warns beyond its assets: a degraded compute or a stale cache. */+function verdictCaveats(s: BackupStatus, now?: number): string[] {+ return [+ ...(s.degraded ? ['the database was unreadable during the check'] : []),+ ...(isBackupStatusStale(s, now) ? ['the verdict is older than the check interval'] : []),+ ];+}++/** Lead with the assets when any block recovery; otherwise the caveats are the cause. */+function warnLead(assetClause: string | null, caveats: string[]): string {+ if (assetClause) return `${assetClause}${caveats.length > 0 ? ` Also: ${caveats.join('; ')}.` : ''}`;+ return `Backup verdict is not current: ${caveats.length > 0 ? caveats.join('; ') : 'its check time could not be verified'}.`;+}++const LISTED_ASSET_CAP = 5;+function toCheck(s: BackupStatus, now?: number): Check {const details = {totals: s.totals,@@ -27,15 +45,15 @@ function toCheck(s: BackupStatus, now?: number): Check {degraded: s.degraded === true,};if (s.overall === 'warn') {- const ids = s.assets- .filter((a) => a.state === 'no_remote')- .map((a) => a.id)- .join(', ');+ const unverified = blockingAssetReasons(s, 'local');+ const listed = unverified.slice(0, LISTED_ASSET_CAP).map((a) => `${a.id} (${a.reason})`).join(', ');+ const more = unverified.length > LISTED_ASSET_CAP ? `, and ${unverified.length - LISTED_ASSET_CAP} more` : '';+ const assetClause = unverified.length > 0 ? `${unverified.length} knowledge asset(s) lack verified recovery: ${listed}${more}.` : null;return {name: 'backup_coverage',status: 'warn',message:- `${s.totals.no_remote} knowledge asset(s) have no git remote: ${ids}. Current recovery is not verified for all repositories. ` ++ `${warnLead(assetClause, verdictCaveats(s, now))} Current recovery is not verified for all repositories. ` +'Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).',details,};@@ -81,12 +99,20 @@ export async function checkBackupCoverage(degraded: cached.degraded === true,note: 'cache-only (remote surface never probes git; aggregate counts only)',};+ // Aggregate-only: reason counts, never asset ids.+ const byReason = new Map<string, number>();+ for (const { reason } of blockingAssetReasons(cached, 'aggregate')) byReason.set(reason, (byReason.get(reason) ?? 0) + 1);+ const unverifiedCount = [...byReason.values()].reduce((a, b) => a + b, 0);+ const reasons = [...byReason].map(([reason, n]) => `${n} ${reason}`).join(', ');+ const assetClause = unverifiedCount > 0+ ? `${unverifiedCount} of ${cached.totals.assets} knowledge asset(s) lack verified recovery (${reasons}).`+ : null;return cached.overall === 'warn'? {name: 'backup_coverage',status: 'warn',message:- `${cached.totals.no_remote} of ${cached.totals.assets} knowledge asset(s) have no git remote; current recovery is not verified for all repositories — ` ++ `${warnLead(assetClause, verdictCaveats(cached, opts.now?.getTime()))} Current recovery is not verified for all repositories — ` +'run `gbrain backup status` on the brain host for the per-asset detail and fix commands.',details,}diff --git a/src/core/advisor/collect-backup-coverage.ts b/src/core/advisor/collect-backup-coverage.tsindex 21051fcce5..a96702c2c2 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, loadBackupStatus } from '../backup/status-file.ts';+import { backupCheckDisabled, backupNagGate, blockingAssetReasons, loadBackupStatus } from '../backup/status-file.ts';import type { AdvisorCollector, AdvisorFinding } from './types.ts';export const collectBackupCoverage: AdvisorCollector = {@@ -31,10 +31,18 @@ export const collectBackupCoverage: AdvisorCollector = {// git subprocesses on a remote surface, ever).const s = loadBackupStatus();if (!s || 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);+ const blocked = [...byReason.values()].reduce((a, b) => a + b, 0);+ const reasons = [...byReason].map(([reason, n]) => `${n} ${reason}`).join(', ');findings.push({id: 'backup_coverage_aggregate',severity: 'warn',- title: `${s.totals.no_remote} of ${s.totals.assets} knowledge assets have no git remote (local-only) — run \`gbrain backup status\` on the brain host for fix commands.`,+ title: (blocked > 0+ ? `${blocked} of ${s.totals.assets} knowledge assets lack verified recovery (${reasons})`+ : 'The cached backup verdict is not current') ++ '. Run `gbrain backup status` on the brain host for fix commands.',fix: { command_argv: null },collector: 'backup-coverage',ask_user: true,@@ -93,6 +101,20 @@ export const collectBackupCoverage: AdvisorCollector = {});}}+ // #5505: dirty trees, non-Git paths and unverified remotes hold the warn+ // too; name them instead of leaving the warn with no finding.+ const otherBlocked = blockingAssetReasons(s, 'local').filter((a) => a.state !== 'no_remote' && a.state !== 'unpushed');+ if (otherBlocked.length > 0) {+ findings.push({+ id: 'backup_recovery_unverified',+ severity: 'warn',+ title: `${otherBlocked.length} knowledge asset(s) lack verified recovery: ${otherBlocked.map((a) => `${a.id} (${a.reason})`).join(', ')}.`,+ detail: 'run gbrain backup status for the per-asset detail and fix commands',+ fix: { command_argv: null },+ collector: 'backup-coverage',+ ask_user: true,+ });+ }const unpushed = s.assets.filter((a) => a.state === 'unpushed');if (unpushed.length > 0) {findings.push({diff --git a/src/core/backup/coverage.ts b/src/core/backup/coverage.tsindex 7b04471496..2557591880 100644--- a/src/core/backup/coverage.ts+++ b/src/core/backup/coverage.ts@@ -18,7 +18,8 @@ import { existsSync } from 'node:fs';import { VERSION } from '../../version.ts';import type { BrainEngine } from '../engine.ts';-import { loadAllSources } from '../sources-load.ts';+import { loadAllSources, parseSourceConfig, type SourceRow } from '../sources-load.ts';+import { connectorAuthorities, type ConnectorAuthority } from '../persistence/connector-authority.ts';import { discoverGitRoot } from '../sync-git.ts';import { realpathOrResolve } from '../path-confine.ts';import { resolveBrainId } from '../brain-resolver.ts';@@ -35,6 +36,7 @@ import {loadBackupStatus,saveBackupStatus,currentBackupEvidence,+ isVerifiedRecoverable,BACKUP_VERIFICATION_MAX_AGE_MS,BACKUP_RECOVERY_SCOPE,type BackupAssetVerdict,@@ -64,6 +66,37 @@ function pushAsset(assets: BackupAssetVerdict[], a: BackupAssetVerdict): void {assets.push(a);}+/**+ * #5505: an API connector's pages come from the provider, not from Git. A+ * connector_database source (managed, unbound) has no canonical files at all;+ * an unmanaged connector's non-Git (or missing) directory is a Markdown cache.+ * Both are recovered by a full re-sync from the provider, so they are an info+ * row and never an unrecoverable repository that keeps the check in warn.+ * `gbrain export` is not offered: `gbrain sync --source <id>` on a Google or+ * GitHub source runs the connector sync, which rebuilds pages from the provider+ * and never reads a Markdown dump, so an export is an archive for that source,+ * not a restore path.+ */+function connectorAsset(id: string, connectorDatabase: boolean): BackupAssetVerdict {+ return {+ kind: 'connector',+ id,+ state: 'info',+ detail: (connectorDatabase+ ? 'API connector source (connector_database): pages are imported from the provider API straight into the database. '+ : 'API connector source: its local directory only caches the provider API as Markdown and is not a git repository. ') ++ "Recover by re-syncing from the provider (within the source's configured history window).",+ fix_argv: ['gbrain', 'sync', '--source', id, '--full'],+ };+}++/** A bound connector's root must be a canonical checkout, so it stays a repo verdict. */+function notARepoAsset(row: SourceRow, authority: ConnectorAuthority | undefined): BackupAssetVerdict {+ return authority === 'unmanaged'+ ? connectorAsset(row.id, false)+ : { kind: 'source_repo', id: row.id, state: 'unknown', detail: 'not_a_git_repo', fix_argv: null };+}+function yieldLoop(): Promise<void> {return new Promise((r) => setTimeout(r, 0));}@@ -142,6 +175,10 @@ export async function computeBackupCoverage(let degraded = false;try {const rows = await loadAllSources(engine);+ const authorities = await connectorAuthorities(+ engine,+ rows.filter((r) => !r.archived).map((r) => ({ id: r.id, kind: parseSourceConfig(r.config).kind })),+ );const byRoot = new Map<string, { ids: string[]; dbOnly: boolean }>();let skippedOverCap = 0;// Root discovery is itself a git subprocess — memoize per local_path, count@@ -151,12 +188,17 @@ export async function computeBackupCoverage(let discoveries = 0;for (const row of rows) {if (row.archived) continue;+ if (authorities.get(row.id) === 'connector_database') {+ pushAsset(assets, connectorAsset(row.id, true)); // local_path, if any, is not canonical+ continue;+ }if (!row.local_path) continue;if (!existsSync(row.local_path)) {// The most disk-loss-adjacent state of all: a registered path that is// GONE. Surface it (unknown — it may live on another machine or have- // moved) instead of silently skipping.- pushAsset(assets, {+ // moved) instead of silently skipping. An unmanaged connector's cache+ // is rebuilt by its next sweep, so it takes the connector verdict.+ pushAsset(assets, authorities.get(row.id) === 'unmanaged' ? connectorAsset(row.id, false) : {kind: 'source_repo',id: row.id,state: 'unknown',@@ -172,7 +214,7 @@ export async function computeBackupCoverage(const memo = rootByPath.get(row.local_path)!;if (memo === null) {// Every source at a known non-repo path gets its own asset row.- pushAsset(assets, { kind: 'source_repo', id: row.id, state: 'unknown', detail: 'not_a_git_repo', fix_argv: null });+ pushAsset(assets, notARepoAsset(row, authorities.get(row.id)));continue;}root = memo;@@ -188,13 +230,7 @@ export async function computeBackupCoverage(rootByPath.set(row.local_path, root);} catch {rootByPath.set(row.local_path, null);- pushAsset(assets, {- kind: 'source_repo',- id: row.id,- state: 'unknown',- detail: 'not_a_git_repo',- fix_argv: null,- });+ pushAsset(assets, notARepoAsset(row, authorities.get(row.id)));continue;}}@@ -329,7 +365,7 @@ export async function computeBackupCoverage(unpushed: assets.filter((a) => a.state === 'unpushed').length,failing: assets.filter((a) => a.state === 'failing').length,configured_repos: assets.filter(a => a.configured_remote === true).length,- recoverable_repos: assets.filter(a => a.state === 'ok' && a.verification?.state === 'verified').length,+ recoverable_repos: assets.filter(isVerifiedRecoverable).length,pages_at_risk: pagesAtRisk,};diff --git a/src/core/backup/status-file.ts b/src/core/backup/status-file.tsindex 29f5f03c35..d1a9d33135 100644--- a/src/core/backup/status-file.ts+++ b/src/core/backup/status-file.ts@@ -48,10 +48,11 @@ import {// ── Verdict types ───────────────────────────────────────────────────────────-export const BACKUP_STATUS_SCHEMA_VERSION = 'gbrain-backup-status-v1' as const;+/** v2: API connector sources became their own `connector` asset kind; a v1 cache reads as absent and is recomputed. */+export const BACKUP_STATUS_SCHEMA_VERSION = 'gbrain-backup-status-v2' as const;export const BACKUP_NAG_SCHEMA_VERSION = 'gbrain-backup-nag-v1' as const;-export type BackupAssetKind = 'source_repo' | 'bootstrap_workspace' | 'harness_skills' | 'db_only' | 'db_content';+export type BackupAssetKind = 'source_repo' | 'bootstrap_workspace' | 'harness_skills' | 'db_only' | 'db_content' | 'connector';export type BackupAssetState = 'ok' | 'no_remote' | 'unpushed' | 'dirty' | 'failing' | 'info' | 'unknown';export type BackupComputedBy = 'cli' | 'advisor' | 'doctor' | 'serve' | 'spawn' | 'sync';@@ -113,6 +114,51 @@ export interface BackupStatus {export const BACKUP_VERIFICATION_MAX_AGE_MS = 60 * 60 * 1000;export const BACKUP_RECOVERY_SCOPE = 'Git evidence covers committed repository files only; not a full database backup. DB-only pages, facts, configuration and credentials need a separate backup and restore drill.';+/** Repository-shaped assets: the ones whose recovery is verified against a remote. */+export function isRepoAsset(a: BackupAssetVerdict): boolean {+ return a.kind === 'source_repo' || a.kind === 'bootstrap_workspace';+}++/** A clean asset whose HEAD matched the remote within the evidence window. */+export function isVerifiedRecoverable(a: BackupAssetVerdict): boolean {+ return a.state === 'ok' && a.verification?.state === 'verified';+}++/**+ * True when this asset keeps the verdict in warn: an unverified repository,+ * or any asset counted in the no_remote / unpushed / failing totals.+ * currentBackupEvidence and the doctor message both read this.+ */+export function assetBlocksRecovery(a: BackupAssetVerdict): boolean {+ return isRepoAsset(a) ? !isVerifiedRecoverable(a) : a.state === 'no_remote' || a.state === 'unpushed' || a.state === 'failing';+}++/**+ * The fixed `unknown` detail codes coverage.ts and repository.ts write. The+ * aggregate surface echoes only these, so a future free-text detail cannot+ * carry a path or a branch name to a remote reader.+ */+const UNKNOWN_DETAIL_CODES = new Set(['not_a_git_repo', 'probes_skipped', 'probe_cap', 'probe_failed', 'local_path not found on this machine']);++/**+ * #5505: one entry per asset that keeps the verdict in warn, with the reason+ * that holds it there, so warnings name the real cause instead of assuming+ * "no git remote". `aggregate` callers must render the reasons only, never ids.+ */+export function blockingAssetReasons(+ s: BackupStatus,+ surface: 'local' | 'aggregate',+): Array<{ id: string; state: BackupAssetState; reason: string }> {+ return s.assets.filter(assetBlocksRecovery).map((a) => ({+ id: a.id,+ 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,+ }));+}+export function currentBackupEvidence(s: BackupStatus, now = Date.now()): BackupStatus {const statusAge = now - Date.parse(s.checked_at);const stale = isBackupStatusStale(s, now) || !Number.isFinite(statusAge) || statusAge < 0;@@ -122,8 +168,8 @@ export function currentBackupEvidence(s: BackupStatus, now = Date.now()): Backupif (!s.degraded && Number.isFinite(age) && age >= 0 && age <= BACKUP_VERIFICATION_MAX_AGE_MS && !stale) return a;return { ...a, verification: { ...a.verification, state: 'stale' as const } };});- const repos = assets.filter(a => a.kind === 'source_repo' || a.kind === 'bootstrap_workspace');- const recoverable = repos.filter(a => a.state === 'ok' && a.verification?.state === 'verified').length;+ const repos = assets.filter(isRepoAsset);+ const recoverable = repos.filter(isVerifiedRecoverable).length;return {...s,assets,diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1a7b4cdce1..4418875251 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -21,7 +21,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'auth': ['--admin-intent', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--no-pull', '--path', '--probe', '--profile', '--redirect-uri', '--repair', '--replace', '--request-id', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],- 'backup': ['--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--mode', '--output', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout'],+ 'backup': ['--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--access', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],diff --git a/test/advisor-backup-coverage.serial.test.ts b/test/advisor-backup-coverage.serial.test.tsindex 002469043b..6681a2c924 100644--- a/test/advisor-backup-coverage.serial.test.ts+++ b/test/advisor-backup-coverage.serial.test.ts@@ -180,6 +180,18 @@ function warnCache(over: Partial<BackupStatus> = {}): BackupStatus {// ── 1. Local ctx (remote:false) — per-asset findings ─────────────────────────describe('collectBackupCoverage local (remote:false)', () => {+ test('#5505: a non-Git source path holds the warn → one backup_recovery_unverified finding naming it', async () => {+ const plain = join(tmp, 'plain-dir');+ mkdirSync(plain, { recursive: true });+ const { engine } = makeEngine({ sources: [{ id: 'plain-src', local_path: plain }], pageCount: 0 });++ const findings = await collectBackupCoverage.collect(ctx(engine));++ const f = findings.find((x) => x.id === 'backup_recovery_unverified');+ expect(f?.severity).toBe('warn');+ expect(f?.title).toBe('1 knowledge asset(s) lack verified recovery: plain-src (not_a_git_repo).');+ });+test('no-remote source repo → backup_source_no_remote:<id> warn with the recipe; unpushed repo → backup_unpushed_work info', async () => {const noRemote = makeNoRemoteRepo('zebra-repo');const unpushed = makeUnpushedRepo('yak-repo');@@ -268,6 +280,22 @@ describe('collectBackupCoverage remote (remote:true)', () => {expect(existsSync(nagPath)).toBe(false);});+ test('#5505: warn cache held only by a dirty repo → reason counts, never "0 of N ... no git remote"', async () => {+ saveBackupStatus(+ warnCache({+ totals: { assets: 2, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 0, pages_at_risk: 0 },+ assets: [{ kind: 'source_repo', id: 'xylophone-secret-source-991', state: 'dirty', detail: 'uncommitted changes', fix_argv: null }],+ }),+ );+ const engine = { executeRaw: async () => { throw new Error('remote collect must not query the engine'); } } as unknown as AdvisorContext['engine'];++ const [f] = await collectBackupCoverage.collect(ctx(engine, { remote: true }));++ expect(f?.title).toStartWith('1 of 2 knowledge assets lack verified recovery (1 dirty)');+ expect(f?.title).not.toContain('no git remote');+ expect(JSON.stringify(f)).not.toContain('xylophone-secret-source-991');+ });+test('ok cache → zero findings and still no nag write', async () => {saveBackupStatus(warnCache({diff --git a/test/backup-cli.serial.test.ts b/test/backup-cli.serial.test.tsindex eaba96e15b..42612273c2 100644--- a/test/backup-cli.serial.test.ts+++ b/test/backup-cli.serial.test.ts@@ -378,6 +378,30 @@ describe('runBackupCli — disabled', () => {});});+// #5505: rows coverage leaves without fix_argv still get a command.+describe('runBackupCli status: fix commands for dirty and unverified rows', () => {+ test('dirty repo, deduped dirty root, dirty workspace and unverified repo each name a fix', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0'; // cache-only render, no compute+ saveBackupStatus({+ ...mkStatus('warn', new Date(Date.now() - 60_000).toISOString()),+ assets: [+ { kind: 'source_repo', id: 'dirty-src', state: 'dirty', detail: 'uncommitted changes', fix_argv: null },+ { kind: 'source_repo', id: 'root-a, root-b', state: 'dirty', detail: 'uncommitted changes', fix_argv: null },+ { kind: 'bootstrap_workspace', id: '/ws/example', state: 'dirty', detail: 'uncommitted changes', fix_argv: null },+ { kind: 'source_repo', id: 'unverified-src', state: 'ok', configured_remote: true, fix_argv: null },+ ],+ });++ const r = await run(['status'], thunkFor(stubEngine({})).connect);++ expect(r.stdout).toContain('fix: gbrain sources push dirty-src');+ expect(r.stdout).toContain('fix: gbrain sources push root-a\n');+ expect(r.stdout).toContain('fix: gbrain sources push --path /ws/example');+ expect(r.stdout).toContain('fix: gbrain backup check');+ expect(r.stdout).toContain('Fix the ✗ and ⚠ rows above, then run: gbrain backup check');+ });+});+// ── --json payload ───────────────────────────────────────────────────────────describe('runBackupCli --json', () => {diff --git a/test/backup-coverage.serial.test.ts b/test/backup-coverage.serial.test.tsindex 37012916b6..ed112e409c 100644--- a/test/backup-coverage.serial.test.ts+++ b/test/backup-coverage.serial.test.ts@@ -122,11 +122,19 @@ function stubEngine(opts: {sources?: unknown[];pages?: number;onCall?: () => void;+ /** persistence_brain.enabled (managed persistence activated). */+ managed?: boolean;+ /** Source ids that have a persistence_source_bindings row. */+ bound?: string[];} = {}): BrainEngine {return {kind: opts.kind ?? 'pglite',- executeRaw: async (sql: string) => {+ executeRaw: async (sql: string, params: unknown[] = []) => {opts.onCall?.();+ if (sql.includes('FROM persistence_brain')) return [{ enabled: opts.managed === true }];+ if (sql.includes('FROM persistence_source_bindings')) {+ return (opts.bound ?? []).includes(String(params[0])) ? [{ source_id: params[0], worktree_id: 'wt-example' }] : [];+ }if (sql.includes('FROM pages')) return [{ n: opts.pages ?? 0 }];if (sql.includes('FROM sources')) return opts.sources ?? [];return [];@@ -680,6 +688,98 @@ describe('computeBackupCoverage — dirty tree, shared git roots, non-repo paths});});+// API connector sources (Google / GitHub)++describe('computeBackupCoverage: API connector sources', () => {+ const connectorRow = (id: string) => ({+ kind: 'connector',+ id,+ state: 'info',+ fix_argv: ['gbrain', 'sync', '--source', id, '--full'],+ });++ function plainCache(name: string): string {+ const dir = join(tmp, name);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'thread.md'), 'cached connector page');+ return dir;+ }++ test.each([+ { label: 'managed + unbound Google source (connector_database)', kind: 'google', managed: true, path: 'cache' },+ { label: 'managed + unbound GitHub source whose cache dir is gone', kind: 'github', managed: true, path: 'missing' },+ { label: 'unmanaged Google source with a plain cache dir', kind: 'google', managed: false, path: 'cache' },+ { label: 'unmanaged Google source whose cache dir is gone', kind: 'google', managed: false, path: 'missing' },+ ] as const)('$label → connector info asset, not an unrecoverable repo', async ({ kind, managed, path }) => {+ const localPath = path === 'cache' ? plainCache('conn-cache') : join(tmp, 'gone-cache');+ const engine = stubEngine({ managed, sources: [srcRow('conn-src', localPath, { config: { kind } })] });++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ expect(s.assets.filter((a) => a.kind === 'source_repo')).toEqual([]);+ const asset = s.assets.find((a) => a.id === 'conn-src');+ expect(asset).toMatchObject(connectorRow('conn-src'));+ expect(asset?.detail).toContain('provider API');+ expect(s.overall).toBe('ok');+ });++ test('managed + BOUND connector keeps the canonical-root Git contract (plain dir → not_a_git_repo)', async () => {+ const localPath = plainCache('bound-cache');+ const engine = stubEngine({+ managed: true,+ bound: ['conn-bound'],+ sources: [srcRow('conn-bound', localPath, { config: { kind: 'google' } })],+ });++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ expect(s.assets.find((a) => a.id === 'conn-bound')).toMatchObject({ kind: 'source_repo', state: 'unknown', detail: 'not_a_git_repo' });+ expect(s.overall).toBe('warn');+ });++ test.each([+ { engine: 'pglite', state: 'no_remote', overall: 'warn' },+ { engine: 'postgres', state: 'info', overall: 'ok' },+ ] as const)('connector-only $engine brain with pages → db_content $state (no git-backed asset)', async ({ engine: kind, state, overall }) => {+ const engine = stubEngine({ kind, managed: true, pages: 7, sources: [srcRow('conn-src', null, { config: { kind: 'google' } })] });++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ expect(s.assets.find((a) => a.id === 'conn-src')).toMatchObject({ kind: 'connector', state: 'info' });+ expect(s.assets.find((a) => a.kind === 'db_content')).toMatchObject({ state });+ expect(s.overall).toBe(overall);+ });++ test('a failing persistence read degrades the verdict instead of exempting the connector', async () => {+ const engine = {+ kind: 'pglite',+ executeRaw: async (sql: string) => {+ if (sql.includes('FROM persistence_brain')) throw new Error('persistence table unreadable');+ if (sql.includes('FROM pages')) return [{ n: 1 }];+ if (sql.includes('FROM sources')) return [srcRow('conn-src', join(tmp, 'x'), { config: { kind: 'google' } })];+ return [];+ },+ } as unknown as BrainEngine;++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ expect(s.degraded).toBe(true);+ expect(s.overall).toBe('warn');+ expect(s.assets.find((a) => a.id === 'conn-src')).toBeUndefined();+ });++ test('unmanaged connector whose local_path IS a git repo is probed like any repo', async () => {+ const repo = join(tmp, 'gh-repo');+ initRepo(repo);+ commitFile(repo, 'a.md', 'x', 'init');+ const engine = stubEngine({ sources: [srcRow('gh-src', repo, { config: { kind: 'github' } })] });++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ expect(s.assets.find((a) => a.id === 'gh-src')).toMatchObject({ kind: 'source_repo', state: 'no_remote' });+ });+});+// ── Bootstrap workspace: failing push status ─────────────────────────────────describe('computeBackupCoverage — bootstrap workspace failing push', () => {diff --git a/test/doctor-backup-coverage.serial.test.ts b/test/doctor-backup-coverage.serial.test.tsindex 4314320583..cebb7a9a5e 100644--- a/test/doctor-backup-coverage.serial.test.ts+++ b/test/doctor-backup-coverage.serial.test.ts@@ -175,6 +175,56 @@ describe('checkBackupCoverage — localOnly (trusted, probes run)', () => {expect(details.totals.recoverable_repos).toBe(1);expect(details.totals.no_remote).toBe(0);});++ test('warn with zero no_remote assets names the assets and reasons that caused it', async () => {+ const dirty = makeHealthyRepo('src-dirty');+ writeFileSync(join(dirty, 'note.md'), '# edited, not committed\n');+ const plain = join(tmp, 'src-plain');+ mkdirSync(plain, { recursive: true });++ const check = await checkBackupCoverage(+ makeEngine([+ { id: 'src-dirty', local_path: dirty },+ { id: 'src-plain', local_path: plain },+ ]),+ { localOnly: true },+ );++ expect(check.status).toBe('warn');+ expect(check.message).toContain('src-dirty (dirty)');+ expect(check.message).toContain('src-plain (not_a_git_repo)');+ expect(check.message).not.toContain('no git remote');+ expect(check.message).toContain('gbrain backup status');+ });++ test('more than five blocking assets → the first five are named, the rest counted', async () => {+ const sources = Array.from({ length: 6 }, (_, i) => {+ const dir = join(tmp, `plain-${i}`);+ mkdirSync(dir, { recursive: true });+ return { id: `plain-${i}`, local_path: dir };+ });++ const check = await checkBackupCoverage(makeEngine(sources), { localOnly: true });++ expect(check.message).toContain('6 knowledge asset(s) lack verified recovery:');+ expect(check.message).toContain('plain-4 (not_a_git_repo), and 1 more.');+ expect(check.message).not.toContain('plain-5');+ });++ test('degraded compute with no assets leads with the unreadable database', async () => {+ const engine = {+ kind: 'pglite',+ executeRaw: async (sql: string) => {+ if (/FROM sources/i.test(sql)) return [];+ throw new Error('pages unreadable');+ },+ } as unknown as BrainEngine;++ const check = await checkBackupCoverage(engine, { localOnly: true });++ expect(check.status).toBe('warn');+ expect(check.message).toStartWith('Backup verdict is not current: the database was unreadable during the check.');+ });});// ── Remote (untrusted) path: cache-only reader, zero git, zero engine ────────@@ -211,6 +261,48 @@ describe('checkBackupCoverage — remote surface (no localOnly)', () => {expect(typeof details.cache_age).toBe('string');});+ test.each([+ { label: 'dirty repo', asset: { state: 'dirty', detail: 'uncommitted changes', configured_remote: true }, reason: '1 dirty' },+ { label: 'remote set, nothing pushed', asset: { state: 'no_remote', configured_remote: true }, reason: '1 remote configured, nothing pushed' },+ { label: 'no remote at all', asset: { state: 'no_remote' }, reason: '1 no git remote' },+ { label: 'ok without remote evidence', asset: { state: 'ok', configured_remote: true }, reason: '1 remote not verified: not_checked' },+ { label: 'known unknown code', asset: { state: 'unknown', detail: 'not_a_git_repo' }, reason: '1 not_a_git_repo' },+ { label: 'free-text unknown detail', asset: { state: 'unknown', detail: 'ahead of origin/private-branch-name' }, reason: '1 unknown' },+ ] as const)('remote warn names reason counts only: $label', async ({ asset, reason }) => {+ saveBackupStatus({+ ...makeWarnCache('private-src-id'),+ totals: { assets: 2, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 0, pages_at_risk: 0 },+ assets: [+ { kind: 'db_only', id: 'private-src-id', state: 'info', fix_argv: null },+ { kind: 'source_repo', id: 'private-src-id', fix_argv: null, ...asset },+ ],+ });++ const check = await checkBackupCoverage(makeThrowingEngine(), {});++ expect(check.status).toBe('warn');+ expect(check.message).toContain(`1 of 2 knowledge asset(s) lack verified recovery (${reason})`);+ expect(check.message).not.toContain('private-src-id');+ expect(check.message).not.toContain('private-branch-name');+ });++ test('stale cache with no blocking asset leads with the staleness, never "0 of N"', async () => {+ __setBackupIntervalForTests(60_000);+ saveBackupStatus({+ ...makeWarnCache('private-src-id'),+ checked_at: new Date(Date.now() - 10 * 60_000).toISOString(),+ overall: 'ok',+ totals: { assets: 1, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 0, pages_at_risk: 0 },+ assets: [{ kind: 'db_only', id: 'private-src-id', state: 'info', fix_argv: null }],+ });++ const check = await checkBackupCoverage(makeThrowingEngine(), {});++ expect(check.status).toBe('warn');+ expect(check.message).toStartWith('Backup verdict is not current: the verdict is older than the check interval.');+ expect(check.message).not.toContain('0 of');+ });+test('ok cache → ok from cache with the cache-only note', async () => {saveBackupStatus({...makeWarnCache('unused'),@@ -220,7 +312,7 @@ describe('checkBackupCoverage — remote surface (no localOnly)', () => {});const check = await checkBackupCoverage(makeThrowingEngine(), {});expect(check.status).toBe('warn');- expect(check.message).toContain('not verified');+ expect(check.message).toContain('(1 remote not verified: not_checked)');expect((check.details as { totals: BackupStatus['totals'] }).totals.recoverable_repos).toBe(0);expect((check.details as { note?: string }).note).toBe('cache-only (remote surface never probes git; aggregate counts only)',diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 282123201b..060c614c93 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -945,7 +945,7 @@"unpushed": 0}},- "message": "0 knowledge asset(s) have no git remote: . Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",+ "message": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).","name": "backup_coverage","status": "warn"},@@ -1241,7 +1241,7 @@"status": "warnings","top_issues": [{- "fix": "0 knowledge asset(s) have no git remote: . Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",+ "fix": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).","name": "backup_coverage","status": "warn","tier": "symptom"diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 9f3f54bc15..43c6ad0cad 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -945,7 +945,7 @@"unpushed": 0}},- "message": "0 knowledge asset(s) have no git remote: . Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",+ "message": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).","name": "backup_coverage","status": "warn"},@@ -1241,7 +1241,7 @@"status": "warnings","top_issues": [{- "fix": "0 knowledge asset(s) have no git remote: . Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",+ "fix": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).","name": "backup_coverage","status": "warn","tier": "symptom"diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 0d6ff4bb98..59337fde0d 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -960,7 +960,7 @@"unpushed": 0}},- "message": "0 knowledge asset(s) have no git remote: . Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",+ "message": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).","name": "backup_coverage","status": "warn"},@@ -1256,7 +1256,7 @@"status": "warnings","top_issues": [{- "fix": "0 knowledge asset(s) have no git remote: . Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).",+ "fix": "1 knowledge asset(s) lack verified recovery: default (not_a_git_repo). Current recovery is not verified for all repositories. Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).","name": "backup_coverage","status": "warn","tier": "symptom"