Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.33.0 feat(backup): monthly backup-coverage check — recreate your agent from a git remote, verified across every harness (#4594)
Garry Tan8a22ee8bccf8
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex f5fa2592e0..11d00b1dab 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.32.0",+ "version": "0.46.33.0","description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex a8827cd10b..89879dfaef 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.32.0",+ "version": "0.46.33.0","description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 8540a56ba1..1900236757 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.32.0 -->+<!-- gbrain-runbook-stamp: 0.46.33.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fd0ebd74a7..c5785e1d44 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,125 @@All notable changes to GBrain will be documented in this file.+## [0.46.33.0] - 2026-08-26++**gbrain now checks, once a month, that your brain and skill files are actually backed up to a git remote, and tells you exactly how to fix it when they aren't.**++Your brain is only as durable as its worst-backed repo. If a knowledge repo lives+only on one disk, a disk failure erases it, and nothing warned you. gbrain already+pushed bootstrap workspaces automatically, but nobody ever asked the simpler,+scarier question: does every repo have a remote at all? Now something does. Once+a month (configurable), gbrain sweeps every registered source repo and your agent+workspace, answers "if this disk died right now, could I recreate my agent?", and+if the answer is no, the warning reaches you in whatever tool you actually use:+a visible banner in Claude Code, a note in the session digest, an aggregate line+in MCP tool responses for Codex and OpenClaw setups, a one-liner on the CLI, and+the OpenClaw context feed. Every warning carries the exact fix commands. Warnings+are hard-bounded: at most one per day, at most three per month, and they stop the+moment you fix the repo.++How to use it:++```bash+gbrain backup status # verdict + per-asset table + fix commands (exit 1 on warn)+gbrain backup check # force a recompute now+gbrain config set backup.check_interval_days 30 # cadence (default 30, min 1)+gbrain config set backup.check_enabled false # off switch (or GBRAIN_BACKUP_CHECK=0)+```++What you'd see on an unbacked brain:++| Asset | State | Fix printed |+|---|---|---|+| a knowledge repo with no `origin` (or a remote configured but never pushed) | warn (flips the verdict) | `git remote add origin <url> && git push -u origin <branch>`, then `gbrain sources harden <id>` |+| workspace with no private repo | warn | `gbrain bootstrap repo` |+| pages that live only in the local database | warn on PGLite, info on managed Postgres | `gbrain sources add` / `gbrain bootstrap repo` |+| `db_only` storage-tier pages | info | `gbrain export --dir <backup-dir>` |+| commits not yet pushed | info only | `gbrain sources push --path <workspace>` |++Things to watch: the verdict is cached at `~/.gbrain/backup-status.json` and+recomputes automatically (sync completion, the serve process, a detached+session-end check); `gbrain backup status` re-probes immediately whenever the+cached verdict is a warning, so a hand-fixed repo goes green on the next look.+Remote/MCP surfaces only ever see aggregate counts, never repo names or paths.+All git probes are local read-only commands; nothing touches the network.+`docs/operations/backup-check.md` has the full contract, including a quarterly+recovery drill that proves the answer is real.++### To take advantage of v0.46.33.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor`+warns about a partial migration:++1. **Run the orchestrator manually:**+ ```bash+ gbrain apply-migrations --yes+ ```+ (No schema migration ships in this release; the step is safe and idempotent.)+2. **Your agent picks the feature up on its own.** The next `gbrain doctor` or+ `gbrain advisor` run computes the first backup verdict; no manual action needed.+3. **Verify the outcome:**+ ```bash+ gbrain backup check+ gbrain backup status+ ```+ Exit 0 with a recovery statement means you're covered; exit 1 prints the fixes.+4. **If any step fails or the numbers look wrong,** please file an issue:+ https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor`+ and `gbrain backup status --json`. This feedback loop is how the gbrain+ maintainers find fragile upgrade paths. Thank you.++### Itemized changes++### Added+- **Backup-coverage core** (`src/core/backup/status-file.ts`, `src/core/backup/coverage.ts`):+ cached verdict at `~/.gbrain/backup-status.json` (schema `gbrain-backup-status-v1`,+ atomic writes, fail-open reads); bounded nag ledger at `~/.gbrain/backup-nag-state.json`+ (schema `gbrain-backup-nag-v1`: 24h cross-channel dampener, per-channel ceiling 3 per+ month+verdict fingerprint, global cap 3 recorded impressions per month, spawn debounce);+ compute sweeps sources deduped by git root (`originRemoteState`/`hasRemoteTrackingRef`/+ `aheadCount`/`isWorkingTreeDirty`, execFile array args, capped at 500 roots with a logged skip count,+ event-loop yields between probes), the bootstrap receipt + push statuses, `db_only`+ tiering, and the DB-only-brain worst case (warn on PGLite, info with different copy on+ managed Postgres via `engine.kind`). Degraded computes (engine unreadable mid-run) are+ never persisted and never replace a probed cache.+- **`gbrain backup status|check`** (`src/commands/backup.ts`): exit 0 ok / 1 warn / 2 usage+ error; recovery statement in human output and a structured `recovery` field in `--json`;+ falls back to the cached verdict with a note when a running `gbrain serve` holds the+ PGLite lock; `--quiet` is the detached-spawn mode (always exit 0). Dispatched pre-engine+ in `src/cli.ts` so `--help` and the lock fallback never touch the database.+- **Doctor + advisor surfaces**: `backup_coverage` check (`src/commands/doctor/checks/backup-coverage.ts`,+ ops category; local runs probe, remote surfaces are cache-only with aggregate counts) and+ the `backup-coverage` advisor collector (`src/core/advisor/collect-backup-coverage.ts`)+ with per-repo findings + fix argvs locally, one aggregate finding remotely.+- **Render channels**: Claude Code user-prompt banner (`systemMessage`, push-failure banner+ wins the slot) + session-start digest note + session-end detached `backup check --quiet`+ spawn (`src/commands/hook.ts`); an aggregate extra content block once per stdio serve+ process (`src/mcp/dispatch.ts` — HTTP serves attach nothing; `content[0]` untouched);+ a CLI stderr rail with the `BACKUP_LOCAL_ONLY <n>` machine marker (`src/cli.ts`); an+ OpenClaw context line that consults the budget read-only (`src/core/context-engine.ts`).+- **Config keys** `backup.check_enabled` and `backup.check_interval_days` (file-plane,+ routed by `gbrain config set/unset`; `config set` rejects intervals below 1 day) + env+ switches `GBRAIN_BACKUP_CHECK=0` and `GBRAIN_BACKUP_CHECK_DAYS` (invalid or sub-1 env+ values fall back to the 30-day default).+- **Docs**: `docs/operations/backup-check.md` (coverage table, channels, nag budget, state+ files, privacy rules, fix recipes, recovery drill), two `docs/architecture/KEY_FILES.md`+ entries, a `backup-check` row in the bootstrap HEARTBEAT template (ships disabled), and+ monthly-cadence notes in the `gbrain-advisor` and `maintain` skills.+- **Tests**: eight new suites (~150 tests) covering the nag budget lifecycle, compute+ classification against real git fixtures, the trust pins (HTTP/unset transport never+ probes git; stdio-only serve refresher; single-flight), remote aggregate privacy, the+ CLI lock fallback, fix-path cache invalidation, and config routing.++### Changed+- `gbrain sources push`, `gbrain sources harden`, and `gbrain bootstrap repo` now drop the+ cached backup verdict on success, so a fixed repo stops warning immediately (`sources push`+ only when the cache carried a warn or failing/unpushed work — a routine healthy push+ leaves an ok cache alone).+- `gbrain sync` completion piggybacks a stale-only backup recompute (trusted local engine+ holder; dry runs stay pure).+- `src/core/workspace-push.ts` exports `aheadCount`; `InstallReceipt` gains the typed+ optional `repo_url` field (`src/core/bootstrap/format.ts`).## [0.46.32.0] - 2026-08-26**The community train: 54 contributor PRs absorbed.** Wave K triaged all 141diff --git a/CLAUDE.md b/CLAUDE.mdindex ebc84d1705..e60e270377 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -146,6 +146,7 @@ detail on demand.)| search / ranking / hybrid / retrieval | `docs/architecture/RETRIEVAL.md` + the `search/*` entries in `KEY_FILES.md` || search modes / cost knobs | `docs/guides/search-modes.md` || embedding spend gates / cost gate / `spend.posture` / off switches | `docs/operations/spend-controls.md` |+| the monthly backup-coverage check (`gbrain backup`, render channels, nag budget) | `docs/operations/backup-check.md` + the `backup/*` entries in `KEY_FILES.md` || push-based context (volunteer/watch/reflex window) | `docs/guides/push-context.md` || checkpoint compaction / compiled context files (`gbrain compile-context`) | `docs/guides/checkpoint-compaction.md` + `docs/guides/ambient-recall.md` || chat connectors (live ChatGPT/Claude history sync — `gbrain connectors`) | `docs/guides/chat-connectors.md` + the `src/core/connectors/*` entries in `KEY_FILES.md` |diff --git a/TODOS.md b/TODOS.mdindex 2b3e3ff70b..139a89a1da 100644--- a/TODOS.md+++ b/TODOS.md@@ -2217,6 +2217,48 @@ job) and sync. See CLAUDE.md "Pace Mode".`embed --stale --pace --progress-json` caps concurrency + emits telemetry;single-flight rejects a 2nd concurrent run; lock heartbeat advances during apaced sleep (short-TTL). Unit coverage (`db-pacer`/`pace-mode`) already ships.+## monthly backup-check follow-ups (filed with the backup-coverage feature)++- [ ] **P2 — Opt-in network push-probe for the backup check (`gbrain backup check --probe`).**+ **What:** authed `pushProbe` (`src/core/git-remote.ts:598`) per asset proving the remote+ is actually PUSHABLE, with TTL-cached verdicts (the `repo-visibility.ts` 1h-cache idiom).+ **Why:** "has origin" doesn't prove "can push" — a revoked PAT or protected branch passes+ today's local-only check while the backup silently rots. **Pros:** turns the verdict from+ "configured" into "verified". **Cons:** network + auth in a check that is deliberately+ offline today; must stay opt-in. **Context:** v1 holds the no-network line by design; the+ seam is `BackupCoverageOpts` in `src/core/backup/coverage.ts` (add a `probe` flag beside+ `localGitProbes`). Effort: M → S with CC. Depends on: the backup-check feature (landed).+- [ ] **P2 — Codex/opencode hook lanes for parity with Claude Code.**+ **What:** flip `CODEX_HAS_HOOKS`/`OPENCODE_HAS_HOOKS` (`src/core/bootstrap/host-specs.ts:341/:421`)+ and wire `gbrain hook` into codex 0.147+'s hooks.json so those harnesses get the+ session-start digest + banner rail. **Why:** today their only backup-notice reach is the+ MCP aggregate block + CLI stderr; Claude Code users get a human-visible systemMessage.+ **Pros:** closes the harness-reach gap for every hook-borne notice, not just backup.+ **Cons:** new host-integration surface to maintain per harness release. **Context:** the+ backup check's render channels are already shaped for it — a codex hook lane would reuse+ `backupSessionStartNote`/`pendingBackupBanner` unchanged. Effort: L → M with CC.+- [ ] **P3 — Neutralize repo-local git config execution vectors in the read-only probe env.**+ **What:** add `-c core.fsmonitor= -c core.hooksPath=` (and consider `core.sshCommand`) to the+ read-only git probe invocations (`GIT_ENV` / `buildGitInvocation` consumers: `hasOriginRemote`,+ `isWorkingTreeDirty`, `detectDefaultBranch`, `aheadCount`, the backup-coverage probes).+ **Why:** `git status` honors `core.fsmonitor` from the TARGET repo's own `.git/config`; the+ backup check now runs probes automatically and periodically across every source root, so a+ hostile config planted inside any registered tree executes monthly without user action.+ **Cons:** touches every existing git caller (sync, doctor, durability) — needs its own test+ sweep; exploiting already requires local write access (D4 holds), so this is defense-in-depth.+ **Where to start:** `src/core/git-remote.ts:GIT_ENV` + `src/core/sync-git.ts:buildGitInvocation`.+- [ ] **P3 — Notice-center rail: one cross-feature nag system.**+ **What:** extract a shared notice rail (per-channel nag state, dampening, render+ adapters) and migrate the backup nag, the push-failure banner (`hook.ts`+ `pendingPushFailureBanner` + `.announced` sidecars), and the upgrade nag+ (`self-upgrade.ts` snooze) onto it. **Why:** three parallel nag systems with three state+ formats is debt; every new periodic notice re-invents cadence + budget logic. **Pros:**+ one budget across ALL notices (no cross-feature nag pileups); one place to test.+ **Cons:** touches load-bearing hook code; needs migration for existing state files.+ **Context:** `src/core/backup/status-file.ts`'s gate (per-channel entries + dampener ++ global monthly cap, enforced uniformly in `record()`) is deliberately shaped as the seed.+ Effort: M-L. Blocked by: the backup-check feature shipping first.+## brain-repo durability follow-ups (filed v0.42.48.0)- [ ] **P3 — gbrain write-path calls commit-push synchronously when durability is on.**diff --git a/VERSION b/VERSIONindex a2246b7a67..c081238583 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.32.0+0.46.33.0diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex bb69ce4fb6..0f4da2b6c1 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -596,6 +596,8 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the #2139 cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/secret-scan.ts` — pattern scanner for USER workspaces (own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml`, which is a public-repo CI fixture policy); redacted previews only; `redactFindings` is the corpus-write mode.+- `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`.+- `src/core/backup/coverage.ts` — engine-side compute for the backup check. `computeBackupCoverage(engine, {localGitProbes})` assesses: source repos (deduped by `discoverGitRoot`, capped 500 roots with a logged skip count; `originRemoteState` — a positive tri-state, deliberately NOT sync-git's `hasOriginRemote`, which collapses probe failures into a false "no remote" — plus `hasRemoteTrackingRef` (origin configured but never pushed is also `no_remote`), `aheadCount`, `isWorkingTreeDirty` — local read-only git subcommands only, no network), the bootstrap workspace (receipt `repo_url` + push statuses, file plane only), db_only tiering (info row with the `gbrain export --dir` fix), harness skill dirs (info — installed copies), and the DB-only-brain worst case (pages>0, nothing git-backed → warn on PGLite / info with different copy on postgres — the engine.kind branch). `no_remote` alone flips `overall: 'warn'`. `getBackupStatus` is the single choke point (fresh cache → file read; probed results persist, probe-less results NEVER persist; a failed compute returns the prior cache — never clobbers). `maybeRefreshBackupStatusInProcess(engine)` is the serve-side single-flight refresher — called from `mcp/dispatch.ts` gated on `opts.transport === 'stdio'` (the WP1/D7 locality axis; 'http'/UNSET ⇒ fail-closed, pinned by test), recomputes on stale-or-absent OR warn+>24h, 1h attempt floor. Trust boundary: D4 (`extraction-sync.ts` anchor) — git probes only in trusted-local contexts. Consumers: `commands/backup.ts` (`gbrain backup status|check`, PGLite-lock fallback to cache), `advisor/collect-backup-coverage.ts`, `doctor/checks/backup-coverage.ts` (`backup_coverage`, localOnly probes / remote cache-only), `commands/sync.ts` post-sync stale-only refresh, hook session-end detached spawn. Docs: `docs/operations/backup-check.md`. Tests: `test/backup-coverage.serial.test.ts`, `test/advisor-backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/hook-backup-notice.serial.test.ts`, `test/mcp-backup-nag.serial.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).- `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 (#4287: 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.mdnew file mode 100644index 0000000000..5a494c0c3a--- /dev/null+++ b/docs/operations/backup-check.md@@ -0,0 +1,152 @@+# The monthly backup-coverage check++gbrain verifies, once a month, that your brain content and skill files are+backed up to a git remote — and warns you through whatever harness you+actually use when they aren't. The question it answers: **"if this disk died+right now, could I recreate my agent?"**++## What is covered++| Asset | How it's checked | Warn condition |+|---|---|---|+| Source repos (every non-archived source with a `local_path`) | local git probes: `git remote get-url origin`, `rev-list --count`, `status --porcelain` — deduped by git root, capped at 500 roots/run | no `origin` remote, OR origin configured but never pushed (`origin/<branch>` unresolvable — the half-completed `git remote add` state). Both report `no_remote`. |+| 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) |+| DB-only brain (pages exist, nothing git-backed) | page count + absence of any git-backed asset | warn on PGLite (total loss on disk failure); info on managed Postgres (DB survives, but isn't the git system of record) |+| `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 |++Only `no_remote` flips the overall verdict to **warn**. Push *staleness* of an+existing remote stays with the existing channels (`bootstrap_push_health`, the+push-failure banner).++**Not covered (v1, by design):** the DB file itself (`~/.gbrain` is+deliberately gitignored — the repo is the system of record and the DB rebuilds+via `gbrain sync`); mounted brains (the verdict cache is host-brain-scoped —+computes against a mounted brain are never persisted); pure-HTTP thin-client+installs (no local CLI on the brain host — nothing there can probe git);+network reachability of the remote (`--probe` is a filed follow-up; "has+origin" doesn't prove "can push"); DB pages that belong to no source on an+install that HAS a workspace repo (whether the workspace write-through covers+them is not verified — the `undeclared_db_only_pages` doctor check is the+page-level audit). The OpenClaw context line is bounded per process (once per+24h); an install that restarts its serve constantly and never fires any+recording channel can see it more often than the recorded-notice cap.++## Where the warning reaches you++One compute, one cached verdict (`~/.gbrain/backup-status.json`), five render+channels — all bounded by the shared nag budget:++1. **Claude Code banner** (`gbrain hook user-prompt` → `systemMessage`, shown+ directly to you; a pending push-failure banner outranks it).+2. **Claude Code session-start digest** (model-visible note).+3. **MCP tool responses** (one aggregate extra content block per stdio serve+ process — counts only, never paths; reaches Codex, OpenClaw, and+ plugin-only installs, which all register stdio serves). HTTP serves attach+ no notice: a remote thin client's token scope doesn't grant the host's+ backup posture, and a remote-triggered display must not spend the local+ notice budget.+4. **CLI stderr** on most `gbrain <cmd>` invocations (serve/hook/jobs/call,+ the upgrade surfaces (`upgrade`/`post-upgrade`/`check-update`/`self-upgrade`),+ and the check's own surfaces are excluded; `--quiet` and+ `GBRAIN_SKIP_STARTUP_HOOKS` silence it). The machine marker+ `BACKUP_LOCAL_ONLY <n>` prints on non-TTY stderr for agents, plus a one-line+ human sentence.+5. **OpenClaw context engine** (one ⚠ line, read-only against the budget).++Two more surfaces spend the same budget without being passive nags: `gbrain+backup status` records an impression when it prints a warn verdict (you just+saw the full table — the passive channels go quiet for 24h), and the advisor+collector records one when it emits backup findings.++Nag budget: at most one impression per 24h across channels, at most 3 per+channel per month **per verdict** (a changed verdict — a repo fixed or a new+one gone local-only — re-arms the per-channel count mid-month), at most 3+recorded impressions per month TOTAL. Fixing the repo (or a new month) re-arms+it; ignoring it goes quiet until next month.++## Commands++```+gbrain backup status [--json] # verdict + per-asset table + fix commands + recovery statement+gbrain backup check [--json] # force a recompute now+```++Exit codes: 0 ok / 1 warn / 2 usage error. Two forced-0 paths: the global+`--quiet` flag (the detached-spawn mode) always exits 0, and a disabled check+(`backup.check_enabled=false` / `GBRAIN_BACKUP_CHECK=0`) exits 0 even on a+cached warn — automation reading exit codes sees the off switch as all-clear,+never a stale failure. `status` answers from the cache when it's ok,+recomputes when it's warn or stale, and falls back to the cached verdict with+a note when a running `gbrain serve` holds the PGLite lock (the serve process+refreshes the verdict itself within a day). The `--json` payload includes a+structured `recovery` field.++When does the compute actually run? On any of: `gbrain backup check`, a stale+cache at `backup status`/doctor/advisor time, `gbrain sync` completion, the+serve process (stdio only) when the cache is stale or a warn verdict is >24h+old, and a detached spawn from the session-end hook. Automatic triggers+self-throttle to once per `backup.check_interval_days`. The monthly recompute+can add a few seconds to one local advisor/doctor run (the 500-root probe cap+bounds it).++## Config + kill switches++```+gbrain config set backup.check_enabled false # off (file plane)+gbrain config set backup.check_interval_days 30 # default 30; set rejects values < 1+GBRAIN_BACKUP_CHECK=0 # env kill switch (everything)+GBRAIN_BACKUP_CHECK_DAYS=<n> # env interval override (wins over config)+```++Interval values below 1 or non-numeric (env or a hand-edited config file) fall+back to the 30-day default — `DAYS=0` never means "recompute every dispatch".+Disabling silences compute AND every render channel, including a stale warn+cache, and forces `backup status` to exit 0. `GBRAIN_HOOKS=0` already silences the hook channels;+`GBRAIN_SKIP_STARTUP_HOOKS` silences the CLI rail.++## State files (machine-owned, under `~/.gbrain/`)++- `backup-status.json` — the cached verdict. Written only by a successful+ probed compute; deleted automatically when a fix lands (`bootstrap repo`,+ `sources harden`, `sources push` success). A compute that couldn't read the+ brain database returns a `degraded: true` verdict (shown as "verdict is+ partial (not cached)" in `backup status`, and as a `degraded` field in+ `--json`) — it is never persisted and never replaces a probed cache.+- `backup-nag-state.json` — the bounded-nag ledger (per-channel counts, the+ 24h dampener, the monthly global cap, the spawn debounce).++Both are fail-open: corrupt or missing files never break a session.++## Privacy++Remote/MCP surfaces render **aggregate counts only** — never a local path or+source id. Full per-asset detail (which repo, which fix) is local-only:+`gbrain backup status` on the brain host.++## Fix recipes++- Workspace with no repo: `gbrain bootstrap repo` (creates a private repo,+ verifies privacy, pushes).+- A source repo with no remote:+ `git remote add origin [email protected]:you/your-brain-repo.git && git push -u origin main`,+ then `gbrain sources harden <source-id>` for auto-push durability.+- Unpushed workspace work: `gbrain sources push --path <workspace>`.+- db_only pages: `gbrain export --dir <backup-dir>` (store the dump outside+ the gitignored dirs — another disk, another repo, anywhere durable).++## Recovery drill (prove the answer is real)++An unverified recovery path is as fake as an unverified backup. Once a+quarter, on a scratch machine or empty directory:++1. `git clone [email protected]:you/your-brain-repo.git && cd your-brain-repo`+2. `gbrain bootstrap attach` — the body travels; identity, memory, and skills+ come back from the repo.+3. Re-add any extra sources: `gbrain sources add <id> --path ../your-wiki`+ (or `--url` for managed clones).+4. `gbrain sync && gbrain embed` — the brain database rebuilds from the repos.+5. `gbrain doctor` — green means the agent is recreated.++If any step fails, that's the gap the monthly check exists to catch — fix it+while the original disk still works.diff --git a/llms-full.txt b/llms-full.txtindex ee3f214d89..aa30fa98dd 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -306,6 +306,7 @@ detail on demand.)| search / ranking / hybrid / retrieval | `docs/architecture/RETRIEVAL.md` + the `search/*` entries in `KEY_FILES.md` || search modes / cost knobs | `docs/guides/search-modes.md` || embedding spend gates / cost gate / `spend.posture` / off switches | `docs/operations/spend-controls.md` |+| the monthly backup-coverage check (`gbrain backup`, render channels, nag budget) | `docs/operations/backup-check.md` + the `backup/*` entries in `KEY_FILES.md` || push-based context (volunteer/watch/reflex window) | `docs/guides/push-context.md` || checkpoint compaction / compiled context files (`gbrain compile-context`) | `docs/guides/checkpoint-compaction.md` + `docs/guides/ambient-recall.md` || chat connectors (live ChatGPT/Claude history sync — `gbrain connectors`) | `docs/guides/chat-connectors.md` + the `src/core/connectors/*` entries in `KEY_FILES.md` |diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex af4d9a0ffc..4d3aad6f02 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.32.0",+ "version": "0.46.33.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex a5231ada27..586bb0968d 100644--- a/package.json+++ b/package.json@@ -171,7 +171,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.32.0",+ "version": "0.46.33.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 638e53273e..91fe6cff94 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.32.0",+ "version": "0.46.33.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 6a595333ee..1063989188 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.46.32.0",+ "version": "0.46.33.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 51190afb99..46e4d1ff59 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.32.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.33.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.mdindex ac82e2949c..dd2e6ce38d 100644--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md@@ -386,6 +386,13 @@ their last embedding. For large brains (>5000 pages), run this with nohup:nohup gbrain embed --stale > /tmp/gbrain-embed.log 2>&1 &```+### Monthly backup check++Run `gbrain backup status` and relay anything red. It verifies every knowledge+repo (and the agent workspace) has a git remote — local-only means a disk loss+loses it. Fixes are printed inline (`gbrain bootstrap repo`, `git remote add`,+`gbrain sources harden <id>`).+### Daily verificationVerify sync is running: check `gbrain stats` and confirm `last_sync` is withindiff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 2576bfd00c..2914a6340d 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.32.0",+ "version": "0.46.33.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 78025e6937..a433f4a0b6 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.46.32.0",+ "version": "0.46.33.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex bd688e7e0b..c1302b5042 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.32.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.33.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.md b/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.mdindex 01db44a6de..204bbc7bb5 100644--- a/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.md+++ b/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.md@@ -37,6 +37,8 @@ This skill guarantees:- On demand when the user asks "how do I get more out of this brain?"- On a **weekly** cadence via the cron recipe below (even idle brains get a"here's how to run this better" ping).+- Monthly, the advisor also surfaces the backup-coverage verdict (`gbrain+ backup status` — which knowledge repos have no git remote); relay any warn.## How to run itdiff --git a/plugin/README.md b/plugin/README.mdindex eaa1b6a582..d692c29c97 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.32.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.33.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/gbrain-advisor/SKILL.md b/plugin/skills/gbrain-advisor/SKILL.mdindex 01db44a6de..204bbc7bb5 100644--- a/plugin/skills/gbrain-advisor/SKILL.md+++ b/plugin/skills/gbrain-advisor/SKILL.md@@ -37,6 +37,8 @@ This skill guarantees:- On demand when the user asks "how do I get more out of this brain?"- On a **weekly** cadence via the cron recipe below (even idle brains get a"here's how to run this better" ping).+- Monthly, the advisor also surfaces the backup-coverage verdict (`gbrain+ backup status` — which knowledge repos have no git remote); relay any warn.## How to run itdiff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.mdindex ac82e2949c..dd2e6ce38d 100644--- a/plugin/skills/maintain/SKILL.md+++ b/plugin/skills/maintain/SKILL.md@@ -386,6 +386,13 @@ their last embedding. For large brains (>5000 pages), run this with nohup:nohup gbrain embed --stale > /tmp/gbrain-embed.log 2>&1 &```+### Monthly backup check++Run `gbrain backup status` and relay anything red. It verifies every knowledge+repo (and the agent workspace) has a git remote — local-only means a disk loss+loses it. Fixes are printed inline (`gbrain bootstrap repo`, `git remote add`,+`gbrain sources harden <id>`).+### Daily verificationVerify sync is running: check `gbrain stats` and confirm `last_sync` is withindiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex ae29e95d57..e2fb135b0b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,14 +3,14 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/commands/doctor.ts 4500 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; +chat-connectors wiring; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193)+src/commands/doctor.ts 4507 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; +chat-connectors wiring; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check)src/core/operations.ts 316 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiringsrc/core/postgres-engine.ts 5625 ratchet lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980)src/core/pglite-engine.ts 6110 ratchet grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980)src/core/migrate.ts 687 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482)-src/commands/sync.ts 5658 ratchet grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases+src/commands/sync.ts 5683 ratchet grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +25 post-sync backup-coverage stale-only refresh (monthly backup check)src/core/ai/gateway.ts 4568 ratchet grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980)-src/cli.ts 3777 ratchet grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; +chat-connectors wiring; wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch+src/cli.ts 3797 ratchet grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; +chat-connectors wiring; wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check)src/core/cycle.ts 3186 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k)src/commands/serve-http.ts 3317 ratchet grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helpersrc/commands/jobs.ts 3127 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring@@ -35,7 +35,7 @@ src/core/link-extraction.ts 1681 ratchet grown v0.46.26.0 megawave: link-aware tsrc/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers)src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)src/core/bootstrap/harness.ts 1951 ratchet +4 at megawave/wave-k merge-src/commands/hook.ts 1559 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245)+src/commands/hook.ts 1667 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers)src/core/chunkers/code.ts 1575 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunkssrc/core/oauth-provider.ts 1552 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard)-src/core/config.ts 1551 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge)+src/core/config.ts 1559 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8 backup.check_enabled/check_interval_days file-plane keys (monthly backup check)diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 2ca7f487b9..bc6c304971 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -27,6 +27,8 @@ test/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressitest/autopilot-shutdown-engine-close.test.ts autopilot.ts graceful engine shutdown (#1872) 6 readFileSynctest/autopilot-supervisor-wiring.test.ts autopilot.ts ↔ ChildWorkerSupervisor wiring 7 readFileSynctest/backlinks-job-default.test.ts backlinks Minion handler — empty payload defaults to check, not fix 3 readFileSync+test/backup-cli.serial.test.ts runBackupCli — PGLite lock fallback 3 readFileSync+test/backup-invalidation.serial.test.ts bootstrap repo — recordRepoInReceipt contract (source-text pin) 2 readFileSynctest/book-mirror.test.ts gbrain book-mirror — source file invariants 7 readFileSynctest/bootstrap-codex-door.test.ts Codex door — rendered AGENTS.md pull protocol (Gate 3) 2 readFileSynctest/bootstrap-opencode-door.serial.test.ts opencode door — rendered AGENTS.md pull protocol 1 readFileSyncdiff --git a/skills/gbrain-advisor/SKILL.md b/skills/gbrain-advisor/SKILL.mdindex 01db44a6de..204bbc7bb5 100644--- a/skills/gbrain-advisor/SKILL.md+++ b/skills/gbrain-advisor/SKILL.md@@ -37,6 +37,8 @@ This skill guarantees:- On demand when the user asks "how do I get more out of this brain?"- On a **weekly** cadence via the cron recipe below (even idle brains get a"here's how to run this better" ping).+- Monthly, the advisor also surfaces the backup-coverage verdict (`gbrain+ backup status` — which knowledge repos have no git remote); relay any warn.## How to run itdiff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.mdindex ac82e2949c..dd2e6ce38d 100644--- a/skills/maintain/SKILL.md+++ b/skills/maintain/SKILL.md@@ -386,6 +386,13 @@ their last embedding. For large brains (>5000 pages), run this with nohup:nohup gbrain embed --stale > /tmp/gbrain-embed.log 2>&1 &```+### Monthly backup check++Run `gbrain backup status` and relay anything red. It verifies every knowledge+repo (and the agent workspace) has a git remote — local-only means a disk loss+loses it. Fixes are printed inline (`gbrain bootstrap repo`, `git remote add`,+`gbrain sources harden <id>`).+### Daily verificationVerify sync is running: check `gbrain stats` and confirm `last_sync` is withindiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 9abe4ec295..cfb9c84464 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -83,13 +83,13 @@"frontmatter-guard/routing-eval.jsonl": "243c28b04b557bac5360318c0f47bb6f1dd56d2f720aad3763b93fc0b2ea081e","functional-area-resolver/SKILL.md": "52df04bc4f8e678f931c3b2078b2126524e6d2d72676ad46b6b710d13271b46c","functional-area-resolver/routing-eval.jsonl": "f80674d915acdfe229046737a5b171da834be15ac6524b5a3fd18048e9b37028",- "gbrain-advisor/SKILL.md": "c15c7a88bee2c96733d718a168dd9afcb123b7b6b2c0014c5260d37c72e8736a",+ "gbrain-advisor/SKILL.md": "b4186ce45ba1b5b90b62aee2cc39a72f56edf148f27507219afaeeeee87b22f6","gbrain-upgrade/SKILL.md": "dcd1ee1d12d500fc1f56d1545c3f05fc305619f295dba53ea1843ae9d820ae1e","idea-ingest/SKILL.md": "01ef449b7d5df52553cfd7c05d1365085058eda32de4fad3e67a22311ccd49f5","idea-lineage/SKILL.md": "bbf37781d93b71ddc7909ecc5ab635872c874fb8591995dbf88b45ffeac6b1de","idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41","ingest/SKILL.md": "dc40ecc0072806fb8c7bb6ab9cf1f103842e05653eb55d67632d7e3ffc4dd7d2",- "maintain/SKILL.md": "3c3ae93af3b224b1f4e2fce313a45b5306809e13eeae3908ba19eacfac7d9d5f",+ "maintain/SKILL.md": "de3d9a6ce414470ce4bd406b28d9c8ab80ee90a56d51ff1bc5136cae9fead00d","manifest.json": "32ec742721aa89c814edcdf17809c73a30dda0c20c4399e1239db10e8504c1c0","measure-before-you-fix/SKILL.md": "1fd3b40ab65cbd08f50dea16107701859165469be3c85c57d779c7b4bbf92db8","measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c",diff --git a/src/cli.ts b/src/cli.tsindex 1f144402a7..38a51aa334 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -77,7 +77,9 @@ export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'pglite-repair', 'upgr// are ENGINE-FREE (dispatched in handleCliOnly before the connectEngine// terminator) and must NEVER enter THIN_CLIENT_REFUSED_COMMANDS. `sweep` is// the trusted local sweep entry [CX2-5] and needs the engine (switch case).-'bootstrap', 'hook', 'sweep']);+'bootstrap', 'hook', 'sweep',+// Monthly backup-coverage check (engine via thunk — pre-engine branch, lock-safe).+'backup']);// CLI-only commands whose handlers print their own --help text. These are// excluded from the generic short-circuit so detailed per-command and// per-subcommand usage stays reachable.@@ -168,6 +170,9 @@ const CLI_ONLY_SELF_HELP = new Set([// would leave that help dead code behind the generic stub (the init.ts:117// trap ENG-2 names).'bootstrap', 'hook', 'sweep',+ // backup ships its own HELP (runBackupCli guard, engine-free — the command+ // dispatches in the pre-engine lane, so help never touches the PGLite lock).+ 'backup',// cathedral-4: transcripts ships its own HELP (the ingest import lane +// the v0.29 recent reader). Without this the generic stub hides both.'transcripts',@@ -448,6 +453,13 @@ async function main() {// GBRAIN_SKIP_STARTUP_HOOKS for their children. Runs for every real command.maybeEmitUpdateMarker(command);+ // Monthly backup-coverage nag (cache-read-only, bounded by the nag gate;+ // guards + skip set live inside the helper — one place, every call site).+ {+ const { maybeEmitBackupNag } = await import('./core/backup/status-file.ts');+ maybeEmitBackupNag(command, { quiet: getCliOptions().quiet === true });+ }+const subArgs = args.slice(1);// DX alias: `ask` is a natural-language alias for `query`@@ -2085,6 +2097,14 @@ async function handleCliOnly(command: string, args: string[]) {setCliExitVerdict(await runHook(args));return;}+ if (command === 'backup') {+ // Monthly backup-coverage check. Engine via thunk: a serve-held PGLite+ // lock degrades to the cached verdict inside runBackupCli instead of a+ // connectEngine crash (the primary cohort runs a long-lived stdio serve).+ const { runBackupCli } = await import('./commands/backup.ts');+ setCliExitVerdict((await runBackupCli(args, () => connectEngine())).exitCode);+ return;+ }if (command === 'sweep' && (args.includes('--help') || args.includes('-h'))) {// SWEEP_HELP is engine-independent and must print on a fresh install// (the sync/capture/enrich pre-engine-bind precedent). runSweep's --helpdiff --git a/src/commands/backup.ts b/src/commands/backup.tsnew file mode 100644index 0000000000..dd4c3d2751--- /dev/null+++ b/src/commands/backup.ts@@ -0,0 +1,181 @@+/**+ * commands/backup.ts — `gbrain backup` CLI surface (monthly backup-coverage+ * check: "if this disk died, could I recreate my agent?").+ *+ * gbrain backup status [--json] # verdict + per-asset table + fix commands+ * gbrain backup check [--json] # force a recompute + write the cache+ *+ * Exit codes: 0 ok / 1 warn (both subcommands). `--quiet` (global flag) is+ * the detached-spawn mode: no output, always exit 0.+ *+ * ENGINE HANDLING: dispatched in cli.ts's PRE-engine lane and connects via an+ * injected thunk, because the shared connectEngine would die on the PGLite+ * single-writer lock while a `gbrain serve` runs — exactly the primary cohort+ * this command serves. On an engine-acquire failure both subcommands fall+ * back to the cached verdict + age (cache-derived exit code), never a crash;+ * absent cache + lock held → unknown, exit 0 (fail-open). The stdio serve+ * refresher's warn+24h rule is what makes "it refreshes within a day" true.+ */++import type { BrainEngine } from '../core/engine.ts';+import { getCliOptions } from '../core/cli-options.ts';+import { getBackupStatus } from '../core/backup/coverage.ts';+import {+ backupCacheAge,+ backupCheckDisabled,+ backupNagGate,+ isBackupStatusStale,+ loadBackupStatus,+ type BackupStatus,+} from '../core/backup/status-file.ts';++export interface BackupCliResult {+ exitCode: 0 | 1 | 2;+}++const HELP =+ 'gbrain backup <status|check> [--json]\n\n' ++ ' status Backup-coverage verdict: which knowledge repos have a git remote,\n' ++ ' what survives a disk loss, and the exact fix commands. Uses the\n' ++ ' cached verdict when it is ok; recomputes when it is warn or stale.\n' ++ ' check Force a recompute and write the cache.\n\n' ++ ' --json Structured verdict (includes the recovery field).\n\n' ++ 'Exit codes: 0 ok / 1 warn / 2 usage error. Off switches: GBRAIN_BACKUP_CHECK=0 or\n' ++ '`gbrain config set backup.check_enabled false`. Interval:\n' ++ '`gbrain config set backup.check_interval_days <n>` (default 30, min 1;\n' ++ 'env GBRAIN_BACKUP_CHECK_DAYS wins over config).';++function exitFor(s: BackupStatus | null): 0 | 1 {+ return s?.overall === 'warn' ? 1 : 0;+}++function recoveryStatement(s: BackupStatus): string {+ const repos = s.totals.recoverable_repos;+ const risk = s.totals.pages_at_risk;+ const repoPart = `${repos} repo${repos === 1 ? '' : 's'} recoverable from a git remote`;+ const riskPart = risk > 0 ? `${risk} page${risk === 1 ? '' : 's'} at risk` : 'no pages at risk';+ return `What survives a disk loss today: ${repoPart}; ${riskPart}.`;+}++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.state === 'no_remote' ? '✗' : a.state === 'info' ? '·' : '⚠';+ out(` ${mark} [${a.kind}] ${a.id} — ${a.state}${a.detail ? `: ${a.detail}` : ''}`);+ if (a.fix_argv && a.fix_argv.length > 0) out(` fix: ${a.fix_argv.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');+ }+}++function isLockError(err: unknown): boolean {+ return err instanceof Error && err.message.includes('Could not acquire PGLite lock');+}++export async function runBackupCli(+ args: string[],+ connect: () => Promise<BrainEngine>,+): Promise<BackupCliResult> {+ if (args.includes('--help') || args.includes('-h') || args.length === 0) {+ console.log(HELP);+ return { exitCode: 0 };+ }+ const sub = args[0];+ if (sub !== 'status' && sub !== 'check') {+ console.error(`Unknown backup subcommand: ${sub}\n\n${HELP}`);+ return { exitCode: 2 };+ }+ const json = args.includes('--json');+ const quiet = getCliOptions().quiet === true;++ const disabled = backupCheckDisabled();+ if (disabled && sub === 'check') {+ if (!quiet) console.error('backup check is disabled (GBRAIN_BACKUP_CHECK=0 or backup.check_enabled=false)');+ return { exitCode: 0 };+ }++ const cached = loadBackupStatus();+ let status: BackupStatus | null = cached;+ let lockNote: string | null = null;++ // status recomputes when the cached verdict is warn (a raw `git remote add`+ // fix must show up immediately) or stale/absent; check always recomputes.+ // A fresh ok cache answers `status` without touching the engine (no lock+ // risk). Disabled silences COMPUTE on both subcommands (the ops-doc+ // contract) — a disabled `status` is a cache-only reader.+ const stale = cached === null || isBackupStatusStale(cached);+ const needCompute = !disabled && (sub === 'check' || stale || cached?.overall === 'warn');+ if (disabled) lockNote = 'backup check disabled — verdict from cache only';+ if (needCompute) {+ try {+ const engine = await connect();+ try {+ status = await getBackupStatus(engine, {+ localGitProbes: true,+ computedBy: quiet ? 'spawn' : 'cli',+ forceRefresh: sub === 'check' || cached?.overall === 'warn',+ });+ } finally {+ try {+ await engine.disconnect();+ } catch {+ /* best-effort teardown */+ }+ }+ } catch (err) {+ if (isLockError(err)) {+ lockNote = cached+ ? `DB locked by serve — verdict from cache (${backupCacheAge(cached)}); it refreshes automatically within a day`+ : 'no cached verdict; DB locked by serve — it refreshes automatically within a day';+ status = cached;+ } else if (cached) {+ lockNote = `engine unavailable — verdict from cache (${backupCacheAge(cached)})`;+ status = cached;+ } else {+ throw err;+ }+ }+ }++ if (quiet) return { exitCode: 0 };++ if (!status) {+ console.log(lockNote ?? 'no backup verdict yet — run: gbrain backup check');+ return { exitCode: 0 };+ }++ if (json) {+ const payload = {+ ...status,+ recovery: {+ recoverable_repos: status.totals.recoverable_repos,+ pages_at_risk: status.totals.pages_at_risk,+ statement: recoveryStatement(status),+ },+ ...(lockNote ? { note: lockNote } : {}),+ };+ process.stdout.write(JSON.stringify(payload, null, 2) + '\n');+ } else {+ renderHuman(status, (l) => process.stdout.write(l + '\n'));+ if (lockNote) process.stdout.write(`note: ${lockNote}\n`);+ }++ // The output itself is never suppressed — only the other channels' budgets+ // learn about this impression (uniform global-cap enforcement in the gate).+ if (status.overall === 'warn' && !disabled) {+ try {+ backupNagGate('status', status).record();+ } catch {+ /* best-effort */+ }+ }+ // Disabled means silent for automation too: a stale warn cache that can+ // never refresh must not fail crons with exit 1.+ return { exitCode: disabled ? 0 : exitFor(status) };+}diff --git a/src/commands/config.ts b/src/commands/config.tsindex 07934cf0bf..112e3ff815 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -44,6 +44,18 @@ export function isSensitiveConfigKey(key: string): boolean {* Keep in sync with the `envFromConfig` mappings in* src/core/ai/build-gateway-config.ts.*/+/** Dotted keys that are FILE-plane canonical (nested under a group in+ * ~/.gbrain/config.json) — read by engine-free processes via+ * loadConfigFileOnly. ONE list for both the `set` and `unset` lanes so the+ * next key cannot be added to only one branch (which would silently route+ * `unset` to the DB plane). */+const FILE_PLANE_DOTTED_KEYS: ReadonlySet<string> = new Set([+ 'push.allow_unverified_remote',+ 'hooks.stop_push_debounce_min',+ 'backup.check_enabled',+ 'backup.check_interval_days',+]);+export const FILE_PLANE_API_KEYS: readonly string[] = ['openai_api_key','anthropic_api_key',@@ -121,10 +133,10 @@ export async function runConfig(engine: BrainEngine, args: string[]) {console.error('Usage: gbrain config unset <key> | --pattern <prefix>');process.exit(1);}- if (key === 'push.allow_unverified_remote' || key === 'hooks.stop_push_debounce_min') {+ if (FILE_PLANE_DOTTED_KEYS.has(key)) {const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');const cfg = loadConfigFileOnly();- const [top, leaf] = key.split('.') as ['push' | 'hooks', string];+ const [top, leaf] = key.split('.') as ['push' | 'hooks' | 'backup', string];const branch = cfg?.[top] as Record<string, unknown> | undefined;if (cfg && branch && leaf in branch) {delete branch[leaf];@@ -222,7 +234,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {// `sources push` child) via loadConfigFileOnly, which never sees the DB// plane — and the DB plane is unreadable anyway while a `gbrain serve`// holds the single-writer lock. Route them to ~/.gbrain/config.json.- if (key === 'push.allow_unverified_remote' || key === 'hooks.stop_push_debounce_min') {+ if (FILE_PLANE_DOTTED_KEYS.has(key)) {const { loadConfigFileOnly, saveConfig, isConfigTruthy } = await import('../core/config.ts');const cfg = (loadConfigFileOnly() ?? { engine: 'pglite' }) as Parameters<typeof saveConfig>[0];if (key === 'push.allow_unverified_remote') {@@ -237,6 +249,20 @@ export async function runConfig(engine: BrainEngine, args: string[]) {'gbrain config set push.allow_unverified_remote false',);}+ } else if (key === 'backup.check_enabled') {+ const on = isConfigTruthy(value);+ cfg.backup = { ...(cfg.backup ?? {}), check_enabled: on };+ saveConfig(cfg);+ console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);+ } else if (key === 'backup.check_interval_days') {+ const n = Number.parseInt(value, 10);+ if (!Number.isFinite(n) || n < 1) {+ console.error(`[config] ${key} must be an integer >= 1 (days between automatic backup checks)`);+ process.exit(1);+ }+ cfg.backup = { ...(cfg.backup ?? {}), check_interval_days: n };+ saveConfig(cfg);+ console.log(`Set ${key} = ${n} (file plane: ~/.gbrain/config.json)`);} else {const n = Number.parseInt(value, 10);if (!Number.isFinite(n) || n < 0) {diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 89cdefaf5b..a44ee9bf9d 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -3877,6 +3877,13 @@ export async function buildChecks(// default (false) — that's the trust-boundary preservation Codex// P0-1 flagged.checks.push(await checkSyncFreshness(engine, { localOnly: true }));+ // Monthly backup-coverage check (same D4 trust stance as sync_freshness:+ // localOnly:true probes git; the remote path stays a cache-only reader).+ progress.heartbeat('backup_coverage');+ {+ const { checkBackupCoverage } = await import('./doctor/checks/backup-coverage.ts');+ checks.push(await checkBackupCoverage(engine, { localOnly: true }));+ }// v0.41.19.0 (Issue 5): sync --all consolidation nudge.progress.heartbeat('sync_consolidation');checks.push(await checkSyncConsolidation(engine));diff --git a/src/commands/doctor/checks/backup-coverage.ts b/src/commands/doctor/checks/backup-coverage.tsnew file mode 100644index 0000000000..3fc0d217e2--- /dev/null+++ b/src/commands/doctor/checks/backup-coverage.ts@@ -0,0 +1,107 @@+/**+ * doctor/checks/backup-coverage.ts — `backup_coverage`: is the user's brain ++ * skills backed up to a git remote at all? Sibling of `bootstrap_push_health`+ * (which owns staleness of an EXISTING remote); this check owns ABSENCE.+ *+ * Trust boundary (D4): git probes against DB-supplied local_path run only on+ * the trusted local doctor path (`localOnly: true`, the checkSyncFreshness+ * precedent at doctor.ts). Without it the check is a cache-only reader.+ */++import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { getBackupStatus } from '../../../core/backup/coverage.ts';+import {+ backupCacheAge,+ backupCheckDisabled,+ loadBackupStatus,+ type BackupStatus,+} from '../../../core/backup/status-file.ts';++function toCheck(s: BackupStatus, note?: string): Check {+ const details = {+ totals: s.totals,+ checked_at: s.checked_at,+ computed_by: s.computed_by,+ cache_age: backupCacheAge(s),+ ...(note ? { note } : {}),+ };+ if (s.overall === 'warn') {+ const ids = s.assets+ .filter((a) => a.state === 'no_remote')+ .map((a) => a.id)+ .join(', ');+ return {+ name: 'backup_coverage',+ status: 'warn',+ message:+ `${s.totals.no_remote} knowledge asset(s) have no git remote — local-only, unrecoverable on disk loss: ${ids}. ` ++ 'Run `gbrain backup status` for fix commands (`gbrain bootstrap repo` / `git remote add origin <url>` / `gbrain sources harden <id>`).',+ details,+ };+ }+ return {+ name: 'backup_coverage',+ status: 'ok',+ message: `${s.totals.recoverable_repos} knowledge repo(s) git-backed; last checked ${backupCacheAge(s)}`,+ details,+ };+}++export async function checkBackupCoverage(+ engine: BrainEngine,+ opts: { localOnly?: boolean; now?: Date } = {},+): Promise<Check> {+ if (backupCheckDisabled()) {+ return {+ name: 'backup_coverage',+ status: 'ok',+ message: 'backup check disabled (backup.check_enabled=false or GBRAIN_BACKUP_CHECK=0)',+ };+ }+ if (!opts.localOnly) {+ // Remote surface: cache-only AND aggregate-only. toCheck's warn message+ // names asset ids (local paths for workspace assets) — that is local-owner+ // detail; a remote reader gets counts, never identifiers (the same+ // amendment-29 discipline as backupNoticeText's 'aggregate' surface).+ const cached = loadBackupStatus();+ if (!cached) {+ return {+ name: 'backup_coverage',+ status: 'ok',+ message: 'not checked from this surface — run `gbrain backup check` on the brain host',+ };+ }+ const details = {+ totals: cached.totals,+ checked_at: cached.checked_at,+ cache_age: backupCacheAge(cached),+ note: 'cache-only (remote surface never probes git; aggregate counts only)',+ };+ 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 — ` ++ 'run `gbrain backup status` on the brain host for the per-asset detail and fix commands.',+ details,+ }+ : {+ name: 'backup_coverage',+ status: 'ok',+ message: `${cached.totals.recoverable_repos} knowledge repo(s) git-backed; last checked ${backupCacheAge(cached)}`,+ details,+ };+ }+ try {+ const s = await getBackupStatus(engine, {+ localGitProbes: true,+ computedBy: 'doctor',+ ...(opts.now ? { now: opts.now } : {}),+ });+ return toCheck(s);+ } catch {+ return { name: 'backup_coverage', status: 'warn', message: 'backup coverage unreadable' };+ }+}diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 6cb4d4a193..67bec9f24b 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -89,6 +89,15 @@ import {summarizePushStatuses,workspaceRootHash,} from '../core/workspace-push.ts';+import {+ backupCheckDisabled,+ backupNagGate,+ backupNoticeText,+ backupSpawnDue,+ isBackupStatusStale,+ loadBackupStatus,+ recordBackupSpawn,+} from '../core/backup/status-file.ts';import { realpathOrResolve } from '../core/path-confine.ts';// ── Tunables ────────────────────────────────────────────────────────────────@@ -167,6 +176,8 @@ export interface HookIo {* gated bootstrap workspace root; throwing marks the push unavailable.*/spawnPush?: (root: string) => void;+ /** TEST SEAM: detached backup-check spawner (default spawnDetachedBackupCheck). */+ spawnBackupCheck?: () => void;/** TEST SEAM: user-prompt deadline override (wall-clock flake control). */userPromptDeadlineMs?: number;/** TEST SEAM: compact deadline override (drives the per-step degrade paths). */@@ -446,6 +457,9 @@ async function hookSessionStart(io: HookIo): Promise<number> {let outcome: HookHeartbeatEntry['outcome'] = 'ok';let reason: string | undefined;const out: string[] = [];+ // Deferred nag records: fire ONLY after the digest actually reached stdout+ // (record-after-write — a deadline-suppressed note must re-fire next time).+ const deferredRecords: Array<() => void> = [];try {const j = await readStdinJson(io, 250);@@ -464,6 +478,14 @@ async function hookSessionStart(io: HookIo): Promise<number> {const pushNote = await pushStatusNote();if (pushNote) out.push(pushNote);+ // 3b. Monthly backup-coverage note (cache read; bounded by the shared+ // nag gate — dampener + per-channel ceiling + global monthly cap).+ const backupNote = backupSessionStartNote();+ if (backupNote) {+ out.push(backupNote.text);+ deferredRecords.push(backupNote.record);+ }+// 4. Visible degradation [B3] + parser-drift status file [G3].const failNote = await hookFailureNotice();if (failNote) out.push(failNote);@@ -532,7 +554,16 @@ async function hookSessionStart(io: HookIo): Promise<number> {// Print whatever accumulated before the deadline — a partial digest// beats an empty one (the deadline bounds latency, not usefulness).const text = out.filter(Boolean).join('\n\n');- if (text) write(io, text + '\n');+ if (text) {+ write(io, text + '\n');+ for (const record of deferredRecords) {+ try {+ record();+ } catch {+ /* fail-open — worst case the note re-fires */+ }+ }+ }} catch (e) {outcome = 'error';reason = errorCode(e); // fail-open: empty stdout, exit 0@@ -986,6 +1017,65 @@ function pendingPushFailureBanner(): { text: string; record: () => void } | null}}+// ── monthly backup-coverage notices (cache readers; engine-free) ────────────++/**+ * Shared body for the two hook-borne backup notices: cache read + the shared+ * nag gate on the given channel; the returned record() is deferred until the+ * text actually reached stdout (record-after-write). backupNoticeText already+ * caps the body at its 300-char budget — the short prefix on top stays far+ * inside the payload cap, so no second slice (a slice here chopped the+ * trailing call-to-action).+ */+function backupHookNotice(channel: string, prefix: string): { text: string; record: () => void } | null {+ try {+ if (backupCheckDisabled()) return null;+ const s = loadBackupStatus();+ if (!s || s.overall !== 'warn') return null;+ const gate = backupNagGate(channel, s);+ if (!gate.show) return null;+ const t = backupNoticeText(s, 'human');+ if (!t) return null;+ return { text: `${prefix}${t}`, record: gate.record };+ } catch {+ return null;+ }+}++/** Session-start digest note ('hook-note' channel). */+function backupSessionStartNote(): { text: string; record: () => void } | null {+ return backupHookNotice('hook-note', 'Backup check: ');+}++/**+ * The backup banner for the user-prompt payload ('hook-banner' channel). Same+ * delivery rail as the push-failure banner (systemMessage + additionalContext);+ * the push failure wins the single banner slot — this one only fires when no+ * push failure is pending.+ */+function pendingBackupBanner(): { text: string; record: () => void } | null {+ return backupHookNotice('hook-banner', 'NOTICE: ');+}++/**+ * Fire-and-forget `gbrain backup check --quiet` as a DETACHED child (the+ * spawnDetachedPush pattern). The child re-resolves everything itself and+ * exits 0 silently when the PGLite lock is held by a live serve — that+ * install is covered by the serve-side refresher instead.+ */+function spawnDetachedBackupCheck(): void {+ const exec = process.execPath ?? '';+ const checkArgs = ['backup', 'check', '--quiet'];+ const argv = /[/\\]gbrain(\.exe)?$/.test(exec) ? checkArgs : [process.argv[1], ...checkArgs];+ const child = spawn(exec, argv, {+ detached: true,+ stdio: 'ignore',+ env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },+ });+ child.on('error', () => {});+ child.unref();+}+// ── user-prompt [ENG-1, S3#8, A9] ───────────────────────────────────────────interface UserPromptOutcome {@@ -1012,7 +1102,10 @@ async function hookUserPrompt(io: HookIo): Promise<number> {let wrotePayload = false;const work = (async (): Promise<UserPromptOutcome> => {- banner = io.disablePushBanner ? null : pendingPushFailureBanner();+ // Push failure wins the single banner slot; the monthly backup notice+ // rides the same rail (systemMessage + additionalContext) when no push+ // failure is pending. Both are cache/file readers, budgeted by the race.+ banner = io.disablePushBanner ? null : (pendingPushFailureBanner() ?? pendingBackupBanner());const j = await readStdinJson(io, 300);if (!j) return { outcome: 'degraded', reason: 'no_stdin' };@@ -1536,6 +1629,21 @@ async function hookSessionEnd(io: HookIo): Promise<number> {/* best effort */}+ // Monthly backup-coverage recompute — detached, 24h-debounced via the nag+ // state file (no sidecar). Covers hooks-without-serve installs; a serve+ // holding the PGLite lock makes the child a benign no-op (exit 0, no cache+ // write) and the serve refresher owns that install instead.+ try {+ if (!backupCheckDisabled() && backupSpawnDue() && isBackupStatusStale(loadBackupStatus())) {+ // Recorded BEFORE the spawn (the stop-push precedent) so repeated+ // fail-fast children stay debounced.+ recordBackupSpawn();+ (io.spawnBackupCheck ?? spawnDetachedBackupCheck)();+ }+ } catch {+ /* best effort */+ }+// GC this session's stop buffer [G15].try {const dir = await liveBufferDir();diff --git a/src/commands/sources-harden.ts b/src/commands/sources-harden.tsindex c66dbd2556..692fccd2a3 100644--- a/src/commands/sources-harden.ts+++ b/src/commands/sources-harden.ts@@ -19,6 +19,7 @@ import {} from '../core/brain-repo-durability.ts';import { divergenceSafePull, detectDefaultBranch, isInsideGitRepo } from '../core/git-remote.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { invalidateBackupStatus } from '../core/backup/status-file.ts';import { existsSync } from 'fs';import { join } from 'path';@@ -108,6 +109,10 @@ export async function runHarden(engine: BrainEngine, args: string[]): Promise<voif (json) console.log(JSON.stringify({ reports }, null, 2));+ // Fix-path invalidation: hardening changes the backup-coverage answer for+ // every touched repo — drop the cached verdict so the next check re-probes.+ if (reports.length > 0) invalidateBackupStatus();+// Non-zero exit if any source needs attention, so cron/automation notices.// Route through setCliExitVerdict — a raw process.exitCode write is zeroed by// the owned-verdict flush-exit (#2084 / PGLite-Emscripten pollution defense).diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 8084f0c4cf..2b5c2b9712 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -5022,6 +5022,8 @@ See also:// v0.42.7 (#1696): brain-wide extraction-lag nudge after the --all wave.// Best-effort, stderr-only; skipped on dry-run.if (!dryRun) await maybeExtractionNudge(engine);+ // Monthly backup-coverage stale-only refresh (trusted local engine holder).+ if (!dryRun) await maybeBackupCoverageRefresh(engine);// #3068: any source wedged on a failed pull (partial/pull_failed) makes// the whole --all run non-zero — it will not self-heal on retry, so a@@ -5137,6 +5139,10 @@ See also:// — NOT just 'synced'; a fresh/--full import (`first_sync`) is the biggest// un-extracted backlog. Scoped to this source; best-effort, stderr-only.if (shouldNudgeAfterSync(result.status)) await maybeExtractionNudge(engine, sourceId);+ // Monthly backup-coverage: the sync CLI legitimately holds the engine+ // (trusted local), so the stale-only compute piggybacks here — covering+ // active CLI users without any serve involvement. Dry-run stays pure.+ if (result.status !== 'dry_run') await maybeBackupCoverageRefresh(engine);// Issue #2 + eng-review pass-2 finding #1 + Codex P1: manage .gitignore ONLY// on successful sync. Skip on dry-run (don't mutate disk in preview mode)// and blocked_by_failures (sync state is inconsistent — defer .gitignore@@ -5545,6 +5551,25 @@ export function manageGitignore(}}+/**+ * Post-sync backup-coverage refresh (monthly, stale-only). The sync CLI is a+ * trusted local engine holder (D4), so the compute piggybacks here; the+ * shared choke point (getBackupStatus) makes a fresh cache a no-op file read.+ * Best-effort — never blocks or fails a sync.+ */+async function maybeBackupCoverageRefresh(engine: BrainEngine): Promise<void> {+ try {+ const { backupCheckDisabled, isBackupStatusStale, loadBackupStatus } = await import(+ '../core/backup/status-file.ts'+ );+ if (backupCheckDisabled() || !isBackupStatusStale(loadBackupStatus())) return;+ const { getBackupStatus } = await import('../core/backup/coverage.ts');+ await getBackupStatus(engine, { localGitProbes: true, computedBy: 'sync' });+ } catch {+ /* best-effort — never block sync on it */+ }+}+/*** v0.42.7 (#1696): one-line end-of-sync nudge when the brain (or a source)* carries a meaningful link/timeline extraction backlog. Reuses the same warndiff --git a/src/core/advisor/collect-backup-coverage.ts b/src/core/advisor/collect-backup-coverage.tsnew file mode 100644index 0000000000..5f781d2382--- /dev/null+++ b/src/core/advisor/collect-backup-coverage.ts@@ -0,0 +1,117 @@+/**+ * advisor/collect-backup-coverage.ts — surfaces the monthly backup-coverage+ * verdict ("which knowledge repos have no git remote?") as advisor findings.+ *+ * Local runs (trusted CLI owner) refresh the verdict through the shared+ * choke point getBackupStatus (stale-only recompute keeps the collector+ * cron-safe; a fresh cache makes this a file read) and emit per-asset+ * findings with fix commands, gated as ONE batch through backupNagGate so+ * the advisor participates in the same bounded-nag budget as every other+ * channel. Remote runs are cache-readers with aggregate counts ONLY+ * (amendment-29 discipline — never a local path or source id) and never+ * write nag state.+ */++import { getBackupStatus } from '../backup/coverage.ts';+import { backupCheckDisabled, backupNagGate, loadBackupStatus } from '../backup/status-file.ts';+import type { AdvisorCollector, AdvisorFinding } from './types.ts';++export const collectBackupCoverage: AdvisorCollector = {+ id: 'backup-coverage',+ collect: async (ctx) => {+ // The off switch silences compute AND every render channel (the ops-doc+ // contract) — including this collector, on both the local compute branch+ // and the remote cache-read branch.+ if (backupCheckDisabled()) return [];+ const findings: AdvisorFinding[] = [];+ const local = !ctx.remote;++ 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 [];+ 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.`,+ fix: { command_argv: null },+ collector: 'backup-coverage',+ ask_user: true,+ });+ return findings;+ }++ const s = await getBackupStatus(ctx.engine, {+ localGitProbes: true,+ computedBy: 'advisor',+ now: ctx.now,+ });+ if (s.overall !== 'warn') return [];++ // One gate for the whole batch (the verdict fingerprint covers the set);+ // recording at collect time matches the collect-mcp-client-fit precedent.+ const gate = backupNagGate('advisor', s, ctx.now.getTime());+ if (!gate.show) return [];++ for (const a of s.assets) {+ if (a.state === 'no_remote' && a.kind === 'source_repo') {+ findings.push({+ id: `backup_source_no_remote:${a.id}`,+ severity: 'warn',+ title: `Knowledge repo ${a.id} has no git remote — a disk loss loses it.`,+ detail: a.detail,+ fix: { command_argv: a.fix_argv ?? null },+ collector: 'backup-coverage',+ ask_user: true,+ });+ } else if (a.state === 'no_remote' && a.kind === 'bootstrap_workspace') {+ findings.push({+ id: 'backup_workspace_no_repo',+ severity: 'warn',+ title: 'Your agent workspace has no private repo yet — a disk loss loses skills, memory, and identity.',+ detail: a.detail,+ fix: { command_argv: a.fix_argv ?? ['gbrain', 'bootstrap', 'repo'] },+ collector: 'backup-coverage',+ ask_user: true,+ });+ } else if (a.state === 'no_remote' && a.kind === 'db_content') {+ findings.push({+ id: 'backup_db_content_unbacked',+ severity: 'warn',+ title: 'Your brain lives only in the local database — nothing is git-backed.',+ detail: a.detail,+ fix: { command_argv: a.fix_argv ?? ['gbrain', 'bootstrap', 'repo'] },+ collector: 'backup-coverage',+ ask_user: true,+ });+ }+ }+ const unpushed = s.assets.filter((a) => a.state === 'unpushed');+ if (unpushed.length > 0) {+ findings.push({+ id: 'backup_unpushed_work',+ severity: 'info',+ title: `${unpushed.length} repo(s) have commits not yet on their remote.`,+ detail: unpushed.map((a) => `${a.id}: ${a.detail ?? 'ahead of origin'}`).join('; '),+ fix: { command_argv: null },+ collector: 'backup-coverage',+ ask_user: true,+ });+ }+ if (s.assets.some((a) => a.kind === 'db_only')) {+ findings.push({+ id: 'backup_db_only_caveat',+ severity: 'info',+ title: 'db_only pages are not covered by any git remote — dump them with gbrain export.',+ detail: 'run gbrain doctor (undeclared_db_only_pages) for the page-level audit',+ fix: { command_argv: null },+ collector: 'backup-coverage',+ ask_user: true,+ });+ }++ if (findings.length > 0) gate.record();+ return findings;+ },+};diff --git a/src/core/advisor/run.ts b/src/core/advisor/run.tsindex 5d76696a2b..12976f91e4 100644--- a/src/core/advisor/run.ts+++ b/src/core/advisor/run.ts@@ -18,6 +18,7 @@ import { collectUninstalledBrainPack } from './collect-uninstalled-brain-pack.tsimport { collectUninstalledBundled } from './collect-uninstalled-bundled.ts';import { collectChronicle } from './collect-chronicle.ts';import { collectMcpClientFit } from './collect-mcp-client-fit.ts';+import { collectBackupCoverage } from './collect-backup-coverage.ts';/** Deterministic v1 collector order (also the secondary sort key for ranking). */export const COLLECTORS: AdvisorCollector[] = [@@ -31,6 +32,7 @@ export const COLLECTORS: AdvisorCollector[] = [collectUninstalledBundled,collectChronicle,collectMcpClientFit,+ collectBackupCoverage,];const SEV_RANK: Record<AdvisorSeverity, number> = { critical: 0, warn: 1, info: 2 };diff --git a/src/core/backup/coverage.ts b/src/core/backup/coverage.tsnew file mode 100644index 0000000000..b75cc57efe--- /dev/null+++ b/src/core/backup/coverage.ts@@ -0,0 +1,571 @@+/**+ * backup/coverage.ts — engine-side compute for the monthly backup-coverage+ * check. Answers "if this disk died right now, could the user recreate their+ * agent?" across every asset class gbrain knows about, and persists the+ * verdict to the engine-free cache in backup/status-file.ts.+ *+ * Trust boundary (D4, extraction-sync.ts:870): git subprocesses against+ * DB-supplied local_path values run ONLY when the caller passes+ * `localGitProbes: true` — trusted-local contexts (CLI, local doctor/advisor,+ * sync completion, the detached spawn) and the STDIO serve refresher (see+ * maybeRefreshBackupStatusInProcess below). Probe-less computes are NEVER+ * persisted: a probe-less write would clobber a probed verdict (reset+ * checked_at, mutate the nag fingerprint, silence a real warn).+ *+ * Probes are local READ subcommands only (`remote get-url`,+ * `status --porcelain`, `rev-list --count`) via execFile array args — never+ * fetch/push/network. Per-repo failures degrade that asset to 'unknown';+ * a failed compute never clobbers an existing cache (getBackupStatus).+ */++import { existsSync } from 'node:fs';+import { execFileSync } from 'node:child_process';++import { VERSION } from '../../version.ts';+import type { BrainEngine } from '../engine.ts';+import { loadAllSources } from '../sources-load.ts';+import { discoverGitRoot } from '../sync-git.ts';+import { GIT_ENV, detectDefaultBranch, isWorkingTreeDirty } from '../git-remote.ts';+import { aheadCount, readPushStatusForRoot } from '../workspace-push.ts';+import { sanitizePushReason } from '../workspace-push.ts';+import { realpathOrResolve } from '../path-confine.ts';+import { resolveBrainId } from '../brain-resolver.ts';+import { readManifest, readReceipt } from '../bootstrap/format.ts';+import { resolveGbrainHome } from '../gbrain-home.ts';+import { loadBridgeState } from '../skillpack/bridge-state.ts';+import { loadStorageConfig } from '../storage-config.ts';+import {+ BACKUP_INTERVAL_DAYS_DEFAULT,+ BACKUP_STATUS_SCHEMA_VERSION,+ backupCheckDisabled,+ backupIntervalMs,+ isBackupStatusStale,+ loadBackupStatus,+ saveBackupStatus,+ type BackupAssetVerdict,+ type BackupComputedBy,+ type BackupStatus,+} from './status-file.ts';++/** No silent caps: at most this many deduped git roots are probed per run;+ * anything beyond is logged as skipped. */+export const BACKUP_PROBE_ROOT_CAP = 500;++export interface BackupCoverageOpts {+ now?: Date;+ /**+ * Trust gate (D4): true only in trusted-local contexts. When false, source+ * repos come back 'unknown' and the result is NEVER persisted.+ */+ localGitProbes: boolean;+ /** Provenance stamp for the status file (default 'cli'). */+ computedBy?: BackupComputedBy;+}++const RECIPE_DETAIL =+ 'fix: git remote add origin <url> && git push -u origin <branch>, then gbrain sources harden <id>';++function pushAsset(assets: BackupAssetVerdict[], a: BackupAssetVerdict): void {+ assets.push(a);+}++/**+ * Event-loop yield between synchronous git probes. The probe helpers are+ * execFileSync (10-30s timeouts each); in the stdio-serve refresher this+ * compute runs on the MCP server's loop, so without yields a multi-repo brain+ * would freeze ALL tool dispatch for the duration of the sweep. A yield before+ * EACH probe bounds the stall to one subprocess (worst case one subprocess+ * timeout on a wedged repo — accepted residual; the compute is at most daily).+ */+function yieldLoop(): Promise<void> {+ return new Promise((r) => setTimeout(r, 0));+}++/**+ * POSITIVE origin determination. `hasOriginRemote` (sync-git) collapses every+ * failure to `false`, which would turn a git timeout / wedged mount into a+ * false "no remote — a disk loss loses them" warn persisted for a month.+ * Exit code 2 is git's documented "no such remote"; anything else that throws+ * is a probe failure ('unknown').+ */+function originRemoteState(root: string): 'present' | 'absent' | 'unknown' {+ try {+ execFileSync('git', ['-C', root, 'remote', 'get-url', 'origin'], {+ encoding: 'utf-8',+ timeout: 15_000,+ stdio: ['ignore', 'pipe', 'pipe'],+ env: GIT_ENV,+ });+ return 'present';+ } catch (err) {+ const status = (err as { status?: number }).status;+ return status === 2 ? 'absent' : 'unknown';+ }+}++/**+ * Does the remote-tracking ref origin/<branch> exist locally? false = the+ * remote has NOTHING pushed for this branch (the half-completed `git remote+ * add` state — zero recoverable history); null = probe failure.+ */+function hasRemoteTrackingRef(root: string, branch: string): boolean | null {+ try {+ execFileSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`], {+ encoding: 'utf-8',+ timeout: 15_000,+ stdio: ['ignore', 'pipe', 'ignore'],+ env: GIT_ENV,+ });+ return true;+ } catch (err) {+ const status = (err as { status?: number }).status;+ // --quiet --verify exits 1 when the ref does not exist; other failures+ // (timeout, spawn error) are indeterminate.+ return status === 1 ? false : null;+ }+}++/** null = the count could not be established (engine down / schema quirk). */+async function countLivePages(engine: BrainEngine): Promise<number | null> {+ try {+ const rows = await engine.executeRaw<{ n: number }>(+ 'SELECT COUNT(*)::int AS n FROM pages WHERE deleted_at IS NULL',+ );+ const n = rows[0]?.n;+ // An empty rowset / non-numeric n is UNESTABLISHED, not zero — returning 0+ // would fabricate a "no pages at risk" all-clear and skip the degraded flag.+ return typeof n === 'number' && Number.isFinite(n) ? n : null;+ } catch {+ return null;+ }+}++export async function computeBackupCoverage(+ engine: BrainEngine,+ opts: BackupCoverageOpts,+): Promise<BackupStatus> {+ const now = opts.now ?? new Date();+ const assets: BackupAssetVerdict[] = [];++ // ── Bootstrap workspace (carries skills/, memory/, brain/, identity) ──────+ // File plane only — no git subprocess needed here.+ let workspaceRoot: string | null = null;+ let receiptHasRepo = false;+ try {+ const home = resolveGbrainHome();+ const receipt = readReceipt(home);+ if (receipt) {+ // Normalized for the source-root dedup compare below — git prints a+ // resolved toplevel, so a symlinked/trailing-slash receipt path must+ // not double-count the workspace as a second asset.+ workspaceRoot = realpathOrResolve(receipt.workspace_dir);+ receiptHasRepo = typeof receipt.repo_url === 'string' && receipt.repo_url.length > 0;+ if (!receiptHasRepo) {+ pushAsset(assets, {+ kind: 'bootstrap_workspace',+ id: receipt.workspace_dir,+ state: 'no_remote',+ detail: 'bootstrap workspace has no private repo yet',+ fix_argv: ['gbrain', 'bootstrap', 'repo'],+ });+ } else {+ // THIS workspace's own push status only — a failing entry from some+ // other push-tracked repo must not be misattributed to the workspace.+ const own = readPushStatusForRoot(receipt.workspace_dir);+ if (own && own.ok === false) {+ pushAsset(assets, {+ kind: 'bootstrap_workspace',+ id: receipt.workspace_dir,+ state: 'failing',+ detail: sanitizePushReason(own.reason),+ fix_argv: ['gbrain', 'sources', 'push', '--path', receipt.workspace_dir],+ });+ } else {+ pushAsset(assets, { kind: 'bootstrap_workspace', id: receipt.workspace_dir, state: 'ok' });+ }+ }+ }+ } catch {+ /* no receipt / unreadable home — the source sweep below stands alone */+ }++ // ── Source repos (deduped by git root) ────────────────────────────────────+ let sourceRootCount = 0;+ let degraded = false;+ try {+ const rows = await loadAllSources(engine);+ const byRoot = new Map<string, { ids: string[]; dbOnly: boolean }>();+ let skippedOverCap = 0;+ // Root discovery is itself a git subprocess — memoize per local_path, count+ // it against the probe cap, skip it entirely on probe-less runs (their+ // assets are 'unknown' either way and probe-less results never persist).+ const rootByPath = new Map<string, string | null>();+ let discoveries = 0;+ for (const row of rows) {+ if (row.archived) 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, {+ kind: 'source_repo',+ id: row.id,+ state: 'unknown',+ detail: 'local_path not found on this machine',+ fix_argv: null,+ });+ continue;+ }+ let root: string;+ if (!opts.localGitProbes) {+ root = row.local_path; // group by raw path — no subprocess on untrusted paths+ } else if (rootByPath.has(row.local_path)) {+ 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 });+ continue;+ }+ root = memo;+ } else if (discoveries >= BACKUP_PROBE_ROOT_CAP) {+ skippedOverCap++;+ pushAsset(assets, { kind: 'source_repo', id: row.id, state: 'unknown', detail: 'probe_cap', fix_argv: null });+ continue;+ } else {+ discoveries++;+ await yieldLoop();+ try {+ root = discoverGitRoot(row.local_path);+ 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,+ });+ continue;+ }+ }+ if (root === workspaceRoot) continue; // the workspace asset above owns it+ const entry = byRoot.get(root);+ let dbOnly = false;+ try {+ dbOnly = (loadStorageConfig(row.local_path)?.db_only?.length ?? 0) > 0;+ } catch {+ /* storage config unreadable — treat as no db_only tiering */+ }+ if (entry) {+ entry.ids.push(row.id);+ entry.dbOnly = entry.dbOnly || dbOnly;+ } else {+ byRoot.set(root, { ids: [row.id], dbOnly });+ }+ // db_only exposure rides as its own info asset (per source repo).+ if (dbOnly) {+ pushAsset(assets, {+ kind: 'db_only',+ id: row.id,+ state: 'info',+ detail:+ 'db_only dirs configured: those pages are not in git and the DB file is deliberately not backed up. ' ++ 'Dump them somewhere OUTSIDE the gitignored dirs (--restore-only is the wrong direction for a backup); ' ++ 'run gbrain doctor (undeclared_db_only_pages) for the page-level audit.',+ fix_argv: ['gbrain', 'export', '--dir', '<backup-dir>'],+ });+ }+ }++ sourceRootCount = byRoot.size;+ let probed = 0;+ for (const [root, { ids }] of byRoot) {+ const id = ids.join(', ');+ if (!opts.localGitProbes) {+ pushAsset(assets, { kind: 'source_repo', id, state: 'unknown', detail: 'probes_skipped', fix_argv: null });+ continue;+ }+ if (probed >= BACKUP_PROBE_ROOT_CAP) {+ skippedOverCap++;+ pushAsset(assets, { kind: 'source_repo', id, state: 'unknown', detail: 'probe_cap', fix_argv: null });+ continue;+ }+ probed++;+ try {+ // "No origin" must be a POSITIVE determination — a probe failure+ // (timeout, wedged mount) is 'unknown', never a false "a disk loss+ // loses them" warn persisted for a month.+ await yieldLoop();+ const origin = originRemoteState(root);+ if (origin === 'unknown') {+ pushAsset(assets, { kind: 'source_repo', id, state: 'unknown', detail: 'probe_failed', fix_argv: null });+ continue;+ }+ if (origin === 'absent') {+ // Bootstrap-initialized roots get the mechanical fix; plain repos+ // get the recipe in detail (no single mechanical fix — argv null).+ let initialized = false;+ try {+ initialized = readManifest(root).state === 'initialized';+ } catch {+ /* manifest unreadable — plain-repo recipe */+ }+ pushAsset(assets, {+ kind: 'source_repo',+ id,+ state: 'no_remote',+ detail: RECIPE_DETAIL,+ fix_argv: initialized ? ['gbrain', 'bootstrap', 'repo'] : null,+ });+ continue;+ }+ await yieldLoop();+ const branch = detectDefaultBranch(root);+ // A remote with NOTHING pushed is not a backup: origin/<branch>+ // unresolvable means zero recoverable history — that is the+ // half-completed `git remote add` state and it must WARN, not read ok.+ if (hasRemoteTrackingRef(root, branch) === false) {+ pushAsset(assets, {+ kind: 'source_repo',+ id,+ state: 'no_remote',+ detail: `remote configured but nothing pushed (origin/${branch} not found) — run: git push -u origin ${branch}`,+ fix_argv: null,+ });+ continue;+ }+ await yieldLoop();+ const ahead = aheadCount(root, branch);+ if (ahead === undefined) {+ pushAsset(assets, { kind: 'source_repo', id, state: 'unknown', detail: 'probe_failed', fix_argv: null });+ continue;+ }+ if (ahead > 0) {+ pushAsset(assets, {+ kind: 'source_repo',+ id,+ state: 'unpushed',+ ahead,+ detail: `${ahead} commit(s) ahead of origin/${branch}`,+ fix_argv: null,+ });+ continue;+ }+ await yieldLoop();+ let dirty = false;+ try {+ dirty = isWorkingTreeDirty(root);+ } catch {+ /* dirtiness probe failure is not worth degrading the asset */+ }+ pushAsset(+ assets,+ dirty+ ? { kind: 'source_repo', id, state: 'dirty', detail: 'uncommitted changes', fix_argv: null }+ : { kind: 'source_repo', id, state: 'ok' },+ );+ } catch {+ pushAsset(assets, { kind: 'source_repo', id, state: 'unknown', detail: 'probe_failed', fix_argv: null });+ }+ }+ if (skippedOverCap > 0) {+ process.stderr.write(+ `[backup] probe cap: ${skippedOverCap} git root(s) beyond ${BACKUP_PROBE_ROOT_CAP} were not probed this run\n`,+ );+ }+ } catch {+ // Sources unreadable (engine down / legacy schema): the verdict is+ // DEGRADED — it must never overwrite a probed cache (getBackupStatus).+ degraded = true;+ }++ // ── Harness-native skill dirs (installed COPIES — info only) ──────────────+ try {+ const bridge = loadBridgeState();+ if (bridge.entries.length > 0) {+ pushAsset(assets, {+ kind: 'harness_skills',+ id: `${bridge.entries.length} harness skill dir(s)`,+ state: 'info',+ detail: 'installed copies; the originals live in brain/skill repos and are covered above',+ fix_argv: null,+ });+ }+ } catch {+ /* bridge state unreadable — cosmetic row only */+ }++ // ── DB-only brain (the worst-case user) ───────────────────────────────────+ // Pages exist but nothing is git-backed: on PGLite that is total loss on a+ // disk failure; on managed Postgres the DB survives by construction, but it+ // still isn't the git system of record.+ const pageCountRaw = await countLivePages(engine);+ if (pageCountRaw === null) degraded = true;+ const pageCount = pageCountRaw ?? 0;+ const hasGitBackedAsset = assets.some(+ (a) => a.kind === 'source_repo' || (a.kind === 'bootstrap_workspace' && a.state !== 'no_remote'),+ );+ let pagesAtRisk = 0;+ if (!degraded && pageCount > 0 && sourceRootCount === 0 && !hasGitBackedAsset && workspaceRoot === null) {+ if (engine.kind === 'postgres') {+ pushAsset(assets, {+ kind: 'db_content',+ id: 'brain database',+ state: 'info',+ detail:+ `your DB is remote (${pageCount} pages survive a disk loss), but it isn't the git system of record — ` ++ 'add a source repo (gbrain sources add) or dump with gbrain export',+ fix_argv: ['gbrain', 'bootstrap', 'repo'],+ });+ } else {+ pagesAtRisk = pageCount;+ pushAsset(assets, {+ kind: 'db_content',+ id: 'brain database',+ state: 'no_remote',+ detail: `${pageCount} pages live ONLY in the local DB — a disk loss loses all of them (gbrain sources add / gbrain bootstrap repo)`,+ fix_argv: ['gbrain', 'bootstrap', 'repo'],+ });+ }+ }++ const totals = {+ assets: assets.length,+ no_remote: assets.filter((a) => a.state === 'no_remote').length,+ unpushed: assets.filter((a) => a.state === 'unpushed').length,+ failing: assets.filter((a) => a.state === 'failing').length,+ recoverable_repos: assets.filter(+ (a) =>+ (a.kind === 'source_repo' || a.kind === 'bootstrap_workspace') &&+ a.state !== 'no_remote' &&+ a.state !== 'unknown' &&+ // A failing push means the remote is BEHIND — counting it recoverable+ // would overstate the recovery statement.+ a.state !== 'failing',+ ).length,+ pages_at_risk: pagesAtRisk,+ };++ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: now.toISOString(),+ gbrain_version: VERSION,+ interval_days: Math.round(backupIntervalMs() / (24 * 60 * 60 * 1000)) || BACKUP_INTERVAL_DAYS_DEFAULT,+ computed_by: opts.computedBy ?? 'cli',+ overall: totals.no_remote > 0 ? 'warn' : 'ok',+ totals,+ assets,+ ...(degraded ? { degraded: true } : {}),+ };+}++/**+ * The single choke point every compute site routes through: a fresh cache is+ * returned as-is; a stale/absent one triggers a compute. Probed results are+ * persisted; probe-less results are NOT (see module header). A failed compute+ * never clobbers an existing cache — the prior verdict is returned instead.+ */+/**+ * True when this process is operating on the HOST brain. The status cache is+ * host-scoped (~/.gbrain/backup-status.json has no brain dimension), so a+ * compute against a mounted brain (--brain flag threaded by the caller, or+ * GBRAIN_BRAIN_ID / a .gbrain-mount dotfile picked up by a detached spawn)+ * must neither read nor write the host cache — an empty mounted brain's `ok`+ * silencing a real host warn is cache poisoning.+ */+function operatingOnHostBrain(): boolean {+ try {+ return resolveBrainId(undefined) === 'host';+ } catch {+ return true; // resolver default is host; fail toward normal behavior+ }+}++export async function getBackupStatus(+ engine: BrainEngine,+ opts: BackupCoverageOpts & { forceRefresh?: boolean },+): Promise<BackupStatus> {+ const hostBrain = operatingOnHostBrain();+ const cached = hostBrain ? loadBackupStatus() : null;+ const nowMs = (opts.now ?? new Date()).getTime();+ if (!opts.forceRefresh && cached && !isBackupStatusStale(cached, nowMs)) return cached;+ try {+ const fresh = await computeBackupCoverage(engine, opts);+ // A DEGRADED verdict (engine down mid-compute — sources/pages unreadable)+ // must never replace a probed cache: prefer the prior verdict outright.+ if (fresh.degraded && cached) return cached;+ if (opts.localGitProbes && !fresh.degraded && hostBrain) {+ // The save gets its own guard: a failed WRITE (disk full) must not+ // discard the fresh verdict the caller just probed for.+ try {+ saveBackupStatus(fresh);+ } catch {+ process.stderr.write('[backup] could not persist the verdict cache (continuing with the fresh result)\n');+ }+ process.stderr.write(+ `[backup] checked ${fresh.totals.assets} asset(s): ${fresh.totals.no_remote} without a git remote (computed_by=${fresh.computed_by})\n`,+ );+ }+ return fresh;+ } catch (err) {+ if (cached) return cached;+ throw err;+ }+}++// ── Serve-side in-process refresher (stdio transport ONLY) ──────────────────+//+// For the primary cohort (Claude Code + PGLite + a long-running stdio serve+// holding the single-writer lock) this is the ONLY automatic compute path —+// the detached CLI spawn dies on the lock. Trust defense (D4 + WP1/D7): the+// caller (mcp/dispatch.ts) gates this on `opts.transport === 'stdio'` — the+// same transport-LOCALITY axis localOnly ops use; 'http' or UNSET never+// reaches here. The refresher is NOT caller-parameterized: it takes no+// request arguments, runs fixed read-only git subcommands via execFile array+// args, and only writes a machine-owned file under ~/.gbrain.++let refreshInFlight = false;+let lastRefreshAttemptMs = 0;+/** Failure/attempt throttle so a broken compute can't retry per dispatch. */+const REFRESH_ATTEMPT_FLOOR_MS = 60 * 60 * 1000;++export function __resetBackupRefreshForTests(): void {+ refreshInFlight = false;+ lastRefreshAttemptMs = 0;+}++/**+ * Fire-and-forget, module-level single-flight. Recomputes when the cache is+ * stale-or-absent OR when the cached verdict is `warn` and the cache is >24h+ * old (so a raw-git fix surfaces within a day in the serve cohort). Never+ * throws.+ */+export function maybeRefreshBackupStatusInProcess(engine: BrainEngine): void {+ try {+ if (refreshInFlight) return;+ if (backupCheckDisabled()) return;+ const now = Date.now();+ if (now - lastRefreshAttemptMs < REFRESH_ATTEMPT_FLOOR_MS) return;+ const cached = loadBackupStatus();+ const warnAging =+ cached?.overall === 'warn' && now - Date.parse(cached.checked_at) > 24 * 60 * 60 * 1000;+ if (cached && !isBackupStatusStale(cached, now) && !warnAging) {+ // Arm the attempt floor on the healthy path too: steady-state dispatch+ // must not pay three file reads per tool call — recheck at most hourly+ // (a <=1h detection delay is noise against the 30-day interval).+ lastRefreshAttemptMs = now;+ return;+ }+ refreshInFlight = true;+ lastRefreshAttemptMs = now;+ void getBackupStatus(engine, { localGitProbes: true, computedBy: 'serve', forceRefresh: true })+ .catch(() => {})+ .finally(() => {+ refreshInFlight = false;+ });+ } catch {+ /* never break dispatch over a refresher */+ }+}diff --git a/src/core/backup/status-file.ts b/src/core/backup/status-file.tsnew file mode 100644index 0000000000..8c8b65d6c5--- /dev/null+++ b/src/core/backup/status-file.ts@@ -0,0 +1,528 @@+/**+ * backup/status-file.ts — ENGINE-FREE core of the monthly backup-coverage+ * check: the cached verdict file, the notice renderer, and the bounded nag+ * gate shared by every render channel.+ *+ * ENGINE-FREE BY CONSTRUCTION: this module is imported by `gbrain hook`+ * (which must never touch the engine — serve holds the PGLite single-writer+ * lock) and by cli.ts's startup rail. Imports are fs/path, config file-plane+ * helpers, and the PURE policy functions from skillpack/nag-state.ts only.+ * Compute lives in backup/coverage.ts (engine-side).+ *+ * Two machine-owned files under the gbrain home (atomic tmp+rename, 0600,+ * fail-open on corrupt — a broken state file must never break a session):+ *+ * backup-status.json the cached BackupStatus verdict. Written ONLY by a+ * successful probed compute (coverage.ts); deleted by+ * invalidateBackupStatus() on fix paths (bootstrap+ * repo / sources harden / sources push success).+ * backup-nag-state.json bounded-nag state. OWN schema (gbrain-backup-nag-v1)+ * — NOT skillpack's: loadNagState() reconstructs only+ * {schema_version, entries} on load, so the dampener /+ * global-cap fields here would be silently dropped on+ * round-trip. We reuse ONLY the pure policy functions+ * (decideNagAction / recordNagDisplay).+ *+ * Nag semantics (per channel, composed as an AND):+ * - per-channel ceiling 3 per pseudo-version, where pack_version =+ * YYYY-MM(checked_at) + verdict fingerprint — a new month or a CHANGED+ * verdict re-surfaces; a same-month recompute with an unchanged verdict+ * stays quiet.+ * - cross-channel 24h dampener (top-level last_shown_at).+ * - global cap: 3 RECORDED impressions per month-bucket across all+ * recording channels (global_shown_count anchored by global_month).+ * record() is DEFERRED — call it only after the text actually reached the+ * wire (the hook.ts banner discipline); cross-process last-writer-wins on+ * this file is acceptable (worst case: one extra display).+ */++import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { dirname } from 'node:path';++import { gbrainPath, loadConfigFileOnly } from '../config.ts';+import {+ decideNagAction,+ recordNagDisplay,+ type NagEntry,+} from '../skillpack/nag-state.ts';++// ── Verdict types ───────────────────────────────────────────────────────────++export const BACKUP_STATUS_SCHEMA_VERSION = 'gbrain-backup-status-v1' 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 BackupAssetState = 'ok' | 'no_remote' | 'unpushed' | 'dirty' | 'failing' | 'info' | 'unknown';+export type BackupComputedBy = 'cli' | 'advisor' | 'doctor' | 'serve' | 'spawn' | 'sync';++export interface BackupAssetVerdict {+ kind: BackupAssetKind;+ /** Source id / workspace root / label. LOCAL surfaces only — aggregate+ * remote wording never includes this field. */+ id: string;+ state: BackupAssetState;+ /** Sanitized detail codes/counts only — never raw git stderr. */+ detail?: string;+ /** Commits ahead of origin (when probed). */+ ahead?: number;+ /** Structured fix argv (AdvisorFix discipline) or null when no single+ * mechanical fix exists. */+ fix_argv?: string[] | null;+}++export interface BackupTotals {+ assets: number;+ no_remote: number;+ unpushed: number;+ failing: number;+ /** Git-backed assets that would survive a disk loss (recovery statement). */+ recoverable_repos: number;+ /** Pages at risk on disk loss (db_only + undeclared DB-only signal). */+ pages_at_risk: number;+}++export interface BackupStatus {+ schema_version: typeof BACKUP_STATUS_SCHEMA_VERSION;+ /** ISO 8601 UTC of the completed compute. */+ checked_at: string;+ gbrain_version: string;+ interval_days: number;+ computed_by: BackupComputedBy;+ overall: 'ok' | 'warn';+ totals: BackupTotals;+ assets: BackupAssetVerdict[];+ /**+ * True when the compute could not read sources/pages (engine down mid-run).+ * A degraded verdict is never persisted over a probed cache+ * (coverage.ts getBackupStatus) — it would silence or fabricate a warn.+ */+ degraded?: boolean;+}++// ── Paths (test seams follow the nag-state.ts idiom) ────────────────────────++let statusPathOverride: string | null = null;+let nagStatePathOverride: string | null = null;+let intervalOverrideMs: number | null = null;++export function backupStatusPath(): string {+ return statusPathOverride ?? gbrainPath('backup-status.json');+}+export function __setBackupStatusPathForTests(p: string | null): void {+ statusPathOverride = p;+}++export function backupNagStatePath(): string {+ return nagStatePathOverride ?? gbrainPath('backup-nag-state.json');+}+export function __setBackupNagStatePathForTests(p: string | null): void {+ nagStatePathOverride = p;+}++export function __setBackupIntervalForTests(ms: number | null): void {+ intervalOverrideMs = ms;+}++// ── Config / kill switches ──────────────────────────────────────────────────++/** Default automatic-compute window: 30 days ("once a month"). */+export const BACKUP_INTERVAL_DAYS_DEFAULT = 30;+/** Human notice budget (the push-banner discipline). */+export const BACKUP_BANNER_MAX_CHARS = 300;+/** Cross-channel dampener: at most one recorded impression per day. */+export const BACKUP_DAMPENER_MS = 24 * 60 * 60 * 1000;+/** Recorded impressions allowed per month-bucket across ALL channels. */+export const BACKUP_GLOBAL_CEILING = 3;++function configBackup(): { check_enabled?: unknown; check_interval_days?: unknown } {+ try {+ const cfg = loadConfigFileOnly() as { backup?: { check_enabled?: unknown; check_interval_days?: unknown } };+ return cfg.backup ?? {};+ } catch {+ return {};+ }+}++/**+ * Hard off-switches. Default ON — the whole point is protecting users who+ * never opted in. `GBRAIN_BACKUP_CHECK=0` is the env kill switch; the+ * file-plane key `backup.check_enabled` accepts 'false'/'0'/'off'/false.+ * Render sites AND compute sites both consult this, so a stale warn cache+ * goes silent the moment the feature is disabled.+ */+export function backupCheckDisabled(): boolean {+ const env = process.env.GBRAIN_BACKUP_CHECK?.trim().toLowerCase();+ if (env === '0' || env === 'false' || env === 'off') return true;+ const raw = configBackup().check_enabled;+ if (raw === undefined || raw === null) return false;+ if (raw === false) return true;+ const s = String(raw).trim().toLowerCase();+ return s === 'false' || s === '0' || s === 'off';+}++/**+ * Automatic-compute window in ms. env GBRAIN_BACKUP_CHECK_DAYS > config >+ * default 30. Clamped to ≥1 day (a leftover DAYS=0 must not re-probe up to+ * 500 git roots on every dispatch) — forcing a recompute is `gbrain backup+ * check` or the test seam, never DAYS=0.+ */+export function backupIntervalMs(): number {+ if (intervalOverrideMs !== null) return intervalOverrideMs;+ const day = 24 * 60 * 60 * 1000;+ const env = process.env.GBRAIN_BACKUP_CHECK_DAYS;+ const cfgRaw = configBackup().check_interval_days;+ const raw = env !== undefined && env !== '' ? Number(env) : cfgRaw !== undefined ? Number(cfgRaw) : NaN;+ const days = Number.isFinite(raw) && raw >= 1 ? raw : BACKUP_INTERVAL_DAYS_DEFAULT;+ return days * day;+}++// ── Cached verdict I/O ──────────────────────────────────────────────────────++function atomicWriteJson(path: string, value: unknown): void {+ mkdirSync(dirname(path), { recursive: true });+ const tmp = `${path}.tmp-${process.pid}`;+ try {+ writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });+ renameSync(tmp, path);+ } catch (err) {+ try {+ rmSync(tmp, { force: true });+ } catch {}+ throw err;+ }+}++/** Missing / corrupt / unknown-schema → null (fail-open). */+export function loadBackupStatus(): BackupStatus | null {+ const path = backupStatusPath();+ if (!existsSync(path)) return null;+ try {+ const raw = JSON.parse(readFileSync(path, 'utf-8')) as Partial<BackupStatus>;+ if (raw.schema_version !== BACKUP_STATUS_SCHEMA_VERSION) return null;+ if (typeof raw.checked_at !== 'string' || !Array.isArray(raw.assets)) return null;+ if (raw.overall !== 'ok' && raw.overall !== 'warn') return null;+ // Renderers dereference totals un-guarded — a truncated-but-schema-valid+ // cache must read as absent, not crash `gbrain backup status`.+ const t = raw.totals;+ if (+ !t ||+ typeof t.assets !== 'number' ||+ typeof t.no_remote !== 'number' ||+ typeof t.recoverable_repos !== 'number' ||+ typeof t.pages_at_risk !== 'number'+ ) {+ return null;+ }+ return raw as BackupStatus;+ } catch {+ return null;+ }+}++export function saveBackupStatus(s: BackupStatus): void {+ atomicWriteJson(backupStatusPath(), s);+}++/**+ * Fix-path invalidation: called on `bootstrap repo` / `sources harden` /+ * `sources push` success so a fixed repo stops nagging immediately instead of+ * at the next 30-day recompute. Best-effort — never throws.+ */+export function invalidateBackupStatus(): void {+ try {+ rmSync(backupStatusPath(), { force: true });+ } catch {}+}++/**+ * Absent cache counts as stale (cold start computes on the first trigger).+ * A checked_at more than 24h in the FUTURE is stale/invalid (clock skew).+ */+export function isBackupStatusStale(s: BackupStatus | null, now: number = Date.now()): boolean {+ if (!s) return true;+ const t = Date.parse(s.checked_at);+ if (!Number.isFinite(t)) return true;+ if (t > now + 24 * 60 * 60 * 1000) return true;+ return now - t > backupIntervalMs();+}++// ── Notice rendering ────────────────────────────────────────────────────────++/** Cache age as a short human phrase ("2h ago", "12d ago"). */+export function backupCacheAge(s: BackupStatus, now: number = Date.now()): string {+ const t = Date.parse(s.checked_at);+ if (!Number.isFinite(t)) return 'unknown age';+ const ms = Math.max(0, now - t);+ const h = Math.floor(ms / (60 * 60 * 1000));+ if (h < 1) return 'under an hour ago';+ if (h < 48) return `${h}h ago`;+ return `${Math.floor(h / 24)}d ago`;+}++/**+ * The user-facing warning line. Returns null when overall is ok.+ *+ * 'human' (trusted local surfaces: hook banner, CLI rail, backup status):+ * names up to two assets, second person, concrete numbers, never preachy+ * (DESIGN.md voice), capped at BACKUP_BANNER_MAX_CHARS.+ *+ * 'aggregate' (remote/MCP surfaces): counts ONLY — never a local path or+ * source id (remote-privacy-sweep is the backstop).+ */+export function backupNoticeText(s: BackupStatus, surface: 'human' | 'aggregate'): string | null {+ if (s.overall !== 'warn') return null;+ const n = s.totals.no_remote;+ const total = s.totals.assets;+ if (surface === 'aggregate') {+ return (+ `gbrain monthly backup check: ${n} of ${total} knowledge assets have no git remote ` ++ `(local-only). A disk loss loses them. Run 'gbrain backup status' on the brain host for fix commands.`+ );+ }+ const names = s.assets+ .filter((a) => a.state === 'no_remote')+ .slice(0, 2)+ .map((a) => a.id);+ const which = names.length > 0 ? ` (${names.join(', ')}${n > names.length ? ', …' : ''})` : '';+ const text =+ `${n} of your ${total} knowledge assets aren't on any git remote${which}. ` ++ `A disk loss loses them. Run: gbrain backup status`;+ return text.length > BACKUP_BANNER_MAX_CHARS ? `${text.slice(0, BACKUP_BANNER_MAX_CHARS - 1)}…` : text;+}++// ── Nag state (own schema; reuses ONLY nag-state.ts pure policy fns) ────────++export interface BackupNagState {+ schema_version: typeof BACKUP_NAG_SCHEMA_VERSION;+ entries: NagEntry[];+ /** Cross-channel dampener: ISO of the last RECORDED impression anywhere. */+ last_shown_at?: string;+ /** Recorded impressions in global_month (cap BACKUP_GLOBAL_CEILING). */+ global_shown_count?: number;+ /** YYYY-MM anchor for global_shown_count; rollover resets the count. */+ global_month?: string;+ /** Session-end detached-spawn debounce (no separate sidecar file). */+ last_spawn_at?: string;+}++const EMPTY_NAG: BackupNagState = { schema_version: BACKUP_NAG_SCHEMA_VERSION, entries: [] };++export function loadBackupNagState(): BackupNagState {+ const path = backupNagStatePath();+ if (!existsSync(path)) return { ...EMPTY_NAG, entries: [] };+ try {+ const raw = JSON.parse(readFileSync(path, 'utf-8')) as Partial<BackupNagState>;+ if (raw.schema_version !== BACKUP_NAG_SCHEMA_VERSION || !Array.isArray(raw.entries)) {+ return { ...EMPTY_NAG, entries: [] };+ }+ return {+ schema_version: BACKUP_NAG_SCHEMA_VERSION,+ entries: raw.entries as NagEntry[],+ last_shown_at: typeof raw.last_shown_at === 'string' ? raw.last_shown_at : undefined,+ global_shown_count: typeof raw.global_shown_count === 'number' ? raw.global_shown_count : undefined,+ global_month: typeof raw.global_month === 'string' ? raw.global_month : undefined,+ last_spawn_at: typeof raw.last_spawn_at === 'string' ? raw.last_spawn_at : undefined,+ };+ } catch {+ return { ...EMPTY_NAG, entries: [] };+ }+}++export function saveBackupNagState(state: BackupNagState): void {+ try {+ atomicWriteJson(backupNagStatePath(), state);+ } catch {+ // Fail-open: a nag-state write failure must never break the caller.+ }+}++function monthBucket(iso: string): string {+ return iso.slice(0, 7); // YYYY-MM+}++/**+ * Pseudo-version: month bucket of the verdict's checked_at + a fingerprint of+ * the no-remote set. A new month or a CHANGED verdict reads as a version bump+ * (re-surfaces, count resets via recordNagDisplay); a same-month forced+ * recompute with an unchanged verdict keeps the same pseudo-version and stays+ * suppressed once the ceiling is hit.+ */+export function backupVerdictVersion(s: BackupStatus): string {+ const ids = s.assets+ .filter((a) => a.state === 'no_remote')+ .map((a) => a.id)+ .sort()+ .join(',');+ const t = s.totals;+ return `${monthBucket(s.checked_at)}:${t.no_remote}/${t.assets}:${ids}`;+}++const NAG_KEY_BASE = { brain_id: 'host', source_id: 'backup' } as const;++/**+ * True when `iso` marks an event within the trailing dampener window. One+ * helper for every consumer (gate, read-only consult, spawn debounce) so the+ * future-skew guard cannot diverge: a far-future timestamp (clock jump /+ * corrupt write) is ignored rather than suppressing forever.+ */+function withinDampener(iso: string | undefined, now: number): boolean {+ if (!iso) return false;+ const t = Date.parse(iso);+ return Number.isFinite(t) && now - t < BACKUP_DAMPENER_MS && t <= now + BACKUP_DAMPENER_MS;+}++export interface BackupNagDecision {+ show: boolean;+ /** Deferred — invoke only AFTER the text reached the wire. No-op when+ * show=false or for read-only consults. */+ record: () => void;+}++const NOOP_DECISION: BackupNagDecision = { show: false, record: () => {} };++/**+ * The bounded-nag gate every RECORDING channel routes through+ * ('hook-banner' | 'hook-note' | 'cli' | 'mcp' | 'status' | 'advisor' | …).+ * The global cap and dampener are enforced HERE, uniformly, so any future+ * channel inherits them.+ */+export function backupNagGate(channel: string, s: BackupStatus, now: number = Date.now()): BackupNagDecision {+ try {+ if (s.overall !== 'warn' || backupCheckDisabled()) return NOOP_DECISION;+ const state = loadBackupNagState();+ const nowIso = new Date(now).toISOString();+ const month = monthBucket(nowIso);++ // Cross-channel 24h dampener.+ if (withinDampener(state.last_shown_at, now)) return NOOP_DECISION;+ // Global per-month-bucket cap (count resets on rollover).+ const globalCount = state.global_month === month ? (state.global_shown_count ?? 0) : 0;+ if (globalCount >= BACKUP_GLOBAL_CEILING) return NOOP_DECISION;++ const key = { ...NAG_KEY_BASE, pack_name: channel };+ const packVersion = backupVerdictVersion(s);+ const prior = state.entries.find(+ (e) => e.brain_id === key.brain_id && e.source_id === key.source_id && e.pack_name === key.pack_name,+ );+ const decision = decideNagAction(prior, { pack_version: packVersion });+ if (!decision.show) return NOOP_DECISION;++ return {+ show: true,+ record: () => {+ try {+ // Re-load for last-writer-wins freshness; races are acceptable+ // (worst case one extra display, documented).+ const fresh = loadBackupNagState();+ const freshPrior = fresh.entries.find(+ (e) => e.brain_id === key.brain_id && e.source_id === key.source_id && e.pack_name === key.pack_name,+ );+ const entry = recordNagDisplay(freshPrior, key, { pack_version: packVersion, nowIso });+ const others = fresh.entries.filter(+ (e) => !(e.brain_id === key.brain_id && e.source_id === key.source_id && e.pack_name === key.pack_name),+ );+ const freshGlobal = fresh.global_month === month ? (fresh.global_shown_count ?? 0) : 0;+ saveBackupNagState({+ ...fresh,+ entries: [...others, entry],+ last_shown_at: nowIso,+ global_month: month,+ global_shown_count: freshGlobal + 1,+ });+ } catch {+ // Fail-open.+ }+ },+ };+ } catch {+ return NOOP_DECISION;+ }+}++/**+ * Read-only consult for the OpenClaw context-engine line: `assemble()`+ * composes server-side and cannot know delivery, so it never writes nag+ * state. Shows only when the shared dampener has aged out AND the recording+ * channels' global budget is not exhausted — bounded by their budget without+ * ever spending it. (The caller adds its own in-process 24h latch.)+ */+export function backupNagReadOnlyConsult(s: BackupStatus, now: number = Date.now()): boolean {+ try {+ if (s.overall !== 'warn' || backupCheckDisabled()) return false;+ const state = loadBackupNagState();+ if (withinDampener(state.last_shown_at, now)) return false;+ const month = monthBucket(new Date(now).toISOString());+ const globalCount = state.global_month === month ? (state.global_shown_count ?? 0) : 0;+ return globalCount < BACKUP_GLOBAL_CEILING;+ } catch {+ return false;+ }+}++// ── Session-end spawn debounce (folded into the nag file — no sidecar) ──────++/** True when a detached `gbrain backup check --quiet` may be spawned. */+export function backupSpawnDue(now: number = Date.now()): boolean {+ try {+ return !withinDampener(loadBackupNagState().last_spawn_at, now);+ } catch {+ return true;+ }+}++export function recordBackupSpawn(now: number = Date.now()): void {+ try {+ const state = loadBackupNagState();+ saveBackupNagState({ ...state, last_spawn_at: new Date(now).toISOString() });+ } catch {}+}++// ── CLI startup rail helper (keeps the cli.ts diff tiny) ────────────────────++/** Commands that must never host the backup nag on the CLI rail. `serve`+ * especially: a harness-spawned MCP server must not burn the shared budget+ * into a log nobody reads. */+export const BACKUP_CLI_NAG_SKIP = new Set([+ 'upgrade',+ 'post-upgrade',+ 'check-update',+ 'self-upgrade',+ 'hook',+ 'backup',+ 'doctor',+ 'advisor',+ 'serve',+ 'call',+ 'jobs',+]);++/**+ * The cli.ts startup-rail body (called right after maybeEmitUpdateMarker).+ * Guards live here — one place, every call site covered. Fail-open.+ */+export function maybeEmitBackupNag(+ command: string | undefined,+ opts: { quiet?: boolean } = {},+ write: (line: string) => void = (line) => process.stderr.write(line),+): void {+ try {+ if (process.env.NODE_ENV === 'test' && process.env.GBRAIN_FORCE_BACKUP_NAG !== '1') return;+ if (process.env.GBRAIN_SKIP_STARTUP_HOOKS) return;+ if (opts.quiet) return;+ if (!command || BACKUP_CLI_NAG_SKIP.has(command)) return;+ if (backupCheckDisabled()) return;+ const s = loadBackupStatus();+ if (!s || s.overall !== 'warn') return;+ const gate = backupNagGate('cli', s);+ if (!gate.show) return;+ const text = backupNoticeText(s, 'human');+ if (!text) return;+ if (!process.stderr.isTTY) {+ write(`BACKUP_LOCAL_ONLY ${s.totals.no_remote}\n`);+ }+ write(`gbrain backup check: ${text}\n`);+ gate.record();+ } catch {+ // Never break a CLI invocation over a notice.+ }+}diff --git a/src/core/bootstrap/format.ts b/src/core/bootstrap/format.tsindex 215e868038..4da038b3b8 100644--- a/src/core/bootstrap/format.ts+++ b/src/core/bootstrap/format.ts@@ -131,6 +131,13 @@ export interface InstallReceipt {created_paths: string[];/** Host registrations bootstrap performed (for marker-keyed removal). */registrations: Array<{ host: 'claude-code' | 'codex' | 'opencode'; scope: string; detail?: string }>;+ /**+ * Private-repo URL, recorded by `bootstrap repo` ONLY after a successful+ * push (repo.ts recordRepoInReceipt). Optional: absent until the repo phase+ * completes. Typed here so consumers (bootstrap/status.ts, backup/coverage)+ * stop re-declaring it as an inline cast.+ */+ repo_url?: string;}export function receiptPath(gbrainHomeDir: string): string {diff --git a/src/core/bootstrap/repo.ts b/src/core/bootstrap/repo.tsindex ad26e80487..0e87983c31 100644--- a/src/core/bootstrap/repo.ts+++ b/src/core/bootstrap/repo.ts@@ -34,6 +34,7 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { configDir } from '../config.ts';+import { invalidateBackupStatus } from '../backup/status-file.ts';import { realpathOrResolve } from '../path-confine.ts';import { defaultRunner, isProxyBlocked403, parseGithubOwnerRepo, type ExecRunner } from '../repo-visibility.ts';import { detectExecutionEnvironment } from '../execution-env.ts';@@ -364,6 +365,10 @@ function recordRepoInReceipt(gbrainHomeDir: string, workspaceDir: string, manifereceipt.repo_url = url;delete receipt.pending_repo_url;writeReceipt(gbrainHomeDir, receipt);+ // Fix-path invalidation: the workspace just gained a verified remote — the+ // backup-coverage cache must stop warning NOW, not at the next 30-day+ // recompute (backup/status-file.ts). Best-effort by construction.+ invalidateBackupStatus();}// ---------------------------------------------------------------------------diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex f2d3f083b2..334103715d 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -21,6 +21,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'auth': ['--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--id', '--json', '--no-embedding', '--redirect-uri', '--scopes', '--source', '--stale', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],'autopilot': ['--all', '--auto-fix', '--batch', '--brain', '--break-lock', '--by-type', '--check', '--dim', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--ff-only', '--fix', '--force', '--force-break-lock', '--force-retry', '--from-pages', '--help', '--http', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--json', '--markdown', '--max-age', '--max-rss', '--max-usd', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--no-inject', '--no-mutate', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--save', '--source', '--stale', '--status', '--surface', '--swap-only', '--take', '--target', '--target-score', '--timeout', '--to', '--token-ttl', '--uninstall', '--unsafe-bypass-dream-guard', '--user', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],+ 'backup': ['--background', '--batch-limit', '--brain', '--brain-wide-max-cost-usd', '--budget-ms', '--check', '--count', '--dir', '--explain', '--follow', '--help', '--json', '--once', '--path', '--porcelain', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restore-only', '--source', '--stale', '--timeout', '--verify'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--all', '--allow-empty', '--apply', '--asof', '--author', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--budget-usd-per-day', '--by-mention', '--chapters-dir', '--check', '--content', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--max-usd', '--mode', '--model', '--multimodal', '--near-symbol', '--no-confirm', '--no-embedding', '--no-follow', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--remediate', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--stdin', '--surface', '--timeout', '--timeout-ms', '--title', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--compile', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--fast', '--file', '--flag', '--force', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--isolated', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-verify', '--once', '--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', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--token-ttl', '--unset-all', '--url', '--user-hooks', '--verify', '--version', '--visibility', '--workspace', '--yes'],@@ -58,7 +59,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--redact', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fast', '--fix', '--force', '--from-pages', '--full', '--get', '--help', '--http', '--include-catch-all', '--include-hidden', '--json', '--name-only', '--name-status', '--no-embedding', '--no-verify', '--others', '--source', '--strategy', '--surface', '--timeout', '--token-ttl', '--uninstall', '--write-back'],'graph-query': ['--brain', '--depth', '--direction', '--fast', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--json', '--mcp-only', '--no-embedding', '--source', '--surface', '--timeout', '--token-ttl', '--type'],- 'hook': ['--allow-unverified-remote', '--auto', '--batch-limit', '--brain', '--budget-ms', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--jq', '--json', '--name-only', '--no-embedding', '--once', '--others', '--path', '--porcelain', '--project', '--pure', '--quiet', '--remove', '--show-current', '--show-toplevel', '--source', '--stale', '--stats', '--status', '--surface', '--timeout', '--token', '--token-ttl'],+ 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--jq', '--json', '--name-only', '--no-embedding', '--others', '--path', '--porcelain', '--project', '--pure', '--quiet', '--remove', '--show-current', '--show-toplevel', '--source', '--stats', '--status', '--surface', '--token', '--token-ttl'],'import': ['--all', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--check', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--include-hidden', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--others', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--since', '--skip-failed', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--workers'],'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--reranking', '--reset', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],diff --git a/src/core/config.ts b/src/core/config.tsindex a0a033018a..b0b86bbcee 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -33,6 +33,9 @@ export interface GBrainConfig {* `gbrain config set` routes these two dotted keys here, not to the DB. */push?: { allow_unverified_remote?: boolean };hooks?: { stop_push_debounce_min?: number | string };+ /** Monthly backup-coverage check (src/core/backup/). File-plane: read by+ * engine-free render sites (hook children, the cli.ts startup rail). */+ backup?: { check_enabled?: boolean | string; check_interval_days?: number | string };database_url?: string;database_path?: string;openai_api_key?: string;@@ -1155,6 +1158,11 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// `config set` — engine-free hook/push children read loadConfigFileOnly).'push.allow_unverified_remote','hooks.stop_push_debounce_min',+ // File-plane backup-check keys (routed to ~/.gbrain/config.json by `config+ // set` — the engine-free render sites read loadConfigFileOnly). Default ON /+ // 30 days; interval clamps to >=1 day at read time (backup/status-file.ts).+ 'backup.check_enabled',+ 'backup.check_interval_days',// DB-plane (v0.32.3 search modes + related)'search.mode','search.cache.enabled',diff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex be73005e95..5cf8d6509f 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -16,6 +16,7 @@import { readFileSync, existsSync, statSync } from 'fs';import { join } from 'path';import { buildReflexAddition, warmReflex, type ResolveEntitiesFn as ReflexResolveEntitiesFn } from './context/reflex.ts';+import { backupNagReadOnlyConsult, backupNoticeText, loadBackupStatus } from './backup/status-file.ts';// Types inlined from openclaw/plugin-sdk to avoid hard dependency during development.// At runtime inside OpenClaw, the real SDK is available; these types ensure build compat.@@ -813,6 +814,13 @@ export function createGBrainContextEngine(ctx: {checkpointMemo.set(sessionId, memo);}let _envelope: string | null = null;+ // Monthly backup-coverage line: in-process 24h latch. assemble() composes+ // server-side and cannot know delivery, so this channel NEVER writes nag+ // state (read-only consult of the shared dampener + global monthly cap).+ // The latch advances on every CONSULT (not just shows) so a long-lived+ // serve pays at most one file read per 24h — an ok verdict must not cost+ // I/O on every turn, and a repeat line stays impossible.+ let _backupCheckedAt = 0;async function envelope(): Promise<string> {if (_envelope !== null) return _envelope;try {@@ -1159,6 +1167,22 @@ export function createGBrainContextEngine(ctx: {if (memoryAddition) parts.push(memoryAddition);if (reflexAddition) parts.push(reflexAddition);+ // Monthly backup-coverage warning (⚠ idiom, model-visible). Bounded by+ // the recording channels' budget without ever spending it; fail-open.+ try {+ const now = Date.now();+ if (now - _backupCheckedAt > 24 * 60 * 60 * 1000) {+ _backupCheckedAt = now;+ const backupStatus = loadBackupStatus();+ if (backupStatus && backupNagReadOnlyConsult(backupStatus, now)) {+ const note = backupNoticeText(backupStatus, 'human');+ if (note) parts.push(`- ⚠️ ${note}`);+ }+ }+ } catch {+ /* a notice must never break context assembly */+ }+// 4. Pass through messages unchanged (legacy assembly)return {messages: msgs,diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 329ad7f09b..9974f6c721 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -161,6 +161,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['bootstrap_harness_health','bootstrap_hooks_heartbeat','bootstrap_last_verify',+ 'backup_coverage','bootstrap_push_health','bootstrap_durability_job','bootstrap_runbook_skew',diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex 0530f9e2c3..97a9ab08e8 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -59,6 +59,7 @@ import { execFileSync } from 'child_process';import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, detectDefaultBranch, divergenceSafePull } from './git-remote.ts';import { loadConfigFileOnly } from './config.ts';import { ensureGbrainHome } from './gbrain-home.ts';+import { invalidateBackupStatus, loadBackupStatus } from './backup/status-file.ts';import {githubOwnerRepoString,readCachedPrivateVerdict,@@ -498,7 +499,9 @@ function sleep(ms: number): Promise<void> {return new Promise((r) => setTimeout(r, ms));}-function aheadCount(root: string, branch: string): number | undefined {+/** Commits ahead of origin/<branch> (undefined when git can't answer).+ * Exported for the backup-coverage probe (src/core/backup/coverage.ts). */+export function aheadCount(root: string, branch: string): number | undefined {const out = tryGit(root, ['rev-list', '--count', `origin/${branch}..HEAD`], { timeoutMs: 15_000 });if (out === null) return undefined;const n = parseInt(out, 10);@@ -538,6 +541,21 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP...(r.ahead !== undefined ? { ahead: r.ahead } : {}),repoRoot: root,});+ // Fix-path invalidation: a successful push changes the backup-coverage+ // answer (workspace failing→ok, unpushed→pushed) — but ONLY when the+ // cached verdict carried something a push can fix. The routine healthy+ // stop-push must not delete an ok cache every session (that would defeat+ // the monthly compute throttle for the healthiest cohort).+ if (r.ok) {+ try {+ const s = loadBackupStatus();+ if (s && (s.overall === 'warn' || s.totals.failing > 0 || s.totals.unpushed > 0)) {+ invalidateBackupStatus();+ }+ } catch {+ /* best-effort */+ }+ }return r;};diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 5b1a33dbbf..bf491877d8 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -21,6 +21,8 @@ import {buildUnknownParamWarnBlock,resolveStrictParamsMode,} from './validate-params.ts';+import { backupCheckDisabled, backupNagGate, backupNoticeText, loadBackupStatus } from '../core/backup/status-file.ts';+import { maybeRefreshBackupStatusInProcess } from '../core/backup/coverage.ts';// WP3: normalization + validation moved to validate-params.ts (direct unit// surface). Re-exported here so existing imports/tests keep working.@@ -28,6 +30,51 @@ export { normalizeOptionalParams, validateParams } from './validate-params.ts';const VERB_NAME_SET: ReadonlySet<string> = new Set(VERB_NAMES);+// ── monthly backup-coverage notice (once per process, agent-facing only) ────++let backupNoticeShown = false;+let backupNoticeCheckedMs = 0;++/** Test seam: re-arm the once-per-process backup notice. */+export function __resetBackupNoticeForTests(): void {+ backupNoticeShown = false;+ backupNoticeCheckedMs = 0;+}++/**+ * Attach the aggregate backup warning as an extra content block. Fail-open:+ * a notice bug must never break a tool call.+ *+ * STDIO transport only: the notice targets local-harness installs (Claude+ * Code/Codex/OpenClaw/plugin serves are all stdio). HTTP callers are remote+ * thin clients — the host's backup posture is operational metadata their+ * token scope doesn't grant (the mcp.publish_advisor discipline), and a+ * remote-triggered record() must not spend the LOCAL notice budget. Local CLI+ * callers (`gbrain call`, opts.remote === false) are excluded too — the+ * cli.ts startup rail owns that surface. The hourly recheck latch keeps the+ * healthy steady state at zero file reads per tool call.+ */+function maybeAttachBackupNotice(out: ToolResult, opts: DispatchOpts): void {+ try {+ if (backupNoticeShown || opts.remote === false || opts.transport !== 'stdio') return;+ const now = Date.now();+ if (now - backupNoticeCheckedMs < 60 * 60 * 1000) return;+ backupNoticeCheckedMs = now;+ if (backupCheckDisabled()) return;+ const s = loadBackupStatus();+ if (!s || s.overall !== 'warn') return;+ const gate = backupNagGate('mcp', s);+ if (!gate.show) return;+ const text = backupNoticeText(s, 'aggregate');+ if (!text) return;+ out.content.push({ type: 'text', text });+ backupNoticeShown = true;+ gate.record();+ } catch {+ /* never break dispatch over a notice */+ }+}+export interface ToolResult {content: { type: 'text'; text: string }[];isError?: boolean;@@ -610,6 +657,15 @@ export async function dispatchToolCall(if (unknownParamWarnings.length > 0) {out.content.push({ type: 'text', text: buildUnknownParamWarnBlock(unknownParamWarnings) });}+ // Monthly backup-coverage: one AGGREGATE model-visible block per process+ // (counts only — never a local path or source id), riding the same+ // extra-block mechanism (content[0] untouched, D3/D8 skew rule). The+ // refresher runs on the stdio transport ONLY — the WP1/D7 locality axis+ // localOnly ops use; 'http' or an UNSET marker never probes (fail-closed).+ maybeAttachBackupNotice(out, opts);+ if (opts.transport === 'stdio') {+ maybeRefreshBackupStatusInProcess(engine);+ }// _meta assembly (WP2 amendment 9): one producer per top-level key,// each isolated — handler-emitted keys (retrieval, warnings) attach// BEFORE and independently of the metaHook, so a hot-memory hookdiff --git a/templates/bootstrap/HEARTBEAT.md.template b/templates/bootstrap/HEARTBEAT.md.templateindex 4a53af8b72..7ff6f5336b 100644--- a/templates/bootstrap/HEARTBEAT.md.template+++ b/templates/bootstrap/HEARTBEAT.md.template@@ -33,6 +33,7 @@ enable two jobs in the same session; you cannot tell which one earned its keep.| brain-hygiene | weekly-equivalent | no | `gbrain doctor`; relay anything red. || morning-briefing | first session after 06:00 | no | One screen: due today, waiting on, worth knowing. No filler — a skipped briefing costs less than an empty one. || ambient-delta | every session start + turn boundary | no | `gbrain delta --session-id <thread> --budget-tokens 2000` — pull "what changed since my last wake" (new/updated pages, new facts, thread updates), deduped per session. Zero-LLM. Inject the returned block; stay silent when empty. Pair with `gbrain context-pack --entities <standing> --budget-tokens 4000` at session start / after compaction to warm context. See docs/guides/ambient-recall.md. |+| backup-check | monthly-equivalent | no | `gbrain backup status`; relay anything red — a knowledge repo without a git remote is unrecoverable on disk loss. |Cadence bookkeeping lives in `state/heartbeat-state.local.json` (machine-local,not committed).diff --git a/templates/bootstrap/template-repo/HEARTBEAT.md b/templates/bootstrap/template-repo/HEARTBEAT.mdindex d74553444e..c75914ae6e 100644--- a/templates/bootstrap/template-repo/HEARTBEAT.md+++ b/templates/bootstrap/template-repo/HEARTBEAT.md@@ -33,6 +33,7 @@ enable two jobs in the same session; you cannot tell which one earned its keep.| brain-hygiene | weekly-equivalent | no | `gbrain doctor`; relay anything red. || morning-briefing | first session after 06:00 | no | One screen: due today, waiting on, worth knowing. No filler — a skipped briefing costs less than an empty one. || ambient-delta | every session start + turn boundary | no | `gbrain delta --session-id <thread> --budget-tokens 2000` — pull "what changed since my last wake" (new/updated pages, new facts, thread updates), deduped per session. Zero-LLM. Inject the returned block; stay silent when empty. Pair with `gbrain context-pack --entities <standing> --budget-tokens 4000` at session start / after compaction to warm context. See docs/guides/ambient-recall.md. |+| backup-check | monthly-equivalent | no | `gbrain backup status`; relay anything red — a knowledge repo without a git remote is unrecoverable on disk loss. |Cadence bookkeeping lives in `state/heartbeat-state.local.json` (machine-local,not committed).diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex ec4d32232d..ac5d24c5f3 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.46.32.0 -->+<!-- gbrain-template-stamp: 0.46.33.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/advisor-backup-coverage.serial.test.ts b/test/advisor-backup-coverage.serial.test.tsnew file mode 100644index 0000000000..263d2b8d82--- /dev/null+++ b/test/advisor-backup-coverage.serial.test.ts@@ -0,0 +1,438 @@+/**+ * Tests for src/core/advisor/collect-backup-coverage.ts — the advisor+ * collector that surfaces the monthly backup-coverage verdict.+ *+ * Local runs (ctx.remote === false) recompute through getBackupStatus with+ * real git probes against tmp fixture repos and emit per-asset findings,+ * gated as one batch through backupNagGate. Remote runs (ctx.remote === true)+ * are cache-readers only: one aggregate finding, no source ids, no local+ * paths, and NEVER a nag-state write.+ *+ * Isolation: tmp GBRAIN_HOME (configDir() appends '.gbrain') plus the+ * status-file __set...ForTests path seams, so the real ~/.gbrain is never+ * touched. No mock.module → plain .test.ts (not serial).+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { collectBackupCoverage } from '../src/core/advisor/collect-backup-coverage.ts';+import { COLLECTORS } from '../src/core/advisor/run.ts';+import type { AdvisorContext } from '../src/core/advisor/types.ts';+import {+ BACKUP_STATUS_SCHEMA_VERSION,+ __setBackupIntervalForTests,+ __setBackupNagStatePathForTests,+ __setBackupStatusPathForTests,+ loadBackupNagState,+ saveBackupStatus,+ type BackupStatus,+} from '../src/core/backup/status-file.ts';++const ENV_KEYS = ['GBRAIN_HOME', 'GBRAIN_BACKUP_CHECK', 'GBRAIN_BACKUP_CHECK_DAYS'] as const;++let tmp: string;+let saved: Record<string, string | undefined>;+let statusPath: string;+let nagPath: string;++beforeEach(() => {+ tmp = realpathSync(mkdtempSync(join(tmpdir(), 'gb-adv-bak-')));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp; // configDir() → tmp/.gbrain (receipt, bridge state, config all isolated)+ statusPath = join(tmp, 'backup-status.json');+ nagPath = join(tmp, 'backup-nag-state.json');+ __setBackupStatusPathForTests(statusPath);+ __setBackupNagStatePathForTests(nagPath);+});++afterEach(() => {+ __setBackupStatusPathForTests(null);+ __setBackupNagStatePathForTests(null);+ __setBackupIntervalForTests(null);+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++// ── Fixture helpers ──────────────────────────────────────────────────────────++function git(cwd: string, args: string[]): void {+ execFileSync(+ 'git',+ ['-c', '[email protected]', '-c', 'user.name=t', ...args],+ { cwd, stdio: ['ignore', 'ignore', 'ignore'] },+ );+}++/** A git repo with one commit and NO origin remote. */+function makeNoRemoteRepo(name: string): string {+ const dir = join(tmp, name);+ mkdirSync(dir, { recursive: true });+ git(dir, ['init', '-q', '-b', 'main']);+ writeFileSync(join(dir, 'README.md'), 'hello\n');+ git(dir, ['add', '.']);+ git(dir, ['commit', '-q', '-m', 'init', '--no-gpg-sign']);+ return dir;+}++/** A repo with an origin (local bare), pushed, then one commit ahead. */+function makeUnpushedRepo(name: string): string {+ const dir = makeNoRemoteRepo(name);+ const bare = join(tmp, `${name}-origin.git`);+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare], {+ stdio: ['ignore', 'ignore', 'ignore'],+ });+ git(dir, ['remote', 'add', 'origin', bare]);+ git(dir, ['push', '-q', '-u', 'origin', 'main']);+ writeFileSync(join(dir, 'extra.md'), 'ahead\n');+ git(dir, ['add', '.']);+ git(dir, ['commit', '-q', '-m', 'ahead', '--no-gpg-sign']);+ return dir;+}++interface SourceFixture {+ id: string;+ local_path: string;+}++/** Minimal engine stub: sources + pages queries via executeRaw. */+function makeEngine(opts: { sources?: SourceFixture[]; pageCount?: number } = {}) {+ const calls: string[] = [];+ const engine = {+ kind: 'pglite',+ executeRaw: async (sql: string) => {+ calls.push(sql);+ if (/from\s+sources/i.test(sql)) {+ return (opts.sources ?? []).map((s) => ({+ id: s.id,+ name: s.id,+ local_path: s.local_path,+ last_commit: null,+ last_sync_at: null,+ config: {},+ created_at: new Date('2026-01-01T00:00:00Z'),+ archived: false,+ newest_content_at: null,+ }));+ }+ if (/from\s+pages/i.test(sql)) return [{ n: opts.pageCount ?? 0 }];+ return [];+ },+ };+ return { engine: engine as unknown as AdvisorContext['engine'], calls };+}++function ctx(+ engine: AdvisorContext['engine'],+ over: Partial<AdvisorContext> = {},+): AdvisorContext {+ return {+ engine,+ config: {} as AdvisorContext['config'],+ version: '0.0.0',+ workspace: null,+ skillsDir: null,+ now: new Date('2026-06-01T00:00:00Z'),+ remote: false,+ ...over,+ };+}++/** A crafted warn cache for the remote (cache-reader) tests. */+function warnCache(over: Partial<BackupStatus> = {}): BackupStatus {+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: '2026-06-01T00:00:00Z',+ gbrain_version: '0.0.0',+ interval_days: 30,+ computed_by: 'cli',+ overall: 'warn',+ totals: { assets: 5, no_remote: 2, unpushed: 0, failing: 0, recoverable_repos: 3, pages_at_risk: 0 },+ assets: [+ {+ kind: 'source_repo',+ id: 'xylophone-secret-source-991',+ state: 'no_remote',+ detail: 'lives at /tmp/zzz-secret-local-path/notes',+ fix_argv: null,+ },+ {+ kind: 'source_repo',+ id: 'quux-secret-source-992',+ state: 'no_remote',+ detail: 'fix: git remote add origin <url>',+ fix_argv: null,+ },+ ],+ ...over,+ };+}++// ── 1. Local ctx (remote:false) — per-asset findings ─────────────────────────++describe('collectBackupCoverage local (remote:false)', () => {+ 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');+ const { engine } = makeEngine({+ sources: [+ { id: 'zebra-no-remote-src', local_path: noRemote },+ { id: 'yak-unpushed-src', local_path: unpushed },+ ],+ pageCount: 0,+ });++ const findings = await collectBackupCoverage.collect(ctx(engine));++ const noRemoteFinding = findings.find((f) => f.id === 'backup_source_no_remote:zebra-no-remote-src');+ expect(noRemoteFinding).toBeDefined();+ expect(noRemoteFinding?.severity).toBe('warn');+ expect(noRemoteFinding?.title).toContain('zebra-no-remote-src');+ // The recipe detail (plain repo, not bootstrap-initialized → argv null).+ expect(noRemoteFinding?.detail).toContain('git remote add origin <url>');+ expect(noRemoteFinding?.detail).toContain('gbrain sources harden');+ expect(noRemoteFinding?.fix.command_argv).toBeNull();++ const unpushedFinding = findings.find((f) => f.id === 'backup_unpushed_work');+ expect(unpushedFinding).toBeDefined();+ expect(unpushedFinding?.severity).toBe('info');+ expect(unpushedFinding?.title).toContain('1 repo(s)');+ expect(unpushedFinding?.detail).toContain('yak-unpushed-src');+ expect(unpushedFinding?.detail).toContain('1 commit(s) ahead of origin/main');++ // Batch discipline: every finding is ask_user + collector-stamped.+ expect(findings.length).toBeGreaterThan(0);+ for (const f of findings) {+ expect(f.ask_user).toBe(true);+ expect(f.collector).toBe('backup-coverage');+ }+ });++ test('receipt-less DB-only brain (pages, no sources, no workspace) → backup_db_content_unbacked warn', async () => {+ const { engine } = makeEngine({ sources: [], pageCount: 42 });++ const findings = await collectBackupCoverage.collect(ctx(engine));++ expect(findings).toHaveLength(1);+ const f = findings[0]!;+ expect(f.id).toBe('backup_db_content_unbacked');+ expect(f.severity).toBe('warn');+ expect(f.detail).toContain('42 pages');+ expect(f.fix.command_argv).toEqual(['gbrain', 'bootstrap', 'repo']);+ expect(f.ask_user).toBe(true);+ expect(f.collector).toBe('backup-coverage');+ });+});++// ── 2 + 3. Remote ctx (remote:true) — cache-reader, aggregate-only ───────────++describe('collectBackupCoverage remote (remote:true)', () => {+ test('warn cache → exactly ONE aggregate finding; no source ids, no local paths, no nag-state write', async () => {+ saveBackupStatus(warnCache());+ // Remote must never touch the engine (cache-only read).+ const engine = {+ executeRaw: async () => {+ throw new Error('remote collect must not query the engine');+ },+ } as unknown as AdvisorContext['engine'];++ const findings = await collectBackupCoverage.collect(ctx(engine, { remote: true }));++ expect(findings).toHaveLength(1);+ const f = findings[0]!;+ expect(f.id).toBe('backup_coverage_aggregate');+ expect(f.severity).toBe('warn');+ expect(f.title).toContain('2 of 5');+ expect(f.fix.command_argv).toBeNull();+ expect(f.ask_user).toBe(true);+ expect(f.collector).toBe('backup-coverage');++ // amendment-29 discipline: aggregate wording ONLY — never a source id or+ // a local path from the cached verdict.+ const blob = JSON.stringify(findings);+ expect(blob).not.toContain('xylophone-secret-source-991');+ expect(blob).not.toContain('quux-secret-source-992');+ expect(blob).not.toContain('/tmp/zzz-secret-local-path');+ expect(blob).not.toContain('zzz-secret-local-path');++ // No nag writes on remote — the state file must not exist.+ expect(existsSync(nagPath)).toBe(false);+ });++ test('ok cache → zero findings and still no nag write', async () => {+ saveBackupStatus(+ 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' }],+ }),+ );+ const { engine } = makeEngine();+ const findings = await collectBackupCoverage.collect(ctx(engine, { remote: true }));+ expect(findings).toEqual([]);+ expect(existsSync(nagPath)).toBe(false);+ });++ test('NO cache → zero findings', async () => {+ expect(existsSync(statusPath)).toBe(false);+ const { engine } = makeEngine();+ const findings = await collectBackupCoverage.collect(ctx(engine, { remote: true }));+ expect(findings).toEqual([]);+ expect(existsSync(nagPath)).toBe(false);+ });+});++// ── 4. Nag ceiling — 3 surfaced batches per verdict, then quiet ──────────────++describe('collectBackupCoverage nag ceiling', () => {+ test('4 runs spaced +25h in the same month: 3 surfaced batches, then []', async () => {+ const noRemote = makeNoRemoteRepo('ceiling-repo');+ const { engine } = makeEngine({+ sources: [{ id: 'ceiling-src', local_path: noRemote }],+ pageCount: 0,+ });++ const t0 = Date.parse('2026-06-01T00:00:00Z');+ const hour = 60 * 60 * 1000;+ const runs: number[] = [];+ for (let i = 0; i < 4; i++) {+ // +25h between runs clears the 24h cross-channel dampener while every+ // run stays inside June (same global month bucket) and inside the 30d+ // cache interval (one compute, constant verdict fingerprint).+ const now = new Date(t0 + i * 25 * hour);+ const findings = await collectBackupCoverage.collect(ctx(engine, { now }));+ runs.push(findings.length);+ }++ expect(runs[0]).toBeGreaterThan(0);+ expect(runs[1]).toBeGreaterThan(0);+ expect(runs[2]).toBeGreaterThan(0);+ // Per-channel ceiling (3 per pseudo-version) AND the 3/month global cap+ // are both spent — the 4th call is gate-suppressed.+ expect(runs[3]).toBe(0);++ // The per-channel entry confirms suppression rather than an accident.+ const state = loadBackupNagState();+ const entry = state.entries.find((e) => e.pack_name === 'advisor');+ expect(entry).toBeDefined();+ expect(entry?.declined_count).toBe(3);+ expect(entry?.suppressed).toBe(true);+ expect(state.global_shown_count).toBe(3);+ expect(state.global_month).toBe('2026-06');+ });+});++// ── Workspace + db_only findings (local branch) ──────────────────────────────++/** Install receipt at configDir()/bootstrap/receipt.json (readReceipt shape). */+function writeReceipt(ws: string, extra: Record<string, unknown> = {}): void {+ const dir = join(tmp, '.gbrain', 'bootstrap');+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, 'receipt.json'),+ JSON.stringify(+ {+ receipt_version: 1,+ workspace_dir: ws,+ source_id: 'workspace',+ agent_name: 'agent-example',+ created_at: new Date().toISOString(),+ created_by: 'test',+ brain_created_by_bootstrap: false,+ created_paths: [],+ registrations: [],+ ...extra,+ },+ null,+ 2,+ ),+ );+}++describe('collectBackupCoverage local — workspace and db_only findings', () => {+ test('receipt without repo_url → backup_workspace_no_repo warn with the bootstrap-repo fix', async () => {+ const ws = join(tmp, 'ws-no-repo');+ mkdirSync(ws, { recursive: true });+ writeReceipt(ws); // no repo_url → bootstrap_workspace no_remote asset++ const { engine } = makeEngine({ sources: [], pageCount: 0 });+ const findings = await collectBackupCoverage.collect(ctx(engine));++ expect(findings).toHaveLength(1);+ const f = findings[0]!;+ expect(f.id).toBe('backup_workspace_no_repo');+ expect(f.severity).toBe('warn');+ expect(f.title).toContain('workspace has no private repo');+ expect(f.detail).toContain('no private repo yet');+ expect(f.fix.command_argv).toEqual(['gbrain', 'bootstrap', 'repo']);+ expect(f.ask_user).toBe(true);+ expect(f.collector).toBe('backup-coverage');+ });++ test('db_only source alongside a no-remote repo → backup_db_only_caveat info rides the warn batch', async () => {+ const noRemote = makeNoRemoteRepo('plain-repo');+ const tiered = makeNoRemoteRepo('tiered-repo');+ writeFileSync(join(tiered, 'gbrain.yml'), 'storage:\n db_only:\n - private/\n');++ const { engine } = makeEngine({+ sources: [+ { id: 'plain-src', local_path: noRemote },+ { id: 'tiered-src', local_path: tiered },+ ],+ pageCount: 0,+ });+ const findings = await collectBackupCoverage.collect(ctx(engine));++ const caveat = findings.find((f) => f.id === 'backup_db_only_caveat');+ expect(caveat).toBeDefined();+ expect(caveat?.severity).toBe('info');+ expect(caveat?.title).toContain('db_only');+ expect(caveat?.detail).toContain('undeclared_db_only_pages');+ expect(caveat?.fix.command_argv).toBeNull();+ // The warn batch it rides on is present too (both repos lack an origin).+ expect(findings.some((f) => f.id === 'backup_source_no_remote:plain-src')).toBe(true);+ expect(findings.some((f) => f.id === 'backup_source_no_remote:tiered-src')).toBe(true);+ });+});++// ── Kill switch: disabled → [] on BOTH branches ──────────────────────────────++describe('collectBackupCoverage — GBRAIN_BACKUP_CHECK=0', () => {+ test('disabled → [] on local AND remote branches even with a warn cache; engine untouched, no nag write', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ saveBackupStatus(warnCache()); // a stale warn cache must go silent too++ // Any engine touch (compute attempt) blows the test up.+ const throwing = {+ executeRaw: async () => {+ throw new Error('disabled collect must not query the engine');+ },+ } as unknown as AdvisorContext['engine'];++ const local = await collectBackupCoverage.collect(ctx(throwing));+ expect(local).toEqual([]);++ const remote = await collectBackupCoverage.collect(ctx(throwing, { remote: true }));+ expect(remote).toEqual([]);++ expect(existsSync(nagPath)).toBe(false); // no nag-state write on either branch+ });+});++// ── 5. COLLECTORS registration pin ───────────────────────────────────────────++describe('advisor registration', () => {+ test('COLLECTORS includes backup-coverage', () => {+ expect(COLLECTORS.some((c) => c.id === 'backup-coverage')).toBe(true);+ expect(collectBackupCoverage.id).toBe('backup-coverage');+ });+});diff --git a/test/backup-cli.serial.test.ts b/test/backup-cli.serial.test.tsnew file mode 100644index 0000000000..5832c5009f--- /dev/null+++ b/test/backup-cli.serial.test.ts@@ -0,0 +1,442 @@+/**+ * backup-cli.serial.test.ts — pins src/commands/backup.ts runBackupCli:+ * usage surface (--help / unknown subcommand), the status cache policy+ * (fresh ok cache never touches the engine; a fresh warn cache forces a+ * recompute), check's always-compute + --quiet contract, the PGLite-lock+ * fallback (cache-derived exit, fail-open with no cache) including a+ * source-text contract pin on the lock-error literal, non-lock engine+ * failures (reject with no cache, cache fallback otherwise), the+ * GBRAIN_BACKUP_CHECK=0 off switch (check refuses; status is a cache-only+ * reader), the --json recovery/degraded payload, and the warn-path+ * 'status' nag impression.+ *+ * Engine is driven through a stub connect thunk (async () => engineStub)+ * with the executeRaw idiom from test/backup-coverage.serial.test.ts —+ * no real PGLite, no real engine lock.+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import type { BrainEngine } from '../src/core/engine.ts';+import { runBackupCli } from '../src/commands/backup.ts';+import { DEFAULT_CLI_OPTIONS, setCliOptions, _resetCliOptionsForTest } from '../src/core/cli-options.ts';+import { __resetBackupRefreshForTests } from '../src/core/backup/coverage.ts';+import {+ BACKUP_STATUS_SCHEMA_VERSION,+ __setBackupIntervalForTests,+ __setBackupNagStatePathForTests,+ __setBackupStatusPathForTests,+ loadBackupStatus,+ saveBackupStatus,+ type BackupStatus,+} from '../src/core/backup/status-file.ts';++/** The exact literal thrown by src/core/pglite-engine.ts on lock contention.+ * isLockError in src/commands/backup.ts matches on the leading substring —+ * the source-text contract pin below fails the suite if either side drifts. */+const LOCK_SUBSTRING = 'Could not acquire PGLite lock';+const LOCK_MESSAGE = 'Could not acquire PGLite lock. Another gbrain process is using the database.';++const ENV_KEYS = [+ 'GBRAIN_HOME',+ 'GBRAIN_BACKUP_CHECK',+ 'GBRAIN_BACKUP_CHECK_DAYS',+ 'DATABASE_URL',+ 'GBRAIN_DATABASE_URL',+ 'GBRAIN_SOURCE',+ 'GBRAIN_SKIP_STARTUP_HOOKS',+] as const;++let tmp: string;+let saved: Record<string, string | undefined>;+let statusPath: string;+let nagPath: string;++const home = () => join(tmp, '.gbrain');++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-bkcli-'));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp; // configDir() === tmp/.gbrain+ statusPath = join(home(), 'backup-status.json');+ nagPath = join(home(), 'backup-nag-state.json');+ __setBackupStatusPathForTests(statusPath);+ __setBackupNagStatePathForTests(nagPath);+ __resetBackupRefreshForTests();+ _resetCliOptionsForTest();+});++afterEach(() => {+ __setBackupStatusPathForTests(null);+ __setBackupNagStatePathForTests(null);+ __setBackupIntervalForTests(null);+ __resetBackupRefreshForTests();+ _resetCliOptionsForTest();+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++// ── Fixtures ─────────────────────────────────────────────────────────────────++function stubEngine(opts: {+ kind?: 'pglite' | 'postgres';+ sources?: unknown[];+ pages?: number;+ sourcesThrow?: boolean;+} = {}): BrainEngine {+ return {+ kind: opts.kind ?? 'pglite',+ executeRaw: async (sql: string) => {+ if (sql.includes('FROM pages')) return [{ n: opts.pages ?? 0 }];+ if (sql.includes('FROM sources')) {+ if (opts.sourcesThrow) throw new Error('sources unreadable');+ return opts.sources ?? [];+ }+ return [];+ },+ disconnect: async () => {},+ } as unknown as BrainEngine;+}++/** Connect thunk that counts calls and resolves the given engine. */+function thunkFor(engine: BrainEngine): { connect: () => Promise<BrainEngine>; calls: () => number } {+ let n = 0;+ return {+ connect: async () => {+ n++;+ return engine;+ },+ calls: () => n,+ };+}++function throwingThunk(err: Error): { connect: () => Promise<BrainEngine>; calls: () => number } {+ let n = 0;+ return {+ connect: async () => {+ n++;+ throw err;+ },+ calls: () => n,+ };+}++/** Hand-built cache verdict that passes loadBackupStatus validation. */+function mkStatus(overall: 'ok' | 'warn', checkedAt: string): BackupStatus {+ const noRemote = overall === 'warn' ? 1 : 0;+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: checkedAt,+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall,+ totals: {+ assets: noRemote,+ no_remote: noRemote,+ unpushed: 0,+ failing: 0,+ recoverable_repos: 0,+ pages_at_risk: 0,+ },+ assets:+ overall === 'warn'+ ? [{ kind: 'source_repo', id: 'stale-example', state: 'no_remote', fix_argv: null }]+ : [],+ };+}++/** Run runBackupCli with stdout/console.log/console.error captured. */+async function run(+ args: string[],+ connect: () => Promise<BrainEngine>,+): Promise<{ exitCode: 0 | 1 | 2; stdout: string; log: string; stderr: string }> {+ const out: string[] = [];+ const log: string[] = [];+ const errs: string[] = [];+ const origWrite = process.stdout.write;+ const origLog = console.log;+ const origErr = console.error;+ (process.stdout as { write: unknown }).write = (chunk: unknown) => {+ out.push(String(chunk));+ return true;+ };+ console.log = (...a: unknown[]) => {+ log.push(a.map(String).join(' '));+ };+ console.error = (...a: unknown[]) => {+ errs.push(a.map(String).join(' '));+ };+ try {+ const res = await runBackupCli(args, connect);+ return { exitCode: res.exitCode, stdout: out.join(''), log: log.join('\n'), stderr: errs.join('\n') };+ } finally {+ (process.stdout as { write: unknown }).write = origWrite;+ console.log = origLog;+ console.error = origErr;+ }+}++// ── Usage surface ────────────────────────────────────────────────────────────++describe('runBackupCli — usage', () => {+ test('--help → exit 0 with the help text', async () => {+ const { connect, calls } = thunkFor(stubEngine({}));+ const r = await run(['--help'], connect);+ expect(r.exitCode).toBe(0);+ expect(r.log).toContain('gbrain backup <status|check>');+ expect(calls()).toBe(0);+ });++ test('no args → exit 0 with the help text', async () => {+ const { connect, calls } = thunkFor(stubEngine({}));+ const r = await run([], connect);+ expect(r.exitCode).toBe(0);+ expect(r.log).toContain('gbrain backup <status|check>');+ expect(calls()).toBe(0);+ });++ test('unknown subcommand → exit 2 on stderr', async () => {+ const { connect, calls } = thunkFor(stubEngine({}));+ const r = await run(['bogus'], connect);+ expect(r.exitCode).toBe(2);+ expect(r.stderr).toContain('Unknown backup subcommand: bogus');+ expect(calls()).toBe(0);+ });+});++// ── status cache policy ──────────────────────────────────────────────────────++describe('runBackupCli status — cache policy', () => {+ test('fresh ok cache → exit 0 and the connect thunk is NEVER called', async () => {+ saveBackupStatus(mkStatus('ok', new Date().toISOString()));+ const { connect, calls } = thunkFor(stubEngine({}));++ const r = await run(['status'], connect);++ expect(r.exitCode).toBe(0);+ expect(calls()).toBe(0); // no lock risk: fresh ok cache answers alone+ expect(r.stdout).toContain('backup coverage — ok');+ });++ test('fresh warn cache → recomputes (forceRefresh), exit reflects the NEW verdict', async () => {+ const oldIso = new Date(Date.now() - 60_000).toISOString();+ saveBackupStatus(mkStatus('warn', oldIso));+ // Recompute against an empty brain (no sources, 0 pages) → verdict ok.+ const { connect, calls } = thunkFor(stubEngine({}));++ const r = await run(['status'], connect);++ expect(calls()).toBe(1);+ expect(r.exitCode).toBe(0); // NEW verdict, not the stale warn+ expect(r.stdout).toContain('backup coverage — ok');+ const persisted = loadBackupStatus();+ expect(persisted?.overall).toBe('ok');+ expect(persisted?.checked_at).not.toBe(oldIso);+ });+});++// ── check always computes + --quiet ─────────────────────────────────────────++describe('runBackupCli check', () => {+ test('check always computes, even over a fresh ok cache; exit 0 when ok', async () => {+ const oldIso = new Date(Date.now() - 60_000).toISOString();+ saveBackupStatus(mkStatus('ok', oldIso));+ const { connect, calls } = thunkFor(stubEngine({}));++ const r = await run(['check'], connect);++ expect(calls()).toBe(1);+ expect(r.exitCode).toBe(0);+ expect(loadBackupStatus()?.checked_at).not.toBe(oldIso); // re-persisted+ });++ test('check exits 1 on a warn compute (pglite pages-only brain)', async () => {+ const { connect, calls } = thunkFor(stubEngine({ kind: 'pglite', pages: 42 }));++ const r = await run(['check'], connect);++ expect(calls()).toBe(1);+ expect(r.exitCode).toBe(1);+ expect(r.stdout).toContain('WARN');+ expect(loadBackupStatus()?.overall).toBe('warn');+ });++ test('--quiet → exit 0 and no stdout (detached-spawn mode)', async () => {+ setCliOptions({ ...DEFAULT_CLI_OPTIONS, quiet: true });+ const { connect, calls } = thunkFor(stubEngine({ kind: 'pglite', pages: 42 }));++ const r = await run(['check'], connect);++ expect(calls()).toBe(1); // still computes + caches+ expect(r.exitCode).toBe(0); // always 0 in quiet mode, even on warn+ expect(r.stdout).toBe('');+ expect(r.log).toBe('');+ const persisted = loadBackupStatus();+ expect(persisted?.overall).toBe('warn');+ expect(persisted?.computed_by).toBe('spawn'); // quiet stamps spawn+ });+});++// ── PGLite-lock fallback contract ────────────────────────────────────────────++describe('runBackupCli — PGLite lock fallback', () => {+ test('lock error + warn cache → exit 1 with the DB-locked note', async () => {+ saveBackupStatus(mkStatus('warn', new Date(Date.now() - 60_000).toISOString()));+ const { connect, calls } = throwingThunk(new Error(LOCK_MESSAGE));++ const r = await run(['status'], connect);++ expect(calls()).toBe(1);+ expect(r.exitCode).toBe(1); // cache-derived exit, never a crash+ expect(r.stdout).toContain('DB locked by serve');+ expect(r.stdout).toContain('backup coverage — WARN');+ });++ test('lock error + NO cache → exit 0 (unknown, fail-open)', async () => {+ const { connect, calls } = throwingThunk(new Error(LOCK_MESSAGE));++ const r = await run(['status'], connect);++ expect(calls()).toBe(1);+ expect(r.exitCode).toBe(0);+ expect(r.log).toContain('no cached verdict; DB locked by serve');+ expect(existsSync(statusPath)).toBe(false);+ });++ test('source-text contract pin: pglite-engine still throws the literal isLockError matches', () => {+ const engineSrc = readFileSync(join(import.meta.dir, '..', 'src', 'core', 'pglite-engine.ts'), 'utf-8');+ expect(engineSrc).toContain(LOCK_SUBSTRING);+ // And backup.ts matches on exactly that substring — drift on either side+ // silently breaks the serve-cohort fallback, so pin both.+ const backupSrc = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'backup.ts'), 'utf-8');+ expect(backupSrc).toContain(`includes('${LOCK_SUBSTRING}')`);+ });+});++// ── Non-lock engine failures ─────────────────────────────────────────────────++describe('runBackupCli — non-lock connect errors', () => {+ test('no cache → runBackupCli rejects (the failure propagates)', async () => {+ const { connect } = throwingThunk(new Error('engine exploded'));+ await expect(runBackupCli(['check'], connect)).rejects.toThrow('engine exploded');+ });++ test('with cache → falls back to the cached verdict + note', async () => {+ saveBackupStatus(mkStatus('warn', new Date(Date.now() - 60_000).toISOString()));+ const { connect, calls } = throwingThunk(new Error('engine exploded'));++ const r = await run(['status'], connect);++ expect(calls()).toBe(1);+ expect(r.exitCode).toBe(1); // exit from cache+ expect(r.stdout).toContain('engine unavailable — verdict from cache');+ });+});++// ── Off switch (GBRAIN_BACKUP_CHECK=0) ───────────────────────────────────────++describe('runBackupCli — disabled', () => {+ test('check → exit 0 + refusal on stderr, no compute', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ const { connect, calls } = thunkFor(stubEngine({ kind: 'pglite', pages: 42 }));++ const r = await run(['check'], connect);++ expect(r.exitCode).toBe(0);+ expect(r.stderr).toContain('backup check is disabled');+ expect(calls()).toBe(0);+ expect(existsSync(statusPath)).toBe(false);+ });++ test('status with warn cache → cache-only reader (thunk never called), exit 0 (cron-safe), no impression', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ saveBackupStatus(mkStatus('warn', new Date(Date.now() - 60_000).toISOString()));+ const { connect, calls } = thunkFor(stubEngine({}));++ const r = await run(['status'], connect);++ expect(calls()).toBe(0); // disabled silences COMPUTE — no engine touch+ // Disabled means silent for automation too: a stale warn cache that can+ // never refresh must not fail crons with exit 1.+ expect(r.exitCode).toBe(0);+ // The verdict + note text still render unchanged for the human reader…+ expect(r.stdout).toContain('backup coverage — WARN');+ expect(r.stdout).toContain('backup check disabled — verdict from cache only');+ // …but no 'status' nag impression is recorded while disabled.+ expect(existsSync(nagPath)).toBe(false);+ });+});++// ── --json payload ───────────────────────────────────────────────────────────++describe('runBackupCli --json', () => {+ test('recovery field carries recoverable_repos / pages_at_risk / statement', async () => {+ const { connect } = thunkFor(stubEngine({}));++ const r = await run(['check', '--json'], connect);++ expect(r.exitCode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ overall: string;+ recovery: { recoverable_repos: number; pages_at_risk: number; statement: string };+ };+ expect(payload.overall).toBe('ok');+ expect(payload.recovery.recoverable_repos).toBe(0);+ expect(payload.recovery.pages_at_risk).toBe(0);+ expect(payload.recovery.statement).toContain('What survives a disk loss today');+ });++ test('degraded compute passes degraded:true through and is never persisted', async () => {+ // sources query throws, pages query works → computeBackupCoverage marks+ // the verdict degraded; with no prior cache it is returned but NOT cached.+ const { connect, calls } = thunkFor(stubEngine({ sourcesThrow: true, pages: 5 }));++ const r = await run(['check', '--json'], connect);++ expect(calls()).toBe(1);+ const payload = JSON.parse(r.stdout) as { degraded?: boolean };+ expect(payload.degraded).toBe(true);+ expect(existsSync(statusPath)).toBe(false); // degraded verdicts never persist+ expect(r.exitCode).toBe(0); // degraded suppresses the db_content warn+ });+});++// ── Nag impression on warn ───────────────────────────────────────────────────++describe('runBackupCli — nag impression', () => {+ test("a warn verdict records a 'status' impression in backup-nag-state.json", async () => {+ const { connect } = thunkFor(stubEngine({ kind: 'pglite', pages: 42 }));++ const r = await run(['check'], connect);+ expect(r.exitCode).toBe(1);++ expect(existsSync(nagPath)).toBe(true);+ const nag = JSON.parse(readFileSync(nagPath, 'utf-8')) as {+ schema_version: string;+ entries: Array<{ pack_name: string; source_id: string }>;+ last_shown_at?: string;+ global_shown_count?: number;+ };+ expect(nag.schema_version).toBe('gbrain-backup-nag-v1');+ expect(nag.entries.some((e) => e.pack_name === 'status' && e.source_id === 'backup')).toBe(true);+ expect(nag.last_shown_at).toBeDefined();+ expect(nag.global_shown_count).toBe(1);+ });++ test('an ok verdict records nothing', async () => {+ const { connect } = thunkFor(stubEngine({}));+ const r = await run(['check'], connect);+ expect(r.exitCode).toBe(0);+ expect(existsSync(nagPath)).toBe(false);+ });+});diff --git a/test/backup-coverage.serial.test.ts b/test/backup-coverage.serial.test.tsnew file mode 100644index 0000000000..30087a13f4--- /dev/null+++ b/test/backup-coverage.serial.test.ts@@ -0,0 +1,818 @@+/**+ * backup-coverage.test.ts — pins src/core/backup/coverage.ts:+ * computeBackupCoverage asset classification (source repos probed via real+ * tmp git fixtures, bootstrap workspace via the receipt file, db_only tiering+ * via gbrain.yml, the DB-only-brain worst case), the getBackupStatus cache+ * choke point (probed persists, probe-less never persists, failed compute+ * never clobbers), and the serve-side single-flight refresher.+ *+ * Engine is a minimal executeRaw stub cast to BrainEngine (no real PGLite);+ * loadAllSources + countLivePages are distinguished by SQL substring.+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import type { BrainEngine } from '../src/core/engine.ts';+import {+ computeBackupCoverage,+ getBackupStatus,+ maybeRefreshBackupStatusInProcess,+ __resetBackupRefreshForTests,+} from '../src/core/backup/coverage.ts';+import { pushStatusPathForRoot } from '../src/core/workspace-push.ts';+import {+ saveBridgeState,+ SKILLPACK_BRIDGE_SCHEMA_VERSION,+} from '../src/core/skillpack/bridge-state.ts';+import {+ BACKUP_STATUS_SCHEMA_VERSION,+ __setBackupIntervalForTests,+ __setBackupNagStatePathForTests,+ __setBackupStatusPathForTests,+ invalidateBackupStatus,+ loadBackupStatus,+ saveBackupStatus,+ type BackupStatus,+} from '../src/core/backup/status-file.ts';++const ENV_KEYS = [+ 'GBRAIN_HOME',+ 'GBRAIN_BACKUP_CHECK',+ 'GBRAIN_BACKUP_CHECK_DAYS',+ 'GBRAIN_BRAIN_ID',+ 'DATABASE_URL',+ 'GBRAIN_DATABASE_URL',+ 'GBRAIN_SOURCE',+ 'GBRAIN_SKIP_STARTUP_HOOKS',+] as const;++let tmp: string;+let saved: Record<string, string | undefined>;+let statusPath: string;++const home = () => join(tmp, '.gbrain');++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-bkcov-'));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp; // configDir() === tmp/.gbrain+ statusPath = join(home(), 'backup-status.json');+ __setBackupStatusPathForTests(statusPath);+ __setBackupNagStatePathForTests(join(home(), 'backup-nag-state.json'));+ __resetBackupRefreshForTests();+});++afterEach(() => {+ __setBackupStatusPathForTests(null);+ __setBackupNagStatePathForTests(null);+ __setBackupIntervalForTests(null);+ __resetBackupRefreshForTests();+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++// ── Fixtures ─────────────────────────────────────────────────────────────────++function g(dir: string, args: string[]): void {+ execFileSync('git', ['-C', dir, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });+}++function initRepo(dir: string): void {+ mkdirSync(dir, { recursive: true });+ execFileSync('git', ['init', '-b', 'main', dir], { stdio: ['ignore', 'pipe', 'pipe'] });+ g(dir, ['config', 'user.email', '[email protected]']);+ g(dir, ['config', 'user.name', 'Test User']);+ g(dir, ['config', 'commit.gpgsign', 'false']);+}++function commitFile(dir: string, name: string, content: string, msg: string): void {+ writeFileSync(join(dir, name), content);+ g(dir, ['add', '.']);+ g(dir, ['commit', '-m', msg]);+}++/** SourceRow shape per src/core/sources-load.ts:192-226. */+function srcRow(id: string, localPath: string | null, extra: Record<string, unknown> = {}) {+ return {+ id,+ name: id,+ local_path: localPath,+ last_commit: null,+ last_sync_at: null,+ config: {},+ created_at: new Date(),+ archived: false,+ newest_content_at: null,+ ...extra,+ };+}++function stubEngine(opts: {+ kind?: 'pglite' | 'postgres';+ sources?: unknown[];+ pages?: number;+ onCall?: () => void;+} = {}): BrainEngine {+ return {+ kind: opts.kind ?? 'pglite',+ executeRaw: async (sql: string) => {+ opts.onCall?.();+ if (sql.includes('FROM pages')) return [{ n: opts.pages ?? 0 }];+ if (sql.includes('FROM sources')) return opts.sources ?? [];+ return [];+ },+ } as unknown as BrainEngine;+}++function writeReceipt(ws: string, extra: Record<string, unknown> = {}): void {+ const dir = join(home(), 'bootstrap');+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, 'receipt.json'),+ JSON.stringify(+ {+ receipt_version: 1,+ workspace_dir: ws,+ source_id: 'workspace',+ agent_name: 'agent-example',+ created_at: new Date().toISOString(),+ created_by: 'test',+ brain_created_by_bootstrap: false,+ created_paths: [],+ registrations: [],+ ...extra,+ },+ null,+ 2,+ ),+ );+}++/** Hand-built cache verdict that passes loadBackupStatus validation. */+function mkStatus(overall: 'ok' | 'warn', checkedAt: string): BackupStatus {+ const noRemote = overall === 'warn' ? 1 : 0;+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: checkedAt,+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall,+ totals: {+ assets: noRemote,+ no_remote: noRemote,+ unpushed: 0,+ failing: 0,+ recoverable_repos: 0,+ pages_at_risk: 0,+ },+ assets:+ overall === 'warn'+ ? [{ kind: 'source_repo', id: 'stale-example', state: 'no_remote', fix_argv: null }]+ : [],+ };+}++function sleep(ms: number): Promise<void> {+ return new Promise((r) => setTimeout(r, ms));+}++async function pollUntil(fn: () => boolean, timeoutMs = 2000): Promise<boolean> {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ if (fn()) return true;+ await sleep(25);+ }+ return fn();+}++// ── Source-repo probing ──────────────────────────────────────────────────────++describe('computeBackupCoverage — source repos', () => {+ test('repo without origin → no_remote asset, overall warn', async () => {+ const repo = join(tmp, 'repo-a');+ initRepo(repo);+ commitFile(repo, 'a.md', 'hello', 'init');+ const engine = stubEngine({ sources: [srcRow('src-a', repo)] });++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'source_repo');+ expect(asset).toBeDefined();+ expect(asset?.id).toBe('src-a');+ expect(asset?.state).toBe('no_remote');+ expect(asset?.detail).toContain('git remote add origin');+ expect(asset?.fix_argv).toBeNull(); // no bootstrap manifest → recipe only+ expect(s.overall).toBe('warn');+ expect(s.totals.no_remote).toBe(1);+ });++ test('repo one commit ahead of a local bare origin → unpushed, overall stays ok', async () => {+ const bare = join(tmp, 'bare.git');+ execFileSync('git', ['init', '--bare', '-b', 'main', bare], { stdio: ['ignore', 'pipe', 'pipe'] });+ const work = join(tmp, 'work');+ initRepo(work);+ commitFile(work, 'a.md', 'baseline', 'baseline');+ g(work, ['remote', 'add', 'origin', bare]);+ g(work, ['push', '-u', 'origin', 'main']);+ commitFile(work, 'b.md', 'more', 'ahead commit');++ const engine = stubEngine({ sources: [srcRow('src-work', work)] });+ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'source_repo');+ expect(asset?.state).toBe('unpushed');+ expect(asset?.ahead).toBeGreaterThanOrEqual(1);+ expect(asset?.detail).toContain('ahead of origin/');+ expect(s.totals.unpushed).toBe(1);+ expect(s.totals.no_remote).toBe(0);+ expect(s.overall).toBe('ok'); // unpushed does NOT flip warn+ });++ test('localGitProbes:false → unknown assets and getBackupStatus never persists', async () => {+ const repo = join(tmp, 'repo-np');+ initRepo(repo);+ commitFile(repo, 'a.md', 'x', 'init');+ const engine = stubEngine({ sources: [srcRow('src-np', repo)] });++ const s = await getBackupStatus(engine, { localGitProbes: false });++ const asset = s.assets.find((a) => a.kind === 'source_repo');+ expect(asset?.state).toBe('unknown');+ expect(asset?.detail).toBe('probes_skipped');+ expect(existsSync(statusPath)).toBe(false); // probe-less computes are never persisted+ });++ test('archived + null-path sources are skipped; a MISSING local_path surfaces as an unknown asset', async () => {+ const repo = join(tmp, 'repo-archived');+ initRepo(repo);+ commitFile(repo, 'a.md', 'x', 'init');+ const engine = stubEngine({+ sources: [+ srcRow('archived-src', repo, { archived: true }),+ srcRow('ghost-src', join(tmp, 'no-such-dir')),+ srcRow('null-path-src', null),+ ],+ });++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ // The most disk-loss-adjacent state of all: a registered path that is GONE+ // is surfaced ('unknown' — it may live on another machine), never silently+ // skipped. Archived and null-path rows still produce nothing.+ const repos = s.assets.filter((a) => a.kind === 'source_repo');+ expect(repos).toHaveLength(1);+ expect(repos[0]?.id).toBe('ghost-src');+ expect(repos[0]?.state).toBe('unknown');+ expect(repos[0]?.detail).toBe('local_path not found on this machine');+ expect(repos[0]?.fix_argv).toBeNull();+ expect(s.totals.assets).toBe(1); // the missing-path asset IS counted+ expect(s.overall).toBe('ok'); // unknown never flips warn+ });++ test('remote added but NOTHING pushed → no_remote (nothing pushed), overall warn', async () => {+ // The half-completed `git remote add` state: origin exists but+ // origin/<branch> is unresolvable — zero recoverable history on the+ // remote, so it must WARN, not read ok.+ const bare = join(tmp, 'never-pushed-origin.git');+ execFileSync('git', ['init', '--bare', '-b', 'main', bare], { stdio: ['ignore', 'pipe', 'pipe'] });+ const work = join(tmp, 'never-pushed');+ initRepo(work);+ commitFile(work, 'a.md', 'unpushed history', 'init');+ g(work, ['remote', 'add', 'origin', bare]); // deliberately NO push++ const engine = stubEngine({ sources: [srcRow('src-never-pushed', work)] });+ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'source_repo');+ expect(asset?.id).toBe('src-never-pushed');+ expect(asset?.state).toBe('no_remote');+ expect(asset?.detail).toContain('nothing pushed');+ expect(asset?.detail).toContain('git push -u origin');+ expect(asset?.fix_argv).toBeNull();+ expect(s.overall).toBe('warn');+ expect(s.totals.no_remote).toBe(1);+ expect(s.totals.recoverable_repos).toBe(0); // nothing on the remote to recover+ });++ test('gbrain.yml storage.db_only tiering → info asset with the export fix', async () => {+ const repo = join(tmp, 'repo-tiered');+ initRepo(repo);+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_only:\n - private/\n');+ commitFile(repo, 'a.md', 'x', 'init');+ const engine = stubEngine({ sources: [srcRow('tiered-src', repo)] });++ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'db_only');+ expect(asset).toBeDefined();+ expect(asset?.id).toBe('tiered-src');+ expect(asset?.state).toBe('info');+ expect(asset?.fix_argv).toEqual(['gbrain', 'export', '--dir', '<backup-dir>']);+ });+});++// ── DB-only brain + empty brain ──────────────────────────────────────────────++describe('computeBackupCoverage — db_content and empty brain', () => {+ test('pglite brain with pages but no sources/receipt → db_content no_remote, pages at risk', async () => {+ const engine = stubEngine({ kind: 'pglite', pages: 42 });+ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'db_content');+ expect(asset?.state).toBe('no_remote');+ expect(asset?.detail).toContain('42 pages');+ expect(asset?.fix_argv).toEqual(['gbrain', 'bootstrap', 'repo']);+ expect(s.totals.pages_at_risk).toBe(42);+ expect(s.overall).toBe('warn');+ });++ test('postgres brain with pages but no sources/receipt → db_content info, overall ok', async () => {+ const engine = stubEngine({ kind: 'postgres', pages: 42 });+ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'db_content');+ expect(asset?.state).toBe('info');+ expect(s.totals.pages_at_risk).toBe(0);+ expect(s.overall).toBe('ok');+ });++ test('empty brain (0 pages, no sources, no receipt) → ok and never warn', async () => {+ const s = await computeBackupCoverage(stubEngine({}), { localGitProbes: true });++ expect(s.overall).toBe('ok');+ expect(s.totals.assets).toBe(0);+ expect(s.totals.pages_at_risk).toBe(0);+ // Zero assets, or only info assets — never a warn-carrying state.+ expect(s.assets.every((a) => a.state === 'info')).toBe(true);+ });+});++// ── Bootstrap workspace via the receipt ─────────────────────────────────────++describe('computeBackupCoverage — bootstrap workspace', () => {+ test('receipt without repo_url → bootstrap_workspace no_remote with bootstrap repo fix', async () => {+ const ws = join(tmp, 'ws');+ mkdirSync(ws, { recursive: true });+ writeReceipt(ws);++ const s = await computeBackupCoverage(stubEngine({}), { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'bootstrap_workspace');+ expect(asset).toBeDefined();+ expect(asset?.id).toBe(ws);+ expect(asset?.state).toBe('no_remote');+ expect(asset?.fix_argv).toEqual(['gbrain', 'bootstrap', 'repo']);+ expect(s.overall).toBe('warn');+ expect(s.totals.no_remote).toBe(1);+ });++ test('receipt with repo_url and no failing push statuses → bootstrap_workspace ok', async () => {+ const ws = join(tmp, 'ws');+ mkdirSync(ws, { recursive: true });+ writeReceipt(ws, { repo_url: 'https://example.com/acme-example/brain.git' });++ const s = await computeBackupCoverage(stubEngine({}), { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'bootstrap_workspace');+ expect(asset?.state).toBe('ok');+ expect(s.overall).toBe('ok');+ expect(s.totals.recoverable_repos).toBe(1);+ });+});++// ── getBackupStatus caching ──────────────────────────────────────────────────++describe('getBackupStatus — cache choke point', () => {+ test('probed compute persists; fresh cache short-circuits; forceRefresh recomputes', async () => {+ const t0 = new Date('2026-08-01T00:00:00.000Z');+ const first = await getBackupStatus(stubEngine({}), { localGitProbes: true, now: t0 });+ expect(existsSync(statusPath)).toBe(true);+ expect(first.checked_at).toBe(t0.toISOString());+ expect(loadBackupStatus()?.checked_at).toBe(t0.toISOString());++ // Fresh cache is returned as-is: a throwing engine is never even touched,+ // and the persisted verdict is not clobbered.+ let throwCalls = 0;+ const throwing = {+ kind: 'pglite',+ executeRaw: async () => {+ throwCalls++;+ throw new Error('boom');+ },+ } as unknown as BrainEngine;+ const second = await getBackupStatus(throwing, {+ localGitProbes: true,+ now: new Date(t0.getTime() + 60_000),+ });+ expect(second.checked_at).toBe(first.checked_at);+ expect(throwCalls).toBe(0);+ expect(loadBackupStatus()?.checked_at).toBe(first.checked_at);++ // forceRefresh + working engine recomputes and re-persists.+ const t1 = new Date(t0.getTime() + 60 * 60 * 1000);+ const third = await getBackupStatus(stubEngine({}), {+ localGitProbes: true,+ now: t1,+ forceRefresh: true,+ });+ expect(third.checked_at).toBe(t1.toISOString());+ expect(loadBackupStatus()?.checked_at).toBe(t1.toISOString());+ });++ test('a failed compute never clobbers — the prior cached verdict is returned', async () => {+ const t0 = new Date('2026-08-01T00:00:00.000Z');+ const first = await getBackupStatus(stubEngine({}), { localGitProbes: true, now: t0 });+ expect(loadBackupStatus()?.checked_at).toBe(first.checked_at);++ // Inject a mid-compute throw through the public API: an Invalid Date+ // makes computeBackupCoverage's checked_at serialization throw, so+ // getBackupStatus must fall back to the prior cache, not clobber it.+ const out = await getBackupStatus(stubEngine({}), {+ localGitProbes: true,+ forceRefresh: true,+ now: new Date('not-a-date'),+ });+ expect(out.checked_at).toBe(first.checked_at); // prior verdict returned+ expect(loadBackupStatus()?.checked_at).toBe(first.checked_at); // never clobbered++ // With no prior cache the same failure propagates to the caller.+ rmSync(statusPath, { force: true });+ await expect(+ getBackupStatus(stubEngine({}), {+ localGitProbes: true,+ forceRefresh: true,+ now: new Date('not-a-date'),+ }),+ ).rejects.toThrow();+ });+});++// ── countLivePages: an unestablished count is DEGRADED, never a fake zero ────++describe('computeBackupCoverage — pages count unestablished', () => {+ function pagesRowEngine(pagesRows: unknown[]): BrainEngine {+ return {+ kind: 'pglite',+ executeRaw: async (sql: string) => {+ if (sql.includes('FROM pages')) return pagesRows;+ if (sql.includes('FROM sources')) return [];+ return [];+ },+ } as unknown as BrainEngine;+ }++ test('empty rowset for the pages query → degraded verdict, never persisted', async () => {+ // Returning 0 would fabricate a "no pages at risk" all-clear; an empty+ // rowset is UNESTABLISHED and must degrade (and degraded never persists).+ const s = await getBackupStatus(pagesRowEngine([]), { localGitProbes: true, forceRefresh: true });+ expect(s.degraded).toBe(true);+ expect(s.totals.pages_at_risk).toBe(0);+ expect(s.assets.find((a) => a.kind === 'db_content')).toBeUndefined();+ expect(existsSync(statusPath)).toBe(false);+ });++ test('non-numeric n → degraded verdict, never persisted', async () => {+ const s = await getBackupStatus(pagesRowEngine([{ n: 'lots' }]), {+ localGitProbes: true,+ forceRefresh: true,+ });+ expect(s.degraded).toBe(true);+ expect(existsSync(statusPath)).toBe(false);+ });+});++// ── Host-brain scoping: the status cache has no brain dimension ──────────────++describe('getBackupStatus — host-brain cache scoping', () => {+ test('non-host GBRAIN_BRAIN_ID: computes fresh (never reads the cache) and never persists', async () => {+ // Seed a FRESH host warn cache (a minute old — well inside the interval,+ // but distinguishable from a same-millisecond fresh compute) — for the+ // host brain this would short-circuit the compute entirely.+ const hostCache = mkStatus('warn', new Date(Date.now() - 60_000).toISOString());+ saveBackupStatus(hostCache);++ process.env.GBRAIN_BRAIN_ID = 'some-team';+ const out = await getBackupStatus(stubEngine({}), { localGitProbes: true });++ // The mounted-brain call computed FRESH from the empty stub (ok), instead+ // of returning the host cache's warn…+ expect(out.overall).toBe('ok');+ expect(out.checked_at).not.toBe(hostCache.checked_at);+ // …and the pre-existing host cache is untouched (an empty mounted brain's+ // ok must never silence a real host warn).+ expect(loadBackupStatus()).toEqual(hostCache);++ // Unset restores normal behavior: the fresh host cache answers as-is.+ delete process.env.GBRAIN_BRAIN_ID;+ const back = await getBackupStatus(stubEngine({}), { localGitProbes: true });+ expect(back.checked_at).toBe(hostCache.checked_at);+ expect(back.overall).toBe('warn');+ });++ test('non-host brain + absent cache: a probed compute leaves the cache file absent', async () => {+ process.env.GBRAIN_BRAIN_ID = 'some-team';+ expect(existsSync(statusPath)).toBe(false);+ const out = await getBackupStatus(stubEngine({}), { localGitProbes: true, forceRefresh: true });+ expect(out.overall).toBe('ok');+ expect(out.degraded).toBeUndefined(); // a clean compute — just never saved+ expect(existsSync(statusPath)).toBe(false);+ });++ test("GBRAIN_BRAIN_ID='host' behaves exactly like unset (reads + persists)", async () => {+ process.env.GBRAIN_BRAIN_ID = 'host';+ const out = await getBackupStatus(stubEngine({}), { localGitProbes: true });+ expect(out.overall).toBe('ok');+ expect(existsSync(statusPath)).toBe(true);+ expect(loadBackupStatus()?.checked_at).toBe(out.checked_at);+ });+});++// ── Serve-side in-process refresher ──────────────────────────────────────────++describe('maybeRefreshBackupStatusInProcess', () => {+ test('absent cache → computes with probes and persists a serve-stamped verdict', async () => {+ const repo = join(tmp, 'repo-refresh');+ initRepo(repo);+ commitFile(repo, 'a.md', 'x', 'init');+ const engine = stubEngine({ sources: [srcRow('src-refresh', repo)] });++ expect(existsSync(statusPath)).toBe(false);+ maybeRefreshBackupStatusInProcess(engine);++ expect(await pollUntil(() => existsSync(statusPath))).toBe(true);+ const s = loadBackupStatus();+ expect(s?.computed_by).toBe('serve');+ expect(s?.overall).toBe('warn'); // fixture repo has no origin+ expect(s?.assets.some((a) => a.kind === 'source_repo' && a.state === 'no_remote')).toBe(true);+ });++ test('two synchronous calls single-flight into one compute', async () => {+ let calls = 0;+ const engine = stubEngine({ onCall: () => calls++ });++ maybeRefreshBackupStatusInProcess(engine);+ maybeRefreshBackupStatusInProcess(engine);++ expect(await pollUntil(() => existsSync(statusPath))).toBe(true);+ await sleep(100); // let any (wrongly) duplicated compute land+ // One compute = exactly two executeRaw calls (sources + pages), not four.+ expect(calls).toBe(2);+ });++ test('fresh ok cache → does nothing (engine never touched)', async () => {+ saveBackupStatus(mkStatus('ok', new Date().toISOString()));+ let calls = 0;+ const engine = stubEngine({ onCall: () => calls++ });++ maybeRefreshBackupStatusInProcess(engine);+ await sleep(150);++ expect(calls).toBe(0);+ });++ test('warn cache older than 24h → recomputes even though the cache is not interval-stale', async () => {+ const old = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();+ saveBackupStatus(mkStatus('warn', old));+ let calls = 0;+ const engine = stubEngine({ onCall: () => calls++ });++ maybeRefreshBackupStatusInProcess(engine);++ expect(await pollUntil(() => loadBackupStatus()?.checked_at !== old)).toBe(true);+ expect(calls).toBeGreaterThanOrEqual(2);+ const s = loadBackupStatus();+ expect(s?.overall).toBe('ok'); // the empty brain no longer warns+ expect(Date.parse(s!.checked_at)).toBeGreaterThan(Date.parse(old));+ });+});++// ── Dirty working tree, shared roots, non-repo paths ─────────────────────────++describe('computeBackupCoverage — dirty tree, shared git roots, non-repo paths', () => {+ test('origin-backed pushed repo with a modified tracked file → dirty, overall stays ok', async () => {+ const bare = join(tmp, 'dirty-bare.git');+ execFileSync('git', ['init', '--bare', '-b', 'main', bare], { stdio: ['ignore', 'pipe', 'pipe'] });+ const work = join(tmp, 'dirty-work');+ initRepo(work);+ commitFile(work, 'a.md', 'clean state', 'baseline');+ g(work, ['remote', 'add', 'origin', bare]);+ g(work, ['push', '-u', 'origin', 'main']);+ writeFileSync(join(work, 'a.md'), 'modified but not committed'); // dirty, NOT ahead++ const engine = stubEngine({ sources: [srcRow('src-dirty', work)] });+ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'source_repo');+ expect(asset?.id).toBe('src-dirty');+ expect(asset?.state).toBe('dirty');+ expect(asset?.detail).toBe('uncommitted changes');+ expect(asset?.fix_argv).toBeNull();+ expect(s.overall).toBe('ok'); // dirty does NOT flip warn — only no_remote does+ expect(s.totals.no_remote).toBe(0);+ expect(s.totals.unpushed).toBe(0);+ // dirty is still recoverable_repos (origin exists; only the delta is at risk)+ expect(s.totals.recoverable_repos).toBe(1);+ });++ test('two sources in the SAME git repo (root + subdir) dedupe to ONE probed asset with joined ids', async () => {+ const repo = join(tmp, 'shared-root');+ initRepo(repo);+ mkdirSync(join(repo, 'docs'), { recursive: true });+ writeFileSync(join(repo, 'docs', 'inner.md'), 'inner');+ commitFile(repo, 'a.md', 'x', 'init'); // commits a.md + docs/inner.md++ const engine = stubEngine({+ sources: [srcRow('root-src', repo), srcRow('sub-src', join(repo, 'docs'))],+ });+ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const repos = s.assets.filter((a) => a.kind === 'source_repo');+ expect(repos).toHaveLength(1); // one git root → one probed asset+ expect(repos[0]?.id).toBe('root-src, sub-src');+ expect(repos[0]?.state).toBe('no_remote'); // fixture repo has no origin+ expect(s.totals.no_remote).toBe(1); // counted once, not per source+ expect(s.overall).toBe('warn');+ });++ test('existing plain directory (not a git repo) → unknown/not_a_git_repo; memoized per path, one asset PER SOURCE', async () => {+ const plain = join(tmp, 'plain-dir');+ mkdirSync(plain, { recursive: true });+ writeFileSync(join(plain, 'notes.md'), 'not under git');++ // Two sources at the SAME non-repo path: discovery is memoized (one+ // subprocess), but EVERY source at the known non-repo path still gets its+ // own asset row — the second source is no longer silently dropped.+ const engine = stubEngine({+ sources: [srcRow('plain-src', plain), srcRow('plain-src-dup', plain)],+ });+ const s = await computeBackupCoverage(engine, { localGitProbes: true });++ const repos = s.assets.filter((a) => a.kind === 'source_repo');+ expect(repos).toHaveLength(2);+ expect(repos.map((a) => a.id).sort()).toEqual(['plain-src', 'plain-src-dup']);+ for (const a of repos) {+ expect(a.state).toBe('unknown');+ expect(a.detail).toBe('not_a_git_repo');+ expect(a.fix_argv).toBeNull();+ }+ expect(s.overall).toBe('ok'); // unknown never flips warn+ expect(s.totals.no_remote).toBe(0);+ });+});++// ── Bootstrap workspace: failing push status ─────────────────────────────────++describe('computeBackupCoverage — bootstrap workspace failing push', () => {+ test('receipt WITH repo_url + a failing per-root push-status → failing asset with sanitized detail', async () => {+ const ws = join(tmp, 'ws-failing');+ mkdirSync(ws, { recursive: true }); // repoRoot must exist or the ghost filter drops the entry+ writeReceipt(ws, { repo_url: 'https://example.com/acme-example/brain.git' });++ // A failing per-root status via the real path helper (workspace-push.ts).+ // The reason carries hostile chars: sanitizePushReason must strip them+ // before the detail reaches any human/model-visible surface.+ const statusFile = pushStatusPathForRoot(ws);+ mkdirSync(join(home(), 'bootstrap'), { recursive: true });+ writeFileSync(+ statusFile,+ JSON.stringify({+ ts: new Date().toISOString(),+ ok: false,+ reason: 'push failed: `rm -rf` $HOME \u0007beep',+ repoRoot: ws,+ }),+ );++ const s = await computeBackupCoverage(stubEngine({}), { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'bootstrap_workspace');+ expect(asset).toBeDefined();+ expect(asset?.id).toBe(ws);+ expect(asset?.state).toBe('failing');+ // Sanitized: backticks/$ replaced, non-printables spaced, content kept.+ expect(asset?.detail).toContain('push failed');+ expect(asset?.detail).toContain("'rm -rf'");+ expect(asset?.detail).not.toContain('`');+ expect(asset?.detail).not.toContain('$');+ expect(asset?.detail).not.toContain('\u0007');+ expect(asset?.fix_argv).toEqual(['gbrain', 'sources', 'push', '--path', ws]);+ expect(s.totals.failing).toBe(1);+ expect(s.overall).toBe('ok'); // failing is not no_remote — the remote exists+ // A failing push means the remote is BEHIND: counting it recoverable would+ // overstate the recovery statement, so recoverable_repos excludes it.+ expect(s.totals.recoverable_repos).toBe(0);+ });++ test("a failing push status for a DIFFERENT root leaves the workspace ok", async () => {+ const ws = join(tmp, 'ws-healthy');+ mkdirSync(ws, { recursive: true });+ writeReceipt(ws, { repo_url: 'https://example.com/acme-example/brain.git' });++ // A failing status for some OTHER push-tracked repo (root exists, so the+ // ghost filter keeps the entry alive) — the workspace verdict reads ONLY+ // its own per-root status and must not inherit this failure.+ const other = join(tmp, 'other-root');+ mkdirSync(other, { recursive: true });+ mkdirSync(join(home(), 'bootstrap'), { recursive: true });+ writeFileSync(+ pushStatusPathForRoot(other),+ JSON.stringify({ ts: new Date().toISOString(), ok: false, reason: 'push failed elsewhere', repoRoot: other }),+ );++ const s = await computeBackupCoverage(stubEngine({}), { localGitProbes: true });++ const asset = s.assets.find((a) => a.kind === 'bootstrap_workspace');+ expect(asset).toBeDefined();+ expect(asset?.state).toBe('ok');+ expect(s.totals.failing).toBe(0);+ expect(s.totals.recoverable_repos).toBe(1);+ expect(s.overall).toBe('ok');+ });+});++// ── Harness skills (bridge-state ledger) ─────────────────────────────────────++describe('computeBackupCoverage — harness_skills info row', () => {+ test('bridge state with one entry → one harness_skills info asset', async () => {+ // Written through the real saver so the fixture matches the BridgeState+ // schema loadBridgeState validates (schema_version + entries shape).+ saveBridgeState({+ schema_version: SKILLPACK_BRIDGE_SCHEMA_VERSION,+ entries: [+ {+ harness: 'claude-code',+ dest: join(tmp, 'harness-skills-dest'),+ last_persona: null,+ last_mode: 'full',+ written: { 'query-skill': { mode: 'full', files: { 'SKILL.md': 'abc123' } } },+ gbrain_version: '0.0.0-test',+ installed_at: '2026-08-01T00:00:00.000Z',+ updated_at: '2026-08-01T00:00:00.000Z',+ },+ ],+ });++ const s = await computeBackupCoverage(stubEngine({}), { localGitProbes: true });++ const rows = s.assets.filter((a) => a.kind === 'harness_skills');+ expect(rows).toHaveLength(1);+ expect(rows[0]?.id).toBe('1 harness skill dir(s)');+ expect(rows[0]?.state).toBe('info');+ expect(rows[0]?.detail).toContain('installed copies');+ expect(rows[0]?.fix_argv).toBeNull();+ expect(s.overall).toBe('ok'); // info never warns+ });+});++describe('degraded verdict never clobbers a probed cache', () => {+ test('forceRefresh against a broken engine keeps the prior warn cache', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gb-bkc-degraded-'));+ const prevHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = home;+ try {+ const warn: BackupStatus = {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: new Date().toISOString(),+ gbrain_version: '0.0.0',+ interval_days: 30,+ computed_by: 'cli',+ overall: 'warn',+ totals: { assets: 1, no_remote: 1, unpushed: 0, failing: 0, recoverable_repos: 0, pages_at_risk: 0 },+ assets: [{ kind: 'source_repo', id: 'kept-repo', state: 'no_remote', fix_argv: null }],+ };+ saveBackupStatus(warn);+ const broken = {+ kind: 'pglite',+ executeRaw: async () => {+ throw new Error('engine down');+ },+ } as unknown as BrainEngine;+ const out = await getBackupStatus(broken, { localGitProbes: true, forceRefresh: true });+ // The degraded empty verdict is discarded in favor of the cached warn…+ expect(out.overall).toBe('warn');+ expect(out.assets[0]?.id).toBe('kept-repo');+ // …and the cache file itself is untouched (no clobber).+ expect(loadBackupStatus()?.overall).toBe('warn');+ // With NO cache, the degraded verdict is returned but never persisted.+ invalidateBackupStatus();+ const degraded = await getBackupStatus(broken, { localGitProbes: true, forceRefresh: true });+ expect(degraded.degraded).toBe(true);+ expect(loadBackupStatus()).toBeNull();+ } finally {+ if (prevHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prevHome;+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/test/backup-invalidation.serial.test.ts b/test/backup-invalidation.serial.test.tsnew file mode 100644index 0000000000..3b30152519--- /dev/null+++ b/test/backup-invalidation.serial.test.ts@@ -0,0 +1,309 @@+/**+ * Fix-path invalidation call sites for the monthly backup-coverage cache+ * (src/core/backup/status-file.ts invalidateBackupStatus):+ *+ * 1. workspace-push — the finish() choke point: EVERY successful push drops+ * the cached verdict; failing/blocked/refused pushes and clean lock-skips+ * leave it untouched. Pinned with REAL behavior: a tmp git repo + local+ * bare origin (the workspace-push.serial.test.ts fixture idiom).+ * 2. sources harden — after the harden loop, a run that produced >=1 report+ * invalidates; a run whose rows were all skipped (no git repo) does not.+ * Pinned with REAL behavior via a stub engine + --dry-run (dry-run is+ * fully offline: pull/verify skipped, --no-cron, writes suppressed).+ * 3. bootstrap repo — recordRepoInReceipt is module-private and driving the+ * full `bootstrap repo` flow needs gh + a pushable GitHub remote, which+ * is infeasible here. Pinned as an explicit SOURCE-TEXT contract instead+ * (see the last describe block for why).+ *+ * Isolation: tmp HOME + GBRAIN_HOME per test, env save/restore, and the+ * __setBackupStatusPathForTests seam so the real ~/.gbrain is never touched.+ * GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1 lets the SSRF-flagged push use the file+ * transport (same knob as workspace-push.serial.test.ts).+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { execFileSync } from 'node:child_process';++import { workspacePush, acquirePushLock } from '../src/core/workspace-push.ts';+import { runHarden } from '../src/commands/sources-harden.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import {+ BACKUP_STATUS_SCHEMA_VERSION,+ loadBackupStatus,+ saveBackupStatus,+ __setBackupStatusPathForTests,+ type BackupStatus,+} from '../src/core/backup/status-file.ts';++const T = 60_000; // explicit per-test timeout — bun ignores bunfig.toml's key++// #2943: env: process.env is REQUIRED — Bun snapshots env at startup, so+// spawned git would otherwise be blind to beforeEach's HOME/GBRAIN_HOME swap.+function git(cwd: string, ...args: string[]): string {+ return execFileSync('git', ['-C', cwd, '-c', 'protocol.file.allow=always', ...args], {+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', env: process.env,+ }).trim();+}++const ENV_KEYS = [+ 'HOME',+ 'GBRAIN_HOME',+ 'GBRAIN_GIT_ALLOW_FILE_TRANSPORT',+ 'GBRAIN_ALLOW_UNVERIFIED_REMOTE',+ 'GBRAIN_GITHUB_PAT',+ 'GBRAIN_BACKUP_CHECK',+] as const;++let root: string;+let work: string;+let bare: string;+let statusPath: string;+let saved: Record<string, string | undefined> = {};+let savedExitCode: typeof process.exitCode;++function makePair(): void {+ bare = mkdtempSync(join(root, 'origin-')) + '.git';+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare], { stdio: 'ignore', env: process.env });+ work = mkdtempSync(join(root, 'work-'));+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, work], {+ stdio: 'ignore', env: process.env,+ });+ git(work, 'config', 'user.email', '[email protected]');+ git(work, 'config', 'user.name', 'tester');+ writeFileSync(join(work, 'README.md'), 'init\n');+ git(work, 'add', 'README.md');+ git(work, 'commit', '-qm', 'init');+ git(work, 'push', '-q', 'origin', 'main');+ try { git(work, 'remote', 'set-head', 'origin', 'main'); } catch { /* */ }+}++/** A warn verdict to seed the cache with — generic ids only (privacy rule). */+function warnStatus(): BackupStatus {+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: new Date().toISOString(),+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall: 'warn',+ totals: { assets: 2, no_remote: 1, unpushed: 0, failing: 0, recoverable_repos: 1, pages_at_risk: 0 },+ assets: [+ { kind: 'source_repo', id: 'wiki', state: 'no_remote', fix_argv: null },+ { kind: 'source_repo', id: 'notes', state: 'ok' },+ ],+ };+}++function seedWarnCache(): void {+ saveBackupStatus(warnStatus());+ expect(loadBackupStatus()).not.toBeNull(); // sanity: the seed took+}++/** A fully-healthy verdict: overall ok, zero failing, zero unpushed. */+function okStatus(over: Partial<BackupStatus['totals']> = {}): BackupStatus {+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: new Date().toISOString(),+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall: 'ok',+ totals: {+ assets: 1, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 1, pages_at_risk: 0,+ ...over,+ },+ assets: [{ kind: 'source_repo', id: 'notes', state: 'ok' }],+ };+}++/** Mute console.log/console.error for the duration (runHarden is chatty). */+async function muted<TReturn>(fn: () => Promise<TReturn>): Promise<TReturn> {+ const origLog = console.log;+ const origErr = console.error;+ console.log = () => {};+ console.error = () => {};+ try {+ return await fn();+ } finally {+ console.log = origLog;+ console.error = origErr;+ }+}++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'gb-backup-inv-'));+ saved = {};+ for (const k of ENV_KEYS) saved[k] = process.env[k];+ savedExitCode = process.exitCode;+ process.env.HOME = mkdtempSync(join(root, 'home-'));+ // CX2-8: GBRAIN_HOME is a PARENT dir → effective home is $HOME/.gbrain.+ process.env.GBRAIN_HOME = process.env.HOME;+ process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';+ delete process.env.GBRAIN_ALLOW_UNVERIFIED_REMOTE;+ delete process.env.GBRAIN_GITHUB_PAT;+ delete process.env.GBRAIN_BACKUP_CHECK;+ statusPath = join(root, 'backup-status.json');+ __setBackupStatusPathForTests(statusPath);+ makePair();+});++afterEach(() => {+ __setBackupStatusPathForTests(null);+ _resetCliExitVerdictForTests();+ process.exitCode = savedExitCode;+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ rmSync(root, { recursive: true, force: true });+});++describe('workspace-push finish() choke point', () => {+ test('a successful push invalidates the cached verdict', async () => {+ seedWarnCache();+ writeFileSync(join(work, 'note.md'), 'remember this\n');+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });+ expect(r.ok).toBe(true);+ expect(r.status).toBe('pushed');+ expect(loadBackupStatus()).toBeNull();+ expect(existsSync(statusPath)).toBe(false); // the file itself is gone+ }, T);++ test('a successful push with NOTHING new to commit still invalidates (finish sees r.ok)', async () => {+ // Local ahead of origin by one prior commit; clean tree → committed:false+ // but the push succeeds — the coverage answer changed (unpushed→pushed).+ writeFileSync(join(work, 'ahead.md'), 'x\n');+ git(work, 'add', 'ahead.md');+ git(work, 'commit', '-qm', 'local-only');+ seedWarnCache();+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });+ expect(r.ok).toBe(true);+ expect(r.committed).toBe(false);+ expect(loadBackupStatus()).toBeNull();+ }, T);++ test('an OK cache with zero failing/unpushed SURVIVES a successful push (guarded invalidation)', async () => {+ // The routine healthy stop-push must not delete an ok cache every session —+ // that would defeat the monthly compute throttle for the healthiest cohort.+ const seed = okStatus();+ saveBackupStatus(seed);+ writeFileSync(join(work, 'note.md'), 'healthy session\n');+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });+ expect(r.ok).toBe(true);+ expect(r.status).toBe('pushed');+ expect(loadBackupStatus()).toEqual(seed); // cache untouched+ expect(existsSync(statusPath)).toBe(true);+ }, T);++ test('an ok cache carrying unpushed>0 IS invalidated by a successful push (the push fixed it)', async () => {+ saveBackupStatus(okStatus({ unpushed: 1 }));+ writeFileSync(join(work, 'note.md'), 'catching up\n');+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });+ expect(r.ok).toBe(true);+ expect(loadBackupStatus()).toBeNull(); // unpushed→pushed changed the answer+ }, T);++ test('an ok cache carrying failing>0 IS invalidated by a successful push', async () => {+ saveBackupStatus(okStatus({ failing: 1 }));+ writeFileSync(join(work, 'note.md'), 'recovered\n');+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });+ expect(r.ok).toBe(true);+ expect(loadBackupStatus()).toBeNull();+ }, T);++ test('a blocked push (tracked deny match) does NOT invalidate', async () => {+ // NOTE: push_failed (unreachable origin) is untestable in this sandbox —+ // a /conductor/bin/git shim swallows subprocess exit codes — so the+ // failing-path pins use verdicts computed from git STDOUT (deny listing,+ // privacy ladder), which the shim passes through faithfully.+ writeFileSync(join(work, '.env'), 'SECRETISH=value\n');+ git(work, 'add', '.env');+ git(work, 'commit', '-qm', 'oops tracked env');+ seedWarnCache();+ const before = loadBackupStatus();+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });+ expect(r.ok).toBe(false);+ expect(r.status).toBe('blocked_tracked_deny');+ expect(loadBackupStatus()).toEqual(before); // cache untouched+ }, T);++ test('a refused-visibility push does NOT invalidate (r.ok=false through finish)', async () => {+ seedWarnCache();+ writeFileSync(join(work, 'note.md'), 'n\n');+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: false });+ expect(r.ok).toBe(false);+ expect(r.status).toBe('refused_visibility');+ expect(r.committed).toBe(true); // the local commit happened…+ expect(loadBackupStatus()).not.toBeNull(); // …but the cache stays+ }, T);++ test('a clean lock-skip never touches the cache (skip returns before finish)', async () => {+ seedWarnCache();+ const lock = acquirePushLock(work);+ expect(lock.acquired).toBe(true);+ try {+ writeFileSync(join(work, 'note.md'), 'racing\n');+ const r = await workspacePush({ dir: work, branch: 'main', allowUnverifiedRemote: true });+ // skipped_in_flight is ok:true (clean skip) but must NOT invalidate —+ // only the lock WINNER's eventual success changes the coverage answer.+ expect(r.ok).toBe(true);+ expect(r.status).toBe('skipped_in_flight');+ expect(loadBackupStatus()).not.toBeNull();+ } finally {+ if (lock.acquired) lock.handle.release();+ }+ }, T);+});++describe('sources harden — invalidation after the harden loop', () => {+ const rowEngine = (local_path: string): BrainEngine =>+ ({ executeRaw: async () => [{ id: 'wiki', local_path, config: null }] } as unknown as BrainEngine);++ test('a run that produced a report drops the cached verdict (dry-run, real repo)', async () => {+ seedWarnCache();+ // --dry-run --no-cron --no-verify keeps hardenBrainRepo fully offline and+ // write-free while still producing a DurabilityReport, which is exactly+ // the condition the invalidation call keys on (reports.length > 0).+ await muted(() => runHarden(rowEngine(work), ['wiki', '--dry-run', '--no-cron', '--no-verify', '--json']));+ expect(loadBackupStatus()).toBeNull();+ }, T);++ test('a run whose rows were ALL skipped (no git repo) leaves the cache alone', async () => {+ seedWarnCache();+ const plain = mkdtempSync(join(root, 'plain-')); // not a git repo → skipped+ await muted(() => runHarden(rowEngine(plain), ['wiki', '--dry-run', '--no-cron', '--no-verify', '--json']));+ expect(loadBackupStatus()).not.toBeNull(); // zero reports → no invalidation+ }, T);+});++describe('bootstrap repo — recordRepoInReceipt contract (source-text pin)', () => {+ // WHY source-text and not behavior: recordRepoInReceipt is module-private+ // to src/core/bootstrap/repo.ts, and the only public path to it is the full+ // `gbrain bootstrap repo` flow — which requires a gh binary, a GitHub-shaped+ // origin, and a repo-privacy verification ladder that cannot run in this+ // sandbox (the git shim also swallows subprocess exit codes). The REAL+ // behavior (invalidateBackupStatus deleting the cache file) is pinned above+ // via the workspace-push and harden paths, which share the same helper; this+ // test pins WHERE bootstrap-repo calls it.+ const repoSrc = () =>+ readFileSync(join(import.meta.dir, '..', 'src', 'core', 'bootstrap', 'repo.ts'), 'utf-8');++ function fnBody(src: string, name: string): string {+ const start = src.indexOf(`function ${name}(`);+ expect(start).toBeGreaterThan(-1);+ const end = src.indexOf('\n}', start); // module-level fn: first col-0 close+ expect(end).toBeGreaterThan(start);+ return src.slice(start, end);+ }++ test('recordRepoInReceipt (post-push success) calls invalidateBackupStatus()', () => {+ expect(fnBody(repoSrc(), 'recordRepoInReceipt')).toContain('invalidateBackupStatus()');+ });++ test('recordPendingRepo (pre-push proof-of-intent) does NOT invalidate — nothing was fixed yet', () => {+ expect(fnBody(repoSrc(), 'recordPendingRepo')).not.toContain('invalidateBackupStatus');+ });+});diff --git a/test/backup-status-file.serial.test.ts b/test/backup-status-file.serial.test.tsnew file mode 100644index 0000000000..01ed2501c5--- /dev/null+++ b/test/backup-status-file.serial.test.ts@@ -0,0 +1,705 @@+/**+ * test/backup-status-file.test.ts — engine-free coverage for+ * src/core/backup/status-file.ts: cached-verdict I/O, staleness, interval /+ * kill-switch config resolution, notice rendering (privacy pins), the+ * pseudo-version fingerprint, the bounded nag gate lifecycle (per-channel+ * ceiling, 24h dampener, global monthly cap), the read-only consult, the+ * spawn debounce, and the CLI startup-rail helper.+ *+ * Uses the module's __set...ForTests seams pointed at files under a mkdtemp+ * dir; never touches the real ~/.gbrain. No engine.+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import {+ BACKUP_BANNER_MAX_CHARS,+ BACKUP_DAMPENER_MS,+ BACKUP_GLOBAL_CEILING,+ BACKUP_INTERVAL_DAYS_DEFAULT,+ BACKUP_NAG_SCHEMA_VERSION,+ BACKUP_STATUS_SCHEMA_VERSION,+ BACKUP_CLI_NAG_SKIP,+ backupCheckDisabled,+ backupIntervalMs,+ backupNagGate,+ backupNagReadOnlyConsult,+ backupNagStatePath,+ backupNoticeText,+ backupSpawnDue,+ backupStatusPath,+ backupVerdictVersion,+ invalidateBackupStatus,+ isBackupStatusStale,+ loadBackupNagState,+ loadBackupStatus,+ maybeEmitBackupNag,+ recordBackupSpawn,+ saveBackupNagState,+ saveBackupStatus,+ __setBackupIntervalForTests,+ __setBackupNagStatePathForTests,+ __setBackupStatusPathForTests,+ type BackupAssetVerdict,+ type BackupStatus,+} from '../src/core/backup/status-file.ts';++const HOUR = 60 * 60 * 1000;+const DAY = 24 * HOUR;++const ENV_KEYS = [+ 'GBRAIN_HOME',+ 'GBRAIN_BACKUP_CHECK',+ 'GBRAIN_BACKUP_CHECK_DAYS',+ 'GBRAIN_SKIP_STARTUP_HOOKS',+ 'GBRAIN_FORCE_BACKUP_NAG',+ 'NODE_ENV',+] as const;++let tmp: string;+let statusPath: string;+let nagPath: string;+let saved: Record<string, string | undefined>;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-backup-status-'));+ saved = {};+ for (const k of ENV_KEYS) saved[k] = process.env[k];+ // Clear the backup knobs; leave NODE_ENV as-is (bun test sets it).+ delete process.env.GBRAIN_BACKUP_CHECK;+ delete process.env.GBRAIN_BACKUP_CHECK_DAYS;+ delete process.env.GBRAIN_SKIP_STARTUP_HOOKS;+ delete process.env.GBRAIN_FORCE_BACKUP_NAG;+ process.env.GBRAIN_HOME = tmp; // config reads resolve to <tmp>/.gbrain/config.json+ statusPath = join(tmp, 'backup-status.json');+ nagPath = join(tmp, 'backup-nag-state.json');+ __setBackupStatusPathForTests(statusPath);+ __setBackupNagStatePathForTests(nagPath);+ __setBackupIntervalForTests(null);+});++afterEach(() => {+ __setBackupStatusPathForTests(null);+ __setBackupNagStatePathForTests(null);+ __setBackupIntervalForTests(null);+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++function writeConfig(cfg: Record<string, unknown>): void {+ const dir = join(tmp, '.gbrain');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'config.json'), JSON.stringify({ engine: 'pglite', ...cfg }));+}++/** Warn-by-default fixture: 2 of 3 assets have no remote. Ids deliberately+ * include a local path and a client name for the privacy pins. */+function makeStatus(overrides: Partial<BackupStatus> = {}): BackupStatus {+ const assets: BackupAssetVerdict[] =+ overrides.assets ??+ ([+ { kind: 'source_repo', id: '/tmp/secret-repo', state: 'no_remote', fix_argv: null },+ { kind: 'source_repo', id: 'client-acme', state: 'no_remote', fix_argv: null },+ { kind: 'source_repo', id: 'public-notes', state: 'ok' },+ ] as BackupAssetVerdict[]);+ const no_remote = assets.filter((a) => a.state === 'no_remote').length;+ const base: BackupStatus = {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: '2026-01-05T12:00:00.000Z',+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall: no_remote > 0 ? 'warn' : 'ok',+ totals: {+ assets: assets.length,+ no_remote,+ unpushed: 0,+ failing: 0,+ recoverable_repos: assets.length - no_remote,+ pages_at_risk: 0,+ },+ assets,+ };+ return { ...base, ...overrides };+}++function okStatus(): BackupStatus {+ return makeStatus({+ assets: [{ kind: 'source_repo', id: 'public-notes', state: 'ok' }] as BackupAssetVerdict[],+ });+}++function collect(): { write: (line: string) => void; lines: string[] } {+ const lines: string[] = [];+ return { write: (line: string) => lines.push(line), lines };+}++// ── 1. Cached verdict I/O ────────────────────────────────────────────────────++describe('loadBackupStatus / saveBackupStatus', () => {+ test('seams route the machine files under the tmp dir', () => {+ expect(backupStatusPath()).toBe(statusPath);+ expect(backupNagStatePath()).toBe(nagPath);+ });++ test('save/load round-trip', () => {+ const s = makeStatus();+ saveBackupStatus(s);+ expect(existsSync(statusPath)).toBe(true);+ expect(loadBackupStatus()).toEqual(s);+ });++ test('missing file -> null', () => {+ expect(existsSync(statusPath)).toBe(false);+ expect(loadBackupStatus()).toBeNull();+ });++ test('corrupt JSON -> null (fail-open)', () => {+ writeFileSync(statusPath, '{ definitely not json');+ expect(loadBackupStatus()).toBeNull();+ });++ test('unknown schema_version -> null', () => {+ const s = makeStatus();+ writeFileSync(statusPath, JSON.stringify({ ...s, schema_version: 'gbrain-backup-status-v999' }));+ expect(loadBackupStatus()).toBeNull();+ });++ test('structurally invalid payloads -> null (checked_at / assets / overall)', () => {+ const s = makeStatus();+ writeFileSync(statusPath, JSON.stringify({ ...s, checked_at: 42 }));+ expect(loadBackupStatus()).toBeNull();+ writeFileSync(statusPath, JSON.stringify({ ...s, assets: 'nope' }));+ expect(loadBackupStatus()).toBeNull();+ writeFileSync(statusPath, JSON.stringify({ ...s, overall: 'panic' }));+ expect(loadBackupStatus()).toBeNull();+ });++ test('missing or malformed totals block -> null (renderers dereference totals un-guarded)', () => {+ const s = makeStatus();+ // Schema-valid JSON with the totals block REMOVED must read as absent,+ // not crash `gbrain backup status`.+ const { totals: _dropped, ...withoutTotals } = s;+ writeFileSync(statusPath, JSON.stringify(withoutTotals));+ expect(loadBackupStatus()).toBeNull();+ // Truncated-but-schema-valid totals (non-numeric / null) are rejected too.+ writeFileSync(statusPath, JSON.stringify({ ...s, totals: null }));+ expect(loadBackupStatus()).toBeNull();+ writeFileSync(statusPath, JSON.stringify({ ...s, totals: { assets: 'three' } }));+ expect(loadBackupStatus()).toBeNull();+ writeFileSync(statusPath, JSON.stringify({ ...s, totals: { ...s.totals, no_remote: 'two' } }));+ expect(loadBackupStatus()).toBeNull();+ // The intact fixture still loads (the guard rejects only malformed shapes).+ writeFileSync(statusPath, JSON.stringify(s));+ expect(loadBackupStatus()).toEqual(s);+ });+});++// ── 2. invalidateBackupStatus ────────────────────────────────────────────────++describe('invalidateBackupStatus', () => {+ test('removes the cache file', () => {+ saveBackupStatus(makeStatus());+ expect(existsSync(statusPath)).toBe(true);+ invalidateBackupStatus();+ expect(existsSync(statusPath)).toBe(false);+ expect(loadBackupStatus()).toBeNull();+ });++ test('no-op when the file is absent', () => {+ expect(existsSync(statusPath)).toBe(false);+ expect(() => invalidateBackupStatus()).not.toThrow();+ expect(existsSync(statusPath)).toBe(false);+ });+});++// ── 3. isBackupStatusStale ───────────────────────────────────────────────────++describe('isBackupStatusStale', () => {+ const now = Date.parse('2026-06-15T00:00:00.000Z');++ test('null -> true (cold start computes)', () => {+ expect(isBackupStatusStale(null, now)).toBe(true);+ });++ test('fresh -> false (injected now)', () => {+ const s = makeStatus({ checked_at: new Date(now - HOUR).toISOString() });+ expect(isBackupStatusStale(s, now)).toBe(false);+ });++ test('older than the default 30d interval -> true', () => {+ const s = makeStatus({ checked_at: new Date(now - 31 * DAY).toISOString() });+ expect(isBackupStatusStale(s, now)).toBe(true);+ const edge = makeStatus({ checked_at: new Date(now - 29 * DAY).toISOString() });+ expect(isBackupStatusStale(edge, now)).toBe(false);+ });++ test('interval seam is honored', () => {+ __setBackupIntervalForTests(1000);+ expect(isBackupStatusStale(makeStatus({ checked_at: new Date(now - 2000).toISOString() }), now)).toBe(true);+ expect(isBackupStatusStale(makeStatus({ checked_at: new Date(now - 500).toISOString() }), now)).toBe(false);+ });++ test('checked_at >24h in the FUTURE -> true (clock skew); <=24h future is tolerated', () => {+ expect(isBackupStatusStale(makeStatus({ checked_at: new Date(now + 25 * HOUR).toISOString() }), now)).toBe(true);+ expect(isBackupStatusStale(makeStatus({ checked_at: new Date(now + HOUR).toISOString() }), now)).toBe(false);+ });++ test('unparseable checked_at -> true', () => {+ expect(isBackupStatusStale(makeStatus({ checked_at: 'not-a-date' }), now)).toBe(true);+ });+});++// ── 4. backupIntervalMs ──────────────────────────────────────────────────────++describe('backupIntervalMs', () => {+ test('default is 30 days', () => {+ expect(BACKUP_INTERVAL_DAYS_DEFAULT).toBe(30);+ expect(backupIntervalMs()).toBe(30 * DAY);+ });++ test('env GBRAIN_BACKUP_CHECK_DAYS=7 -> 7 days', () => {+ process.env.GBRAIN_BACKUP_CHECK_DAYS = '7';+ expect(backupIntervalMs()).toBe(7 * DAY);+ });++ test('DAYS=0 is clamped to the default (invalid, NOT always-stale)', () => {+ process.env.GBRAIN_BACKUP_CHECK_DAYS = '0';+ expect(backupIntervalMs()).toBe(30 * DAY);+ // A fresh cache stays fresh under DAYS=0 — the clamp prevents always-stale.+ const now = Date.parse('2026-06-15T00:00:00.000Z');+ const fresh = makeStatus({ checked_at: new Date(now - HOUR).toISOString() });+ expect(isBackupStatusStale(fresh, now)).toBe(false);+ });++ test('config backup.check_interval_days honored; env wins over config', () => {+ writeConfig({ backup: { check_interval_days: 2 } });+ expect(backupIntervalMs()).toBe(2 * DAY);+ process.env.GBRAIN_BACKUP_CHECK_DAYS = '7';+ expect(backupIntervalMs()).toBe(7 * DAY);+ });+});++// ── 5. backupCheckDisabled ───────────────────────────────────────────────────++describe('backupCheckDisabled', () => {+ test('default false (on — the whole point is unopted users)', () => {+ expect(backupCheckDisabled()).toBe(false);+ });++ test('env GBRAIN_BACKUP_CHECK=0 -> true', () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ expect(backupCheckDisabled()).toBe(true);+ });++ test("env GBRAIN_BACKUP_CHECK 'false' / 'off' (case-insensitive, trimmed) -> true", () => {+ for (const v of ['false', 'off', 'FALSE', 'Off', ' false ']) {+ process.env.GBRAIN_BACKUP_CHECK = v;+ expect(backupCheckDisabled()).toBe(true);+ }+ });++ test("env GBRAIN_BACKUP_CHECK '1' / 'true' / '' do NOT disable", () => {+ for (const v of ['1', 'true', 'on', '']) {+ process.env.GBRAIN_BACKUP_CHECK = v;+ expect(backupCheckDisabled()).toBe(false);+ }+ });++ test("config backup.check_enabled false/'false'/'off'/'0' -> true", () => {+ for (const v of [false, 'false', 'off', '0'] as const) {+ writeConfig({ backup: { check_enabled: v } });+ expect(backupCheckDisabled()).toBe(true);+ }+ });++ test("config backup.check_enabled true/'true' -> false", () => {+ for (const v of [true, 'true'] as const) {+ writeConfig({ backup: { check_enabled: v } });+ expect(backupCheckDisabled()).toBe(false);+ }+ });+});++// ── 6. backupNoticeText ──────────────────────────────────────────────────────++describe('backupNoticeText', () => {+ test('ok verdict -> null on both surfaces', () => {+ expect(backupNoticeText(okStatus(), 'human')).toBeNull();+ expect(backupNoticeText(okStatus(), 'aggregate')).toBeNull();+ });++ test('human form names up to two assets and stays <= 300 chars', () => {+ const text = backupNoticeText(makeStatus(), 'human');+ expect(text).not.toBeNull();+ expect(text!).toContain('/tmp/secret-repo');+ expect(text!).toContain('client-acme');+ expect(text!).toContain('2 of your 3');+ expect(text!.length).toBeLessThanOrEqual(BACKUP_BANNER_MAX_CHARS);+ });++ test('human form is truncated to the banner budget even with long asset ids', () => {+ const long = makeStatus({+ assets: [+ { kind: 'source_repo', id: `/very/deep/${'x'.repeat(200)}`, state: 'no_remote', fix_argv: null },+ { kind: 'source_repo', id: `/another/${'y'.repeat(200)}`, state: 'no_remote', fix_argv: null },+ ] as BackupAssetVerdict[],+ });+ const text = backupNoticeText(long, 'human');+ expect(text).not.toBeNull();+ expect(text!.length).toBeLessThanOrEqual(BACKUP_BANNER_MAX_CHARS);+ expect(text!.endsWith('…')).toBe(true);+ });++ test('aggregate form carries counts only — never an asset id or path fragment (privacy pin)', () => {+ const text = backupNoticeText(makeStatus(), 'aggregate');+ expect(text).not.toBeNull();+ expect(text!).toContain('2 of 3');+ expect(text!).not.toContain('secret-repo');+ expect(text!).not.toContain('client-acme');+ expect(text!).not.toContain('/tmp');+ // No path fragments from the fixture ids at all.+ expect(text!).not.toContain('/tmp/secret-repo');+ });+});++// ── 7. backupVerdictVersion ──────────────────────────────────────────────────++describe('backupVerdictVersion', () => {+ test('same month + same no-remote set -> equal (day within month is irrelevant)', () => {+ const a = makeStatus({ checked_at: '2026-01-05T12:00:00.000Z' });+ const b = makeStatus({ checked_at: '2026-01-28T09:30:00.000Z' });+ expect(backupVerdictVersion(a)).toBe(backupVerdictVersion(b));+ });++ test('different month -> different', () => {+ const a = makeStatus({ checked_at: '2026-01-05T12:00:00.000Z' });+ const b = makeStatus({ checked_at: '2026-02-05T12:00:00.000Z' });+ expect(backupVerdictVersion(a)).not.toBe(backupVerdictVersion(b));+ });++ test('different no-remote set -> different', () => {+ const a = makeStatus();+ const b = makeStatus({+ assets: [+ { kind: 'source_repo', id: '/tmp/secret-repo', state: 'no_remote', fix_argv: null },+ { kind: 'source_repo', id: 'client-other', state: 'no_remote', fix_argv: null },+ { kind: 'source_repo', id: 'public-notes', state: 'ok' },+ ] as BackupAssetVerdict[],+ });+ expect(backupVerdictVersion(a)).not.toBe(backupVerdictVersion(b));+ });+});++// ── 8. backupNagGate lifecycle ───────────────────────────────────────────────++describe('backupNagGate', () => {+ test('ok verdict -> hidden; disabled -> hidden even on warn', () => {+ expect(backupNagGate('cli', okStatus(), Date.parse('2026-03-01T00:00:00Z')).show).toBe(false);+ process.env.GBRAIN_BACKUP_CHECK = '0';+ expect(backupNagGate('cli', makeStatus(), Date.parse('2026-03-01T00:00:00Z')).show).toBe(false);+ });++ test('first show -> record -> immediate re-gate hidden by the 24h dampener', () => {+ const s = makeStatus();+ const t0 = Date.parse('2026-03-01T00:00:00.000Z');+ const g1 = backupNagGate('hook-banner', s, t0);+ expect(g1.show).toBe(true);+ g1.record();+ expect(backupNagGate('hook-banner', s, t0 + 1000).show).toBe(false);+ expect(backupNagGate('hook-banner', s, t0 + BACKUP_DAMPENER_MS - 1000).show).toBe(false);+ });++ test('per-channel ceiling of 3 per pseudo-version; a different channel is independent of it but bound by the dampener', () => {+ const s = makeStatus({ checked_at: '2026-01-05T12:00:00.000Z' });+ // Spread the three recorded impressions across months so the GLOBAL cap+ // never saturates — this isolates the per-channel ceiling.+ const t1 = Date.parse('2026-01-05T12:00:00.000Z');+ const t2 = Date.parse('2026-02-06T12:00:00.000Z');+ const t3 = Date.parse('2026-03-07T12:00:00.000Z');+ for (const t of [t1, t2, t3]) {+ const g = backupNagGate('cli', s, t);+ expect(g.show).toBe(true);+ g.record();+ }+ const state = loadBackupNagState();+ expect(state.entries).toHaveLength(1);+ expect(state.entries[0]!.declined_count).toBe(3);+ expect(state.entries[0]!.suppressed).toBe(true);+ expect(state.global_shown_count).toBe(1); // March bucket only holds one++ // Ceiling hit: hidden even after the dampener ages out (+48h).+ const t4 = Date.parse('2026-03-09T12:00:00.000Z');+ expect(backupNagGate('cli', s, t4).show).toBe(false);++ // A DIFFERENT channel: not bound by cli's per-channel ceiling...+ expect(backupNagGate('status', s, t4).show).toBe(true);+ // ...but IS blocked by the shared 24h dampener right after a record.+ expect(backupNagGate('status', s, t3 + HOUR).show).toBe(false);+ });++ test('same-month forced recompute (new checked_at, same verdict) stays suppressed; month rollover re-surfaces with reset count', () => {+ const s = makeStatus({ checked_at: '2026-01-05T12:00:00.000Z' });+ const t1 = Date.parse('2026-01-05T12:00:00.000Z');+ const t2 = Date.parse('2026-02-06T12:00:00.000Z');+ const t3 = Date.parse('2026-03-07T12:00:00.000Z');+ for (const t of [t1, t2, t3]) {+ const g = backupNagGate('cli', s, t);+ expect(g.show).toBe(true);+ g.record();+ }+ const t4 = Date.parse('2026-03-09T12:00:00.000Z'); // dampener aged, global under cap+ expect(backupNagGate('cli', s, t4).show).toBe(false); // at ceiling++ // Same checked_at month, different day, same no-remote set -> same+ // pseudo-version -> STAYS suppressed.+ const sSameMonth = makeStatus({ checked_at: '2026-01-28T03:00:00.000Z' });+ expect(backupVerdictVersion(sSameMonth)).toBe(backupVerdictVersion(s));+ expect(backupNagGate('cli', sSameMonth, t4).show).toBe(false);++ // New checked_at month -> new pack_version -> re-surfaces, count resets.+ const sApril = makeStatus({ checked_at: '2026-04-01T00:00:00.000Z' });+ const t5 = Date.parse('2026-04-10T12:00:00.000Z');+ const g = backupNagGate('cli', sApril, t5);+ expect(g.show).toBe(true);+ g.record();+ const entry = loadBackupNagState().entries.find((e) => e.pack_name === 'cli');+ expect(entry!.declined_count).toBe(1); // reset, not 4+ expect(entry!.suppressed).toBe(false);+ // Still under ceiling: shows again once the dampener ages out.+ expect(backupNagGate('cli', sApril, t5 + 26 * HOUR).show).toBe(true);+ });++ test('global cap: 3 recorded impressions in one month across channels hides EVERY channel; next month re-arms', () => {+ const s = makeStatus({ checked_at: '2026-03-01T00:00:00.000Z' });+ const base = Date.parse('2026-03-01T00:00:00.000Z');+ const channels = ['a', 'b', 'c'];+ channels.forEach((ch, i) => {+ const g = backupNagGate(ch, s, base + i * 25 * HOUR);+ expect(g.show).toBe(true);+ g.record();+ });+ expect(loadBackupNagState().global_shown_count).toBe(BACKUP_GLOBAL_CEILING);++ const later = base + 3 * 25 * HOUR; // dampener aged; still March+ expect(backupNagGate('d', s, later).show).toBe(false); // fresh channel: global cap+ expect(backupNagGate('a', s, later).show).toBe(false); // under-ceiling channel: global cap+ expect(backupNagGate('d', s, later + 25 * HOUR).show).toBe(false); // stays hidden in-month++ // Next month: global count re-arms (dampener long aged).+ const april = Date.parse('2026-04-02T00:00:00.000Z');+ expect(backupNagGate('d', s, april).show).toBe(true);+ });++ test('record() is deferred — show without record leaves no state, so the next gate still shows', () => {+ const s = makeStatus();+ const t0 = Date.parse('2026-03-01T00:00:00.000Z');+ const g1 = backupNagGate('cli', s, t0);+ expect(g1.show).toBe(true);+ // record NOT called: nothing persisted, nothing counted.+ expect(existsSync(nagPath)).toBe(false);+ expect(backupNagGate('cli', s, t0 + 60_000).show).toBe(true); // even inside the would-be dampener window+ expect(backupNagGate('cli', s, t0 + BACKUP_DAMPENER_MS + HOUR).show).toBe(true);+ });+});++// ── 9. backupNagReadOnlyConsult ──────────────────────────────────────────────++describe('backupNagReadOnlyConsult', () => {+ const now = Date.parse('2026-03-10T00:00:00.000Z');++ test('warn + no state -> true, and never creates the state file', () => {+ expect(existsSync(nagPath)).toBe(false);+ expect(backupNagReadOnlyConsult(makeStatus(), now)).toBe(true);+ expect(existsSync(nagPath)).toBe(false);+ });++ test('ok verdict / disabled -> false', () => {+ expect(backupNagReadOnlyConsult(okStatus(), now)).toBe(false);+ process.env.GBRAIN_BACKUP_CHECK = '0';+ expect(backupNagReadOnlyConsult(makeStatus(), now)).toBe(false);+ });++ test('within 24h of last_shown_at -> false; never writes the state file', () => {+ saveBackupNagState({+ schema_version: BACKUP_NAG_SCHEMA_VERSION,+ entries: [],+ last_shown_at: new Date(now - HOUR).toISOString(),+ });+ const before = readFileSync(nagPath, 'utf-8');+ expect(backupNagReadOnlyConsult(makeStatus(), now)).toBe(false);+ expect(readFileSync(nagPath, 'utf-8')).toBe(before);+ });++ test('global count at ceiling for the current month -> false; under cap next month -> true; never writes', () => {+ saveBackupNagState({+ schema_version: BACKUP_NAG_SCHEMA_VERSION,+ entries: [],+ last_shown_at: new Date(now - 48 * HOUR).toISOString(),+ global_month: '2026-03',+ global_shown_count: BACKUP_GLOBAL_CEILING,+ });+ const before = readFileSync(nagPath, 'utf-8');+ expect(backupNagReadOnlyConsult(makeStatus(), now)).toBe(false);+ // Month rollover: the March count no longer binds.+ expect(backupNagReadOnlyConsult(makeStatus(), Date.parse('2026-04-05T00:00:00.000Z'))).toBe(true);+ expect(readFileSync(nagPath, 'utf-8')).toBe(before);+ });+});++// ── 10. backupSpawnDue / recordBackupSpawn ───────────────────────────────────++describe('backupSpawnDue / recordBackupSpawn', () => {+ test('due when never recorded; not due within 24h; due after (injected now)', () => {+ const t0 = Date.parse('2026-05-01T00:00:00.000Z');+ expect(backupSpawnDue(t0)).toBe(true);+ recordBackupSpawn(t0);+ expect(backupSpawnDue(t0 + HOUR)).toBe(false);+ expect(backupSpawnDue(t0 + 23 * HOUR)).toBe(false);+ expect(backupSpawnDue(t0 + 25 * HOUR)).toBe(true);+ });++ test('recordBackupSpawn preserves the rest of the nag state', () => {+ const t0 = Date.parse('2026-05-01T00:00:00.000Z');+ const g = backupNagGate('cli', makeStatus(), t0);+ g.record();+ recordBackupSpawn(t0 + 1000);+ const state = loadBackupNagState();+ expect(state.entries).toHaveLength(1);+ expect(state.last_spawn_at).toBe(new Date(t0 + 1000).toISOString());+ expect(state.last_shown_at).toBe(new Date(t0).toISOString());+ });+});++// ── 11. maybeEmitBackupNag (CLI startup rail) ────────────────────────────────++describe('maybeEmitBackupNag', () => {+ test('warn cache + non-skip command emits the machine marker + human line and records', () => {+ process.env.GBRAIN_FORCE_BACKUP_NAG = '1';+ saveBackupStatus(makeStatus());+ const c = collect();+ maybeEmitBackupNag('search', {}, c.write);+ // stderr is not a TTY under redirected test runs -> machine marker first.+ expect(c.lines.some((l) => l === 'BACKUP_LOCAL_ONLY 2\n')).toBe(true);+ const human = c.lines.find((l) => l.startsWith('gbrain backup check: '));+ expect(human).toBeDefined();+ expect(human!).toContain("aren't on any git remote");+ // Recorded: nag state exists and counted one impression.+ const state = loadBackupNagState();+ expect(state.global_shown_count).toBe(1);+ expect(state.entries.find((e) => e.pack_name === 'cli')).toBeDefined();+ // Immediate second invocation is dampened -> silent.+ const c2 = collect();+ maybeEmitBackupNag('search', {}, c2.write);+ expect(c2.lines).toEqual([]);+ });++ test('skip-set commands emit nothing and record nothing', () => {+ process.env.GBRAIN_FORCE_BACKUP_NAG = '1';+ saveBackupStatus(makeStatus());+ for (const cmd of ['serve', 'backup', 'doctor', 'advisor', 'call', 'jobs', 'hook', 'upgrade']) {+ expect(BACKUP_CLI_NAG_SKIP.has(cmd)).toBe(true);+ const c = collect();+ maybeEmitBackupNag(cmd, {}, c.write);+ expect(c.lines).toEqual([]);+ }+ // Undefined command is skipped too.+ const c = collect();+ maybeEmitBackupNag(undefined, {}, c.write);+ expect(c.lines).toEqual([]);+ expect(existsSync(nagPath)).toBe(false);+ });++ test('quiet opt emits nothing', () => {+ process.env.GBRAIN_FORCE_BACKUP_NAG = '1';+ saveBackupStatus(makeStatus());+ const c = collect();+ maybeEmitBackupNag('search', { quiet: true }, c.write);+ expect(c.lines).toEqual([]);+ expect(existsSync(nagPath)).toBe(false);+ });++ test('GBRAIN_SKIP_STARTUP_HOOKS set -> nothing', () => {+ process.env.GBRAIN_FORCE_BACKUP_NAG = '1';+ process.env.GBRAIN_SKIP_STARTUP_HOOKS = '1';+ saveBackupStatus(makeStatus());+ const c = collect();+ maybeEmitBackupNag('search', {}, c.write);+ expect(c.lines).toEqual([]);+ });++ test('disabled -> nothing (stale warn cache goes silent)', () => {+ process.env.GBRAIN_FORCE_BACKUP_NAG = '1';+ process.env.GBRAIN_BACKUP_CHECK = '0';+ saveBackupStatus(makeStatus());+ const c = collect();+ maybeEmitBackupNag('search', {}, c.write);+ expect(c.lines).toEqual([]);+ });++ test('ok cache -> nothing; missing cache -> nothing', () => {+ process.env.GBRAIN_FORCE_BACKUP_NAG = '1';+ saveBackupStatus(okStatus());+ const c = collect();+ maybeEmitBackupNag('search', {}, c.write);+ expect(c.lines).toEqual([]);+ invalidateBackupStatus();+ const c2 = collect();+ maybeEmitBackupNag('search', {}, c2.write);+ expect(c2.lines).toEqual([]);+ });++ test("NODE_ENV=test without GBRAIN_FORCE_BACKUP_NAG -> early return (test-suite guard)", () => {+ process.env.NODE_ENV = 'test';+ delete process.env.GBRAIN_FORCE_BACKUP_NAG;+ saveBackupStatus(makeStatus());+ const c = collect();+ maybeEmitBackupNag('search', {}, c.write);+ expect(c.lines).toEqual([]);+ });+});++// ── 12. Fail-open corruption + atomic-write hygiene ──────────────────────────++describe('fail-open + atomicity', () => {+ test('corrupt nag-state file -> gate fail-open (still decides; record repairs the file)', () => {+ writeFileSync(nagPath, '{ this is not json');+ const s = makeStatus();+ const t0 = Date.parse('2026-03-01T00:00:00.000Z');+ const g = backupNagGate('cli', s, t0);+ expect(g.show).toBe(true); // worst case: one extra display, never a crash+ g.record();+ const state = loadBackupNagState();+ expect(state.schema_version).toBe(BACKUP_NAG_SCHEMA_VERSION);+ expect(state.entries).toHaveLength(1);+ expect(state.global_shown_count).toBe(1);+ });++ test('unknown nag-state schema -> empty state (fail-open load)', () => {+ writeFileSync(nagPath, JSON.stringify({ schema_version: 'gbrain-backup-nag-v999', entries: [{}] }));+ const state = loadBackupNagState();+ expect(state.entries).toEqual([]);+ });++ test('kill-mid-write: a partial .tmp sibling next to the status path is ignored', () => {+ const s = makeStatus();+ saveBackupStatus(s);+ // Simulate a writer killed between writeFileSync(tmp) and renameSync.+ writeFileSync(`${statusPath}.tmp-99999`, '{"schema_version":"gbrain-ba'); // truncated JSON+ expect(loadBackupStatus()).toEqual(s); // real file wins; tmp never consulted+ // And with ONLY the orphaned partial present, load sees a missing file.+ rmSync(statusPath);+ expect(loadBackupStatus()).toBeNull();+ });++ test('saveBackupStatus leaves no .tmp droppings on the happy path', () => {+ saveBackupStatus(makeStatus());+ expect(existsSync(`${statusPath}.tmp-${process.pid}`)).toBe(false);+ expect(existsSync(statusPath)).toBe(true);+ });+});diff --git a/test/config-file-plane-keys.test.ts b/test/config-file-plane-keys.test.tsindex f36108b59a..fe8e8150a7 100644--- a/test/config-file-plane-keys.test.ts+++ b/test/config-file-plane-keys.test.ts@@ -7,12 +7,18 @@* the loud warning) and the read half (configAllowsUnverifiedRemote).*/import { describe, test, expect } from 'bun:test';-import { mkdtempSync, readFileSync } from 'node:fs';+import { existsSync, mkdtempSync, readFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { runConfig } from '../src/commands/config.ts';import { configAllowsUnverifiedRemote } from '../src/core/workspace-push.ts';+import {+ BACKUP_INTERVAL_DAYS_DEFAULT,+ backupCheckDisabled,+ backupIntervalMs,+ __setBackupIntervalForTests,+} from '../src/core/backup/status-file.ts';import type { BrainEngine } from '../src/core/engine.ts';import { withEnv } from './helpers/with-env.ts';@@ -70,6 +76,104 @@ describe('config set — file-plane bootstrap hook-lane keys [D18]', () => {});});+/**+ * backup.* keys are FILE-plane canonical for the same reason as the hook-lane+ * keys: their readers (backupCheckDisabled / backupIntervalMs in+ * src/core/backup/status-file.ts) are engine-free — `gbrain hook`, the cli.ts+ * startup rail, and the MCP dispatch notice all resolve through+ * loadConfigFileOnly, which never sees the DB plane. These tests pin the write+ * half (runConfig routes the nested keys to ~/.gbrain/config.json) AND the+ * read half (the status-file resolvers flip on the same file).+ */+describe('config set — backup.* file-plane keys', () => {+ const DAY = 24 * 60 * 60 * 1000;++ /** Validation-error idiom: console.error + process.exit(1) → capture the+ * error stream and turn exit into a recoverable sentinel throw. */+ async function captureErrExit(fn: () => Promise<void>): Promise<{ err: string; exitCode: number | undefined }> {+ const origErr = console.error;+ const origExit = process.exit;+ let err = '';+ let exitCode: number | undefined;+ console.error = (...a: unknown[]) => { err += a.map(String).join(' ') + '\n'; };+ (process as { exit: unknown }).exit = ((code?: number) => {+ exitCode = code ?? 0;+ throw new Error('__exit__');+ }) as unknown as typeof process.exit;+ try {+ await fn();+ } catch (e) {+ if (!(e instanceof Error) || e.message !== '__exit__') throw e;+ } finally {+ console.error = origErr;+ process.exit = origExit;+ }+ return { err, exitCode };+ }++ test('backup.check_enabled: false lands NESTED on the file plane and flips backupCheckDisabled(); true flips it back; unset restores the default', async () => {+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-backup-'));+ // Clear the env kill switch — backupCheckDisabled consults it first.+ await withEnv({ GBRAIN_HOME: parent, GBRAIN_BACKUP_CHECK: undefined }, async () => {+ const out = await captureLog(() => runConfig(noEngine, ['set', 'backup.check_enabled', 'false']));+ expect(out).toContain('Set backup.check_enabled = false');+ expect(out).toContain('file plane');+ const cfgPath = join(parent, '.gbrain', 'config.json');+ let cfg = JSON.parse(readFileSync(cfgPath, 'utf8')) as { backup?: { check_enabled?: boolean } };+ expect(cfg.backup?.check_enabled).toBe(false); // nested, not a flat dotted key+ // The engine-free read half sees the same file.+ expect(backupCheckDisabled()).toBe(true);++ // set true → re-enabled.+ await captureLog(() => runConfig(noEngine, ['set', 'backup.check_enabled', 'true']));+ cfg = JSON.parse(readFileSync(cfgPath, 'utf8')) as { backup?: { check_enabled?: boolean } };+ expect(cfg.backup?.check_enabled).toBe(true);+ expect(backupCheckDisabled()).toBe(false);++ // unset → key removed from the file, default (enabled) restored.+ const out2 = await captureLog(() => runConfig(noEngine, ['unset', 'backup.check_enabled']));+ expect(out2).toContain('Unset backup.check_enabled (file plane)');+ cfg = JSON.parse(readFileSync(cfgPath, 'utf8')) as { backup?: { check_enabled?: boolean } };+ expect(cfg.backup?.check_enabled).toBeUndefined();+ expect(backupCheckDisabled()).toBe(false);+ });+ });++ test('backup.check_interval_days: 7 lands nested and backupIntervalMs() = 7d; unset restores the 30d default', async () => {+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-backup2-'));+ // Env resolves ABOVE config in backupIntervalMs — clear it; also clear any+ // leftover test-seam override so the config value is what resolves.+ __setBackupIntervalForTests(null);+ await withEnv({ GBRAIN_HOME: parent, GBRAIN_BACKUP_CHECK_DAYS: undefined }, async () => {+ const out = await captureLog(() => runConfig(noEngine, ['set', 'backup.check_interval_days', '7']));+ expect(out).toContain('Set backup.check_interval_days = 7');+ expect(out).toContain('file plane');+ const cfgPath = join(parent, '.gbrain', 'config.json');+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf8')) as { backup?: { check_interval_days?: number } };+ expect(cfg.backup?.check_interval_days).toBe(7);+ expect(backupIntervalMs()).toBe(7 * DAY);++ // unset → default interval restored.+ await captureLog(() => runConfig(noEngine, ['unset', 'backup.check_interval_days']));+ expect(backupIntervalMs()).toBe(BACKUP_INTERVAL_DAYS_DEFAULT * DAY);+ });+ });++ test('backup.check_interval_days: "0" and "abc" are refused (exit 1, nothing written)', async () => {+ const parent = mkdtempSync(join(tmpdir(), 'gb-cfg-backup3-'));+ await withEnv({ GBRAIN_HOME: parent, GBRAIN_BACKUP_CHECK_DAYS: undefined }, async () => {+ const cfgPath = join(parent, '.gbrain', 'config.json');+ for (const bad of ['0', 'abc']) {+ const { err, exitCode } = await captureErrExit(() =>+ runConfig(noEngine, ['set', 'backup.check_interval_days', bad]));+ expect(exitCode).toBe(1);+ expect(err).toContain('backup.check_interval_days must be an integer >= 1');+ expect(existsSync(cfgPath)).toBe(false); // the refused set wrote NOTHING+ }+ });+ });+});+/*** Vendor API keys are FILE-plane canonical too.*diff --git a/test/doctor-backup-coverage.serial.test.ts b/test/doctor-backup-coverage.serial.test.tsnew file mode 100644index 0000000000..71f1f02391--- /dev/null+++ b/test/doctor-backup-coverage.serial.test.ts@@ -0,0 +1,306 @@+/**+ * doctor/checks/backup-coverage.ts — checkBackupCoverage.+ *+ * Pins the D4 trust boundary: git probes against DB-supplied local_path run+ * ONLY on the trusted local doctor path (localOnly: true). The remote surface+ * is a cache-only, AGGREGATE-ONLY reader — it must never spawn git, never+ * touch the engine, and never surface asset ids / local paths (counts only).+ *+ * Isolation: tmp GBRAIN_HOME (configDir() appends '.gbrain'), the status-file+ * path seams, real tmp git fixtures (no-origin repo; origin-backed clean repo+ * pushed to a local bare — file transport, no network), and a minimal engine+ * stub cast to BrainEngine that serves `sources` / `pages` via executeRaw.+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import { checkBackupCoverage } from '../src/commands/doctor/checks/backup-coverage.ts';+import {+ BACKUP_STATUS_SCHEMA_VERSION,+ __setBackupIntervalForTests,+ __setBackupNagStatePathForTests,+ __setBackupStatusPathForTests,+ saveBackupStatus,+ type BackupStatus,+} from '../src/core/backup/status-file.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const ENV_KEYS = ['GBRAIN_HOME', 'GBRAIN_BACKUP_CHECK', 'GBRAIN_BACKUP_CHECK_DAYS'] as const;++let tmp: string;+let saved: Record<string, string | undefined>;+let statusFile: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-bkcov-'));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp; // configDir() === join(tmp, '.gbrain')+ statusFile = join(tmp, 'state', 'backup-status.json');+ __setBackupStatusPathForTests(statusFile);+ __setBackupNagStatePathForTests(join(tmp, 'state', 'backup-nag-state.json'));+});++afterEach(() => {+ __setBackupStatusPathForTests(null);+ __setBackupNagStatePathForTests(null);+ __setBackupIntervalForTests(null);+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++// ── Fixtures ─────────────────────────────────────────────────────────────────++function git(dir: string, args: string[]): void {+ execFileSync(+ 'git',+ ['-C', dir, '-c', '[email protected]', '-c', 'user.name=t', '-c', 'commit.gpgsign=false', ...args],+ { stdio: ['ignore', 'ignore', 'ignore'], timeout: 30_000 },+ );+}++/** Local git repo with one commit and NO origin remote. */+function makeNoOriginRepo(name: string): string {+ const dir = join(tmp, name);+ mkdirSync(dir, { recursive: true });+ execFileSync('git', ['init', '-q', '-b', 'main', dir], { stdio: ['ignore', 'ignore', 'ignore'] });+ writeFileSync(join(dir, 'note.md'), '# hello\n');+ git(dir, ['add', '.']);+ git(dir, ['commit', '-q', '-m', 'init']);+ return dir;+}++/** Clean repo pushed to a local bare origin (file transport — no network). */+function makeHealthyRepo(name: string): string {+ const dir = makeNoOriginRepo(name);+ const bare = join(tmp, `${name}-origin.git`);+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare], { stdio: ['ignore', 'ignore', 'ignore'] });+ git(dir, ['remote', 'add', 'origin', bare]);+ git(dir, ['push', '-q', '-u', 'origin', 'main']);+ return dir;+}++/** Minimal engine stub (dispatch-response-meta idiom) — never a real PGLite. */+function makeEngine(sourcePaths: Array<{ id: string; local_path: string }>, pageCount = 0): BrainEngine {+ return {+ kind: 'pglite',+ executeRaw: async (sql: string) => {+ if (/FROM sources/i.test(sql)) {+ return sourcePaths.map((s) => ({+ id: s.id,+ name: s.id,+ local_path: s.local_path,+ last_commit: null,+ last_sync_at: null,+ config: '{}',+ created_at: new Date(),+ archived: false,+ newest_content_at: null,+ }));+ }+ if (/FROM pages/i.test(sql)) return [{ n: pageCount }];+ throw new Error(`unexpected sql in stub: ${sql}`);+ },+ } as unknown as BrainEngine;+}++/** Engine stub that throws on ANY property access — the remote-path trust pin. */+function makeThrowingEngine(): BrainEngine {+ return new Proxy(+ {},+ {+ get(_t, prop) {+ throw new Error(`engine touched on remote/disabled path: ${String(prop)}`);+ },+ },+ ) as unknown as BrainEngine;+}++function makeWarnCache(assetId: string): BackupStatus {+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: new Date(Date.now() - 60_000).toISOString(),+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall: 'warn',+ totals: { assets: 1, no_remote: 1, unpushed: 0, failing: 0, recoverable_repos: 0, pages_at_risk: 0 },+ assets: [{ kind: 'source_repo', id: assetId, state: 'no_remote', detail: 'fixture', fix_argv: null }],+ };+}++// ── Local (trusted) path: probes run ─────────────────────────────────────────++describe('checkBackupCoverage — localOnly (trusted, probes run)', () => {+ test('no-origin source repo → warn naming the asset, points at gbrain backup status', async () => {+ const repo = makeNoOriginRepo('src-a');+ const check = await checkBackupCoverage(makeEngine([{ id: 'src-a', local_path: repo }]), {+ localOnly: true,+ });++ expect(check.name).toBe('backup_coverage');+ expect(check.status).toBe('warn');+ expect(check.message).toContain('gbrain backup status');+ expect(check.message).toContain('src-a');+ expect(check.message).toContain('no git remote');++ const details = check.details as { totals: BackupStatus['totals']; computed_by: string };+ expect(details.totals.no_remote).toBe(1);+ expect(details.computed_by).toBe('doctor');+ // Probed compute persists the verdict cache (getBackupStatus discipline).+ expect(existsSync(statusFile)).toBe(true);+ });++ test('healthy repo (origin, pushed, clean) → ok with recoverable count', async () => {+ const repo = makeHealthyRepo('src-b');+ const check = await checkBackupCoverage(makeEngine([{ id: 'src-b', local_path: repo }], 3), {+ localOnly: true,+ });++ expect(check.name).toBe('backup_coverage');+ expect(check.status).toBe('ok');+ expect(check.message).toContain('1 knowledge repo(s) git-backed');+ expect(check.message).toContain('last checked');++ const details = check.details as { totals: BackupStatus['totals'] };+ expect(details.totals.recoverable_repos).toBe(1);+ expect(details.totals.no_remote).toBe(0);+ });+});++// ── Remote (untrusted) path: cache-only reader, zero git, zero engine ────────++describe('checkBackupCoverage — remote surface (no localOnly)', () => {+ test('no cache → ok, "not checked from this surface", engine untouched', async () => {+ const check = await checkBackupCoverage(makeThrowingEngine(), {});+ expect(check.name).toBe('backup_coverage');+ expect(check.status).toBe('ok');+ expect(check.message).toContain('not checked from this surface');+ expect(check.message).toContain('gbrain backup check');+ });++ test('warn cache → AGGREGATE-ONLY warn from cache; zero git subprocesses, zero engine calls', async () => {+ // Trust pin (D4): the cached asset id points at a REAL git repo dir. If+ // the remote path probed git or touched the engine, the throwing engine+ // stub would blow up. And the remote surface is aggregate-only: the+ // message carries COUNTS ('N of M'), never the asset id / local path.+ const repo = makeNoOriginRepo('real-repo-dir');+ saveBackupStatus(makeWarnCache(repo));++ const check = await checkBackupCoverage(makeThrowingEngine(), {});++ expect(check.name).toBe('backup_coverage');+ expect(check.status).toBe('warn');+ expect(check.message).toContain('1 of 1'); // aggregate counts+ expect(check.message).not.toContain(repo); // NEVER the asset id / local path+ expect(check.message).not.toContain('real-repo-dir');+ expect(check.message).toContain('gbrain backup status');++ const details = check.details as { note?: string; computed_by?: string; cache_age?: string };+ expect(details.note).toBe('cache-only (remote surface never probes git; aggregate counts only)');+ expect(details.computed_by).toBeUndefined(); // remote details drop provenance+ expect(typeof details.cache_age).toBe('string');+ });++ test('ok cache → ok from cache with the cache-only note', async () => {+ saveBackupStatus({+ ...makeWarnCache('unused'),+ overall: 'ok',+ totals: { assets: 1, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 1, pages_at_risk: 0 },+ assets: [{ kind: 'source_repo', id: 'unused', state: 'ok' }],+ });+ const check = await checkBackupCoverage(makeThrowingEngine(), {});+ expect(check.status).toBe('ok');+ expect(check.message).toContain('1 knowledge repo(s) git-backed');+ expect((check.details as { note?: string }).note).toBe(+ 'cache-only (remote surface never probes git; aggregate counts only)',+ );+ });+});++// ── Kill switch ───────────────────────────────────────────────────────────────++describe('checkBackupCoverage — GBRAIN_BACKUP_CHECK=0', () => {+ test('disabled → ok with "disabled" message, no probes, no engine, no cache write', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ const check = await checkBackupCoverage(makeThrowingEngine(), { localOnly: true });+ expect(check.name).toBe('backup_coverage');+ expect(check.status).toBe('ok');+ expect(check.message).toContain('disabled');+ // Early return: no compute ran, so nothing was persisted.+ expect(existsSync(statusFile)).toBe(false);+ });++ test('disabled shadows even a stale warn cache on the remote surface', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ saveBackupStatus(makeWarnCache('anything'));+ const check = await checkBackupCoverage(makeThrowingEngine(), {});+ expect(check.status).toBe('ok');+ expect(check.message).toContain('disabled');+ });+});++// ── Local catch branch: getBackupStatus rethrows, checker degrades to warn ───++describe('checkBackupCoverage — localOnly catch branch', () => {+ test('compute throws with NO cache → warn "backup coverage unreadable", nothing persisted', async () => {+ // Verified against the source: a throwing engine alone only DEGRADES the+ // verdict (loadAllSources/countLivePages catch internally — no throw). To+ // make getBackupStatus itself throw through the public API, inject an+ // Invalid Date (checked_at serialization throws mid-compute — the same+ // idiom as backup-coverage.serial.test.ts). With NO cache to fall back+ // to, getBackupStatus rethrows and the checker's try/catch owns it.+ const throwing = {+ kind: 'pglite',+ executeRaw: async () => {+ throw new Error('engine down');+ },+ } as unknown as BrainEngine;++ expect(existsSync(statusFile)).toBe(false);+ const check = await checkBackupCoverage(throwing, {+ localOnly: true,+ now: new Date('not-a-date'),+ });++ expect(check).toEqual({+ name: 'backup_coverage',+ status: 'warn',+ message: 'backup coverage unreadable',+ });+ // The failed compute never persisted anything (no clobber, no cache).+ expect(existsSync(statusFile)).toBe(false);+ });++ test('broken compute WITH a cache → the cached verdict is returned, not the unreadable warn', async () => {+ // The sibling path: with a cache present, getBackupStatus never surfaces+ // the failure (a fresh cache short-circuits; even a failed compute falls+ // back to the prior verdict) — the checker renders the cached verdict.+ const cache = makeWarnCache('cached-asset-src');+ saveBackupStatus(cache);+ const throwing = {+ kind: 'pglite',+ executeRaw: async () => {+ throw new Error('engine down');+ },+ } as unknown as BrainEngine;++ const check = await checkBackupCoverage(throwing, {+ localOnly: true,+ now: new Date('not-a-date'),+ });++ expect(check.status).toBe('warn');+ expect(check.message).toContain('cached-asset-src'); // local surface names assets+ expect(check.message).not.toBe('backup coverage unreadable');+ });+});diff --git a/test/hook-backup-notice.serial.test.ts b/test/hook-backup-notice.serial.test.tsnew file mode 100644index 0000000000..3d19d85cd4--- /dev/null+++ b/test/hook-backup-notice.serial.test.ts@@ -0,0 +1,278 @@+/**+ * `gbrain hook` monthly backup-coverage integration points (hook.ts):+ * 1. session-start digest note (backupSessionStartNote, 'hook-note' channel,+ * record-after-write + 24h cross-channel dampener);+ * 2. user-prompt banner on the degraded no-serve path (pendingBackupBanner,+ * 'hook-banner' channel), with the push-failure banner outranking it;+ * 3. session-end detached `gbrain backup check --quiet` spawn (stale-or-absent+ * cache only, 24h debounce via last_spawn_at in the nag file, kill switch).+ *+ * hook.ts reads the REAL cache/nag paths under GBRAIN_HOME (status-file.ts+ * seams stay at their defaults), so tests write the cache via saveBackupStatus()+ * against the tmp home. Follows test/hook-command.serial.test.ts exactly for+ * env save/restore + tmp GBRAIN_HOME + collectStdout + runHook.+ */+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { runHook } from '../src/commands/hook.ts';+import { pushStatusPathForRoot } from '../src/core/workspace-push.ts';+import {+ BACKUP_STATUS_SCHEMA_VERSION,+ BACKUP_NAG_SCHEMA_VERSION,+ saveBackupStatus,+ __setBackupStatusPathForTests,+ __setBackupNagStatePathForTests,+ __setBackupIntervalForTests,+ type BackupStatus,+} from '../src/core/backup/status-file.ts';++const ENV_KEYS = [+ 'GBRAIN_HOME', 'DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE', 'GBRAIN_HOOKS',+ // stop-push [D3/D17/D20] + banner [D5] + cloud detection knobs+ 'GBRAIN_STOP_PUSH', 'GBRAIN_STOP_PUSH_DEBOUNCE_MIN', 'CLAUDE_CODE_REMOTE',+ 'CLAUDE_CODE_REMOTE_SESSION_ID', 'GH_TOKEN', 'GITHUB_TOKEN',+ // backup-check knobs+ 'GBRAIN_BACKUP_CHECK', 'GBRAIN_BACKUP_CHECK_DAYS', 'GBRAIN_FORCE_BACKUP_NAG',+] as const;++let tmp: string;+let saved: Record<string, string | undefined>;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-hkbk-'));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp; // cache/nag/heartbeat all under tmp/.gbrain+ // Seams stay at DEFAULT — they resolve under the tmp GBRAIN_HOME. The+ // explicit nulls just guard against leakage from another file in-process.+ __setBackupStatusPathForTests(null);+ __setBackupNagStatePathForTests(null);+ __setBackupIntervalForTests(null);+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++const home = () => join(tmp, '.gbrain');+const nagPath = () => join(home(), 'backup-nag-state.json');++function collectStdout(): { io: { write: (s: string) => void }; get: () => string } {+ let buf = '';+ return { io: { write: (s: string) => { buf += s; } }, get: () => buf };+}++interface NagFileShape {+ schema_version: string;+ entries: Array<{ brain_id: string; source_id: string; pack_name: string; declined_count: number }>;+ last_shown_at?: string;+ global_shown_count?: number;+ global_month?: string;+ last_spawn_at?: string;+}++function readNagState(): NagFileShape {+ return JSON.parse(readFileSync(nagPath(), 'utf8')) as NagFileShape;+}++function makeStatus(overall: 'ok' | 'warn'): BackupStatus {+ const noRemote = overall === 'warn' ? 1 : 0;+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: new Date().toISOString(), // fresh — well inside the 30d window+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall,+ totals: {+ assets: 2,+ no_remote: noRemote,+ unpushed: 0,+ failing: 0,+ recoverable_repos: 2 - noRemote,+ pages_at_risk: 0,+ },+ assets: [+ overall === 'warn'+ ? { kind: 'source_repo', id: 'wiki-example', state: 'no_remote', fix_argv: null }+ : { kind: 'source_repo', id: 'wiki-example', state: 'ok' },+ { kind: 'bootstrap_workspace', id: join(tmp, 'ws-example'), state: 'ok' },+ ],+ };+}++function makeWs(name: string): string {+ const ws = join(tmp, name);+ mkdirSync(ws, { recursive: true });+ return ws;+}++// ── 1. session-start digest note ('hook-note') ──────────────────────────────++describe('session-start backup note (hook-note channel)', () => {+ test('warn cache → digest carries "Backup check:", ONE hook-note impression; immediate re-run is dampened', async () => {+ saveBackupStatus(makeStatus('warn'));+ const ws = makeWs('ws');++ const out = collectStdout();+ expect(await runHook(['session-start'], { ...out.io, stdin: '', cwd: ws })).toBe(0);+ const text = out.get();+ expect(text).toContain('Backup check:');+ expect(text).toContain("aren't on any git remote");+ expect(text).toContain('wiki-example');++ // Record-after-write: exactly ONE impression landed in the nag file.+ const state = readNagState();+ expect(state.schema_version).toBe(BACKUP_NAG_SCHEMA_VERSION);+ const noteEntries = state.entries.filter((e) => e.pack_name === 'hook-note');+ expect(noteEntries).toHaveLength(1);+ expect(noteEntries[0]!.brain_id).toBe('host');+ expect(noteEntries[0]!.source_id).toBe('backup');+ expect(noteEntries[0]!.declined_count).toBe(1);+ expect(state.global_shown_count).toBe(1);+ expect(state.last_shown_at).toBeDefined();++ // A second session-start immediately after: the 24h cross-channel+ // dampener suppresses the note; the budget is not spent again.+ const out2 = collectStdout();+ expect(await runHook(['session-start'], { ...out2.io, stdin: '', cwd: ws })).toBe(0);+ expect(out2.get()).not.toContain('Backup check:');+ const state2 = readNagState();+ expect(state2.global_shown_count).toBe(1);+ expect(state2.entries.filter((e) => e.pack_name === 'hook-note')).toHaveLength(1);+ });++ test('ok cache → no backup note in the digest, no nag state written', async () => {+ saveBackupStatus(makeStatus('ok'));+ const ws = makeWs('ws-ok');+ const out = collectStdout();+ expect(await runHook(['session-start'], { ...out.io, stdin: '', cwd: ws })).toBe(0);+ expect(out.get()).not.toContain('Backup check:');+ expect(existsSync(nagPath())).toBe(false);+ });++ test('GBRAIN_BACKUP_CHECK=0 silences a warn cache (kill switch beats a stale warn)', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ saveBackupStatus(makeStatus('warn'));+ const ws = makeWs('ws-off');+ const out = collectStdout();+ expect(await runHook(['session-start'], { ...out.io, stdin: '', cwd: ws })).toBe(0);+ expect(out.get()).not.toContain('Backup check:');+ expect(existsSync(nagPath())).toBe(false);+ });+});++// ── 2. user-prompt banner ('hook-banner') on the degraded no-serve path ─────++describe('user-prompt backup banner (hook-banner channel)', () => {+ test('warn cache + no serve → banner-only JSON payload with systemMessage AND additionalContext; hook-banner impression recorded', async () => {+ saveBackupStatus(makeStatus('warn'));+ const out = collectStdout();+ // No config at all → the main payload never writes (degraded rail); the+ // backup banner rides the banner-only emission path.+ expect(await runHook(['user-prompt'], { ...out.io, stdin: '{}' })).toBe(0);+ const payload = JSON.parse(out.get()) as {+ hookSpecificOutput?: { hookEventName?: string; additionalContext?: string };+ systemMessage?: string;+ };+ expect(payload.hookSpecificOutput?.hookEventName).toBe('UserPromptSubmit');+ expect(payload.systemMessage).toContain('NOTICE:');+ expect(payload.systemMessage).toContain("aren't on any git remote");+ expect(payload.systemMessage).toContain('gbrain backup status');+ expect(payload.hookSpecificOutput?.additionalContext).toBe(payload.systemMessage!);++ const state = readNagState();+ const bannerEntries = state.entries.filter((e) => e.pack_name === 'hook-banner');+ expect(bannerEntries).toHaveLength(1);+ expect(bannerEntries[0]!.declined_count).toBe(1);+ expect(state.global_shown_count).toBe(1);+ });++ test('push-failure banner outranks the backup banner (single banner slot)', async () => {+ saveBackupStatus(makeStatus('warn'));+ // A failing push status for an EXISTING root (ghost entries are filtered).+ const root = makeWs('banner-brain');+ mkdirSync(join(home(), 'bootstrap'), { recursive: true });+ writeFileSync(+ pushStatusPathForRoot(root),+ JSON.stringify({ ts: new Date().toISOString(), ok: false, reason: 'refused_visibility: origin unverifiable', repoRoot: root }) + '\n',+ { mode: 0o600 },+ );++ const out = collectStdout();+ expect(await runHook(['user-prompt'], { ...out.io, stdin: JSON.stringify({ prompt: 'hi' }) })).toBe(0);+ const payload = JSON.parse(out.get()) as {+ hookSpecificOutput?: { additionalContext?: string };+ systemMessage?: string;+ };+ // The PUSH failure text won the slot…+ expect(payload.systemMessage).toContain('FAILING');+ expect(payload.systemMessage).toContain('NOT on GitHub');+ expect(payload.hookSpecificOutput?.additionalContext).toContain('FAILING');+ // …and the backup text is nowhere in the payload.+ expect(payload.systemMessage).not.toContain('knowledge assets');+ expect(payload.hookSpecificOutput?.additionalContext).not.toContain('knowledge assets');+ // The backup gate was never consulted/recorded — no hook-banner impression.+ if (existsSync(nagPath())) {+ expect(readNagState().entries.filter((e) => e.pack_name === 'hook-banner')).toHaveLength(0);+ }+ });+});++// ── 3. session-end detached backup-check spawn ──────────────────────────────++function sessionEndIo(ws: string, spy: () => void) {+ return {+ write: () => {},+ stdin: JSON.stringify({ session_id: 'sess-bkp', cwd: ws }),+ spawnPush: () => {},+ spawnBackupCheck: spy,+ };+}++describe('session-end backup-check spawn (24h debounce)', () => {+ test('stale-or-absent cache → spawns once; second session-end debounced via last_spawn_at', async () => {+ const ws = makeWs('ws-end');+ let spawns = 0;+ const io = sessionEndIo(ws, () => { spawns++; });++ // No cache file at all: absent counts as stale → spawn.+ expect(await runHook(['session-end'], io)).toBe(0);+ expect(spawns).toBe(1);+ // Debounce banked in the nag file (recorded BEFORE the spawn).+ expect(readNagState().last_spawn_at).toBeDefined();++ // Second session-end immediately after: still no cache (the spy wrote+ // nothing), but the 24h last_spawn_at debounce holds — no second spawn.+ expect(await runHook(['session-end'], io)).toBe(0);+ expect(spawns).toBe(1);+ });++ test('fresh ok cache → no spawn (nothing stale to recompute)', async () => {+ saveBackupStatus(makeStatus('ok'));+ const ws = makeWs('ws-end-ok');+ let spawns = 0;+ expect(await runHook(['session-end'], sessionEndIo(ws, () => { spawns++; }))).toBe(0);+ expect(spawns).toBe(0);+ // recordBackupSpawn never ran — no debounce state was written.+ expect(existsSync(nagPath())).toBe(false);+ });++ test('GBRAIN_BACKUP_CHECK=0 → no spawn even with an absent cache', async () => {+ process.env.GBRAIN_BACKUP_CHECK = '0';+ const ws = makeWs('ws-end-off');+ let spawns = 0;+ expect(await runHook(['session-end'], sessionEndIo(ws, () => { spawns++; }))).toBe(0);+ expect(spawns).toBe(0);+ expect(existsSync(nagPath())).toBe(false);+ });+});diff --git a/test/mcp-backup-nag.serial.test.ts b/test/mcp-backup-nag.serial.test.tsnew file mode 100644index 0000000000..6b53ebca92--- /dev/null+++ b/test/mcp-backup-nag.serial.test.ts@@ -0,0 +1,335 @@+/**+ * Dispatch-layer backup nag (src/mcp/dispatch.ts):+ * - maybeAttachBackupNotice — the once-per-process AGGREGATE extra content+ * block on STDIO tool calls (content[0] untouched; counts only, never a+ * local path / source id). The notice is stdio-ONLY: 'http', an UNSET+ * transport marker, and local callers (remote: false) get NO block;+ * - the hourly recheck latch (backupNoticeCheckedMs): once a consult ran,+ * later cache changes within the hour are invisible until+ * __resetBackupNoticeForTests;+ * - the stdio-gated maybeRefreshBackupStatusInProcess call — the TRUST PIN:+ * 'http' or an UNSET transport marker never computes (fail-closed),+ * 'stdio' kicks the in-process refresher. The refresher arms its 1h+ * attempt floor even on the fresh-cache no-op path — a second call that+ * must compute needs __resetBackupRefreshForTests first;+ * - nag-gate integration: showing the block records an 'mcp' entry and+ * spends one unit of the global monthly budget.+ *+ * Serial: mock.module (hybridSearchCached is mocked BEFORE dispatch import,+ * following test/dispatch-response-meta.serial.test.ts).+ */++import { describe, test, expect, mock, beforeEach, afterEach } from 'bun:test';+import { existsSync, mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import * as realHybrid from '../src/core/search/hybrid.ts';+import type { BrainEngine } from '../src/core/engine.ts';++let nextResults: unknown[] = [{ page_id: 1, slug: 'a', chunk_text: 'x' }];++// Mock BEFORE importing dispatch (operations.ts binds hybridSearchCached at+// import time; the spread keeps every other export live).+mock.module('../src/core/search/hybrid.ts', () => ({+ ...realHybrid,+ hybridSearchCached: async () => nextResults,+}));++const { dispatchToolCall, __resetBackupNoticeForTests } = await import('../src/mcp/dispatch.ts');+const {+ BACKUP_STATUS_SCHEMA_VERSION,+ backupStatusPath,+ loadBackupStatus,+ loadBackupNagState,+ saveBackupStatus,+ __setBackupStatusPathForTests,+ __setBackupNagStatePathForTests,+ __setBackupIntervalForTests,+} = await import('../src/core/backup/status-file.ts');+type BackupStatus = import('../src/core/backup/status-file.ts').BackupStatus;+const { __resetBackupRefreshForTests } = await import('../src/core/backup/coverage.ts');++// ── engine stub (records executeRaw SQL; never a real PGLite) ───────────────++let rawCalls: string[] = [];+const engineStub = {+ kind: 'pglite',+ getConfig: async () => null,+ executeRaw: async (sql: string) => {+ rawCalls.push(String(sql));+ // countLivePages treats an EMPTY rowset as UNESTABLISHED (null → degraded+ // verdict, never persisted) — a healthy stub must answer the pages count+ // with a real number or the refresher pins below would never see a cache.+ if (/\bfrom\s+pages\b/i.test(String(sql))) return [{ n: 0 }];+ return [];+ },+} as unknown as BrainEngine;++// ── fixture verdicts ────────────────────────────────────────────────────────++const SECRET_PATH = '/tmp/very-secret-repo/notes';+const SECRET_SOURCE = 'client-source-alpha';+const OK_SOURCE = 'ok-repo-beta';++function warnStatus(): BackupStatus {+ return {+ schema_version: BACKUP_STATUS_SCHEMA_VERSION,+ checked_at: new Date().toISOString(),+ gbrain_version: '0.0.0-test',+ interval_days: 30,+ computed_by: 'cli',+ overall: 'warn',+ totals: { assets: 3, no_remote: 2, unpushed: 0, failing: 0, recoverable_repos: 1, pages_at_risk: 0 },+ assets: [+ { kind: 'source_repo', id: SECRET_PATH, state: 'no_remote', detail: 'fix: add a remote', fix_argv: null },+ { kind: 'bootstrap_workspace', id: SECRET_SOURCE, state: 'no_remote', fix_argv: ['gbrain', 'bootstrap', 'repo'] },+ { kind: 'source_repo', id: OK_SOURCE, state: 'ok' },+ ],+ };+}++function okStatus(): BackupStatus {+ return {+ ...warnStatus(),+ overall: 'ok',+ totals: { assets: 1, no_remote: 0, unpushed: 0, failing: 0, recoverable_repos: 1, pages_at_risk: 0 },+ assets: [{ kind: 'source_repo', id: OK_SOURCE, state: 'ok' }],+ };+}++// ── dispatch helpers ────────────────────────────────────────────────────────++type CallOpts = { remote?: boolean; transport?: 'stdio' | 'http' };++// Default transport is 'stdio' — the ONLY transport the notice fires on.+// Trust-pin tests pass 'http' / undefined explicitly.+function callSearch(opts: CallOpts = {}) {+ return dispatchToolCall(engineStub, 'search', { query: 'anything at all' }, {+ remote: true,+ transport: 'stdio',+ sourceId: 'default',+ ...opts,+ });+}++async function waitFor(pred: () => boolean, ms = 2000): Promise<boolean> {+ const start = Date.now();+ while (Date.now() - start < ms) {+ if (pred()) return true;+ await new Promise((r) => setTimeout(r, 25));+ }+ return pred();+}++// ── isolation (hook-command.serial.test.ts idiom) ───────────────────────────++const ENV_KEYS = ['GBRAIN_HOME', 'GBRAIN_BACKUP_CHECK', 'GBRAIN_BACKUP_CHECK_DAYS'] as const;++let tmp: string;+let saved: Record<string, string | undefined>;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-mcp-nag-'));+ saved = {};+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ process.env.GBRAIN_HOME = tmp; // status/nag files land under tmp/.gbrain+ // Kill any path overrides another serial file may have left behind.+ __setBackupStatusPathForTests(null);+ __setBackupNagStatePathForTests(null);+ __setBackupIntervalForTests(null);+ __resetBackupNoticeForTests();+ __resetBackupRefreshForTests();+ rawCalls = [];+ nextResults = [{ page_id: 1, slug: 'a', chunk_text: 'x' }];+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ rmSync(tmp, { recursive: true, force: true });+});++// ── the pins ────────────────────────────────────────────────────────────────++describe('maybeAttachBackupNotice (stdio aggregate block)', () => {+ test("warn cache + transport 'stdio' → extra block once per process; content[0] untouched", async () => {+ saveBackupStatus(warnStatus());++ const first = await callSearch({ remote: true, transport: 'stdio' });+ expect(first.isError).toBeUndefined();+ // content[0] is UNCHANGED — still the bare op result.+ expect(JSON.parse(first.content[0].text)).toEqual(nextResults);+ // The backup block rides as an EXTRA block.+ expect(first.content.length).toBe(2);+ const block = first.content[1].text;+ expect(block).toContain('backup');+ expect(block).toContain('2 of 3');+ expect(block).toContain('no git remote');++ // Once per process: the second call carries NO backup block.+ const second = await callSearch({ remote: true, transport: 'stdio' });+ expect(second.content.length).toBe(1);+ expect(JSON.parse(second.content[0].text)).toEqual(nextResults);+ });++ test("transport 'http' + warn cache → NO block (stdio-only notice); a later stdio call still gets it", async () => {+ saveBackupStatus(warnStatus());++ const http = await callSearch({ remote: true, transport: 'http' });+ expect(http.content.length).toBe(1);+ expect(JSON.parse(http.content[0].text)).toEqual(nextResults);++ // The http call must not burn the once-per-process flag or arm the+ // hourly latch — the first stdio call still attaches the block.+ const stdio = await callSearch({ remote: true, transport: 'stdio' });+ expect(stdio.content.length).toBe(2);+ expect(stdio.content[1].text).toContain('2 of 3');+ });++ test('transport UNSET + warn cache → NO block (fail-closed)', async () => {+ saveBackupStatus(warnStatus());+ const out = await callSearch({ remote: true, transport: undefined });+ expect(out.content.length).toBe(1);+ expect(JSON.parse(out.content[0].text)).toEqual(nextResults);+ });++ test('aggregate block never leaks local paths or source ids', async () => {+ saveBackupStatus(warnStatus());+ const out = await callSearch();+ expect(out.content.length).toBe(2);+ const block = out.content[1].text;+ expect(block).not.toContain(SECRET_PATH);+ expect(block).not.toContain('very-secret-repo');+ expect(block).not.toContain(SECRET_SOURCE);+ expect(block).not.toContain(OK_SOURCE);+ });++ test('ok cache → no backup block', async () => {+ saveBackupStatus(okStatus());+ const out = await callSearch();+ expect(out.content.length).toBe(1);+ });++ test('absent cache → no backup block', async () => {+ const out = await callSearch();+ expect(out.content.length).toBe(1);+ // Default transport is stdio, so the fire-and-forget refresher computes+ // in the background — let it settle before afterEach tears tmp down.+ await waitFor(() => existsSync(backupStatusPath()), 2000);+ });++ test('GBRAIN_BACKUP_CHECK=0 kill switch silences a warn cache', async () => {+ saveBackupStatus(warnStatus());+ process.env.GBRAIN_BACKUP_CHECK = '0';+ const out = await callSearch();+ expect(out.content.length).toBe(1);+ });++ test('opts.remote:false (local gbrain call) → no backup block even with warn cache on stdio', async () => {+ saveBackupStatus(warnStatus());+ const out = await callSearch({ remote: false, transport: 'stdio' });+ expect(out.content.length).toBe(1);+ expect(JSON.parse(out.content[0].text)).toEqual(nextResults);+ });++ test('hourly latch: an ok-cache consult blinds a warn cache written moments later, until reset', async () => {+ // First consult sees an ok cache: no block, but backupNoticeCheckedMs arms.+ saveBackupStatus(okStatus());+ const first = await callSearch();+ expect(first.content.length).toBe(1);++ // The cache flips to warn a moment later IN THE SAME PROCESS — the+ // hourly recheck latch means dispatch does not re-read the file yet.+ saveBackupStatus(warnStatus());+ const latched = await callSearch();+ expect(latched.content.length).toBe(1);++ // __resetBackupNoticeForTests clears the latch → the block attaches.+ __resetBackupNoticeForTests();+ const after = await callSearch();+ expect(after.content.length).toBe(2);+ expect(after.content[1].text).toContain('2 of 3');+ });++ test('nag-gate integration: one shown block records an mcp entry + global_shown_count 1', async () => {+ saveBackupStatus(warnStatus());+ const out = await callSearch();+ expect(out.content.length).toBe(2); // shown++ const state = loadBackupNagState();+ const entry = state.entries.find((e) => e.pack_name === 'mcp');+ expect(entry).toBeDefined();+ expect(entry!.brain_id).toBe('host');+ expect(entry!.source_id).toBe('backup');+ expect(entry!.declined_count).toBe(1);+ expect(state.global_shown_count).toBe(1);+ expect(state.global_month).toBe(new Date().toISOString().slice(0, 7));+ expect(typeof state.last_shown_at).toBe('string');+ });+});++describe('stdio-gated refresher (TRUST PIN)', () => {+ test("transport 'http' NEVER computes: cache stays absent, sources query never issued", async () => {+ expect(existsSync(backupStatusPath())).toBe(false);+ await callSearch({ remote: true, transport: 'http' });+ // The refresher is fire-and-forget; give a wrongly-started compute time+ // to land before asserting it never did.+ await new Promise((r) => setTimeout(r, 300));+ expect(existsSync(backupStatusPath())).toBe(false);+ expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);+ });++ test('transport UNSET is fail-closed: no compute, no sources query', async () => {+ expect(existsSync(backupStatusPath())).toBe(false);+ await callSearch({ remote: true, transport: undefined });+ await new Promise((r) => setTimeout(r, 300));+ expect(existsSync(backupStatusPath())).toBe(false);+ expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);+ });++ test("transport 'stdio' kicks the in-process refresher: absent cache gets computed + persisted", async () => {+ expect(existsSync(backupStatusPath())).toBe(false);+ await callSearch({ remote: true, transport: 'stdio' });++ const appeared = await waitFor(() => existsSync(backupStatusPath()), 2000);+ expect(appeared).toBe(true);++ const s = loadBackupStatus();+ expect(s).not.toBeNull();+ expect(s!.computed_by).toBe('serve');+ expect(s!.overall).toBe('ok'); // zero sources, zero pages → nothing at risk+ expect(s!.totals.assets).toBe(0);+ // The refresher DID walk the sources table on the stdio path.+ expect(rawCalls.some((sql) => /\bfrom\s+sources\b/i.test(sql))).toBe(true);+ });++ test('attempt floor arms on the fresh-cache no-op path: a deleted cache is NOT recomputed within the hour', async () => {+ // First stdio call consults a fresh ok cache → refresher no-ops but arms+ // its 1h attempt floor.+ saveBackupStatus(okStatus());+ await callSearch({ remote: true, transport: 'stdio' });+ await new Promise((r) => setTimeout(r, 100));+ expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);++ // Delete the cache. A second stdio call within the hour is still a no-op+ // — the floor, not the cache, gates the attempt.+ rmSync(backupStatusPath(), { force: true });+ await callSearch({ remote: true, transport: 'stdio' });+ await new Promise((r) => setTimeout(r, 300));+ expect(existsSync(backupStatusPath())).toBe(false);+ expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);++ // __resetBackupRefreshForTests clears the floor → the compute runs.+ __resetBackupRefreshForTests();+ await callSearch({ remote: true, transport: 'stdio' });+ const appeared = await waitFor(() => existsSync(backupStatusPath()), 2000);+ expect(appeared).toBe(true);+ expect(rawCalls.some((sql) => /\bfrom\s+sources\b/i.test(sql))).toBe(true);+ });+});