Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): pass an env allowlist to the remote-ref probe (#5794)
garrytan1d705bfe137f
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex d3e32017fd..0022ef7088 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -27,7 +27,7 @@- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts under the embed-skip threshold. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`).- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch.- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v1`; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.-- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. Tests: `test/backup-verification.serial.test.ts`, `test/backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.+- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.- `src/core/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 (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.mdindex be553cd3a5..be23e929b7 100644--- a/docs/operations/backup-check.md+++ b/docs/operations/backup-check.md@@ -114,6 +114,29 @@ a clean tree. Roots beyond the budget report `budget_exhausted`; successivesweeps can cover them. Background and stdio refreshes use local probes only;remote MCP doctor reads aggregate cache only, with no engine or Git access.+### Remote verification and your Git configuration++The probe runs `git` with an allowlist of your environment, so it reads your own+`~/.gitconfig`, credential helpers and `url.<base>.insteadOf` rewrites:+`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`,+`HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` (upper and lower case), plus+`USERPROFILE`, `APPDATA` and `SystemRoot` on Windows. It never passes `GIT_DIR`,+`GIT_WORK_TREE` or any other variable, and it always disables prompts.++A deploy key works through `~/.ssh/config` (`Host` with `IdentityFile`). The+probe sets its own `GIT_SSH_COMMAND` (`ssh -oBatchMode=yes+-oStrictHostKeyChecking=yes -oConnectTimeout=2`), so a `GIT_SSH_COMMAND` you+export is not used, and the remote's host key must already be in `known_hosts`.++| `verification.state` | Meaning | What to do |+|---|---|---|+| `verified` | The remote branch HEAD matches a clean local HEAD. | Nothing. |+| `missing_ref` | The remote answered but has no such branch. | `git push -u origin <branch>`, then `gbrain backup check`. |+| `mismatch` | The remote HEAD differs from the local HEAD, or the tree changed during the probe. | Push or pull until they match, then `gbrain backup check`. |+| <a id="remote-unavailable"></a>`unavailable` | `git ls-remote` failed: no network, authentication refused, or an unknown host key. The probe passes only `HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, `HTTPS_PROXY`/`https_proxy`, `HTTP_PROXY`/`http_proxy`, `NO_PROXY`/`no_proxy` (and `USERPROFILE`, `APPDATA`, `SystemRoot` on Windows). | Run `git -C <root> ls-remote origin` in the same shell; credentials must come from your Git config, a credential helper, `~/.ssh/config` or the SSH agent, not from a prompt or `GIT_SSH_COMMAND`. |+| `budget_exhausted` | The sweep's eight-probe or eight-second budget ran out first. | Run `gbrain backup check` again. |+| `stale`, `not_checked` | Earlier evidence expired or no probe ran yet. | `gbrain backup check`. |+When does the compute actually run? On any of: `gbrain backup check`, a stalecache at `backup status`/doctor/advisor time, `gbrain sync` completion, theserve process (stdio only) when the cache is stale or a warn verdict is >24hdiff --git a/src/core/backup/repository.ts b/src/core/backup/repository.tsindex eba98a51ca..2b71c7978f 100644--- a/src/core/backup/repository.ts+++ b/src/core/backup/repository.ts@@ -1,7 +1,7 @@import { execFile, execFileSync } from 'node:child_process';import { createHash } from 'node:crypto';import { existsSync, realpathSync, statSync } from 'node:fs';-import { GIT_ENV } from '../git-remote.ts';+import { buildGitEnv } from '../git-remote.ts';import { pushStatusPathForRoot, readPushStatusForRoot } from '../workspace-push.ts';import { readManifest } from '../bootstrap/format.ts';import { BACKUP_VERIFICATION_MAX_AGE_MS, type BackupAssetVerdict } from './status-file.ts';@@ -12,10 +12,29 @@ export const BACKUP_REMOTE_TIMEOUT_MS = 2_000;export interface RemoteProbeBudget { remaining: number; deadline?: number }+/** Variables that locate the user's own git config, credentials and network path. */+export const BACKUP_GIT_ENV_ALLOWLIST = ['HOME', 'PATH', 'XDG_CONFIG_HOME', 'SSH_AUTH_SOCK', 'GIT_CONFIG_GLOBAL',+ 'HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'NO_PROXY', 'no_proxy'] as const;+export const BACKUP_GIT_ENV_WINDOWS_ALLOWLIST = ['USERPROFILE', 'APPDATA', 'SystemRoot'] as const;++/**+ * The probe env passes only the allowlist, so git reads the user's config and+ * credential helpers (#5794) but never a repository-redirecting variable such+ * as GIT_DIR or GIT_WORK_TREE; the no-prompt overrides always win.+ */+export function backupGitEnv(source: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): Record<string, string> {+ const env: Record<string, string> = {};+ for (const key of [...BACKUP_GIT_ENV_ALLOWLIST, ...(platform === 'win32' ? BACKUP_GIT_ENV_WINDOWS_ALLOWLIST : [])]) {+ const value = source[key];+ if (value !== undefined) env[key] = value;+ }+ return { ...env, ...buildGitEnv(platform) };+}+function git(root: string, args: string[]): string {return execFileSync('git', ['-C', root, ...args], {encoding: 'utf8', timeout: 2_000, maxBuffer: 1024 * 1024,- stdio: ['ignore', 'pipe', 'pipe'], env: GIT_ENV,+ stdio: ['ignore', 'pipe', 'pipe'], env: backupGitEnv(),}).trim();}@@ -99,7 +118,7 @@ export async function assessBackupRepository('-c', 'protocol.https.allow=always', '-c', 'protocol.http.allow=always', '-c', 'protocol.ssh.allow=always','-c', 'http.followRedirects=false', '-c', 'credential.interactive=false', 'ls-remote', '--exit-code', '--refs', 'origin', ref], {encoding: 'utf8', timeout: Math.min(BACKUP_REMOTE_TIMEOUT_MS, remainingMs), maxBuffer: 64 * 1024,- env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', SSH_ASKPASS_REQUIRE: 'never', GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=2' },+ env: { ...backupGitEnv(), GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', SSH_ASKPASS_REQUIRE: 'never', GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=2' },}, (error, stdout) => error ? reject(error) : resolve(stdout));}).catch(error => {asset.verification = { state: error.code === 2 ? 'missing_ref' : 'unavailable', checked_at: now.toISOString(), repository_fingerprint: fingerprint };diff --git a/test/backup-git-env.test.ts b/test/backup-git-env.test.tsnew file mode 100644index 0000000000..3e04ad3c60--- /dev/null+++ b/test/backup-git-env.test.ts@@ -0,0 +1,37 @@+/** #5794: the backup probe's git env is an allowlist, never the whole process env. */+import { describe, expect, test } from 'bun:test';+import { backupGitEnv } from '../src/core/backup/repository.ts';+import { buildGitEnv } from '../src/core/git-remote.ts';++const source = {+ HOME: '/home/example', PATH: '/usr/bin', XDG_CONFIG_HOME: '/home/example/.config', SSH_AUTH_SOCK: '/tmp/agent.sock',+ GIT_CONFIG_GLOBAL: '/home/example/.gitconfig-work', HTTPS_PROXY: 'http://proxy.example:8080', https_proxy: 'http://proxy.example:8080',+ HTTP_PROXY: 'http://proxy.example:8080', http_proxy: 'http://proxy.example:8080', NO_PROXY: 'localhost', no_proxy: 'localhost',+ USERPROFILE: 'C:\\Users\\example', APPDATA: 'C:\\Users\\example\\AppData\\Roaming', SystemRoot: 'C:\\Windows',+ GIT_DIR: '/elsewhere/.git', GIT_WORK_TREE: '/elsewhere', GIT_ASKPASS: '/usr/bin/askpass', GIT_TERMINAL_PROMPT: '1', OPENAI_API_KEY: 'example-key',+};++describe('backup probe git env (#5794)', () => {+ test('passes the user config, credential and proxy variables on POSIX', () => {+ const env = backupGitEnv(source, 'linux');+ expect(Object.keys(env).sort()).toEqual(['GCM_INTERACTIVE', 'GIT_ASKPASS', 'GIT_CONFIG_GLOBAL', 'GIT_TERMINAL_PROMPT', 'HOME', 'HTTPS_PROXY', 'HTTP_PROXY',+ 'NO_PROXY', 'PATH', 'SSH_ASKPASS', 'SSH_AUTH_SOCK', 'XDG_CONFIG_HOME', 'http_proxy', 'https_proxy', 'no_proxy'].sort());+ expect(env).toMatchObject({ HOME: '/home/example', PATH: '/usr/bin', SSH_AUTH_SOCK: '/tmp/agent.sock', ...buildGitEnv('linux') });+ });++ test('adds the Windows profile variables only on Windows', () => {+ expect(backupGitEnv(source, 'win32')).toMatchObject({ USERPROFILE: source.USERPROFILE, APPDATA: source.APPDATA, SystemRoot: source.SystemRoot, ...buildGitEnv('win32') });+ expect(backupGitEnv(source, 'linux').USERPROFILE).toBeUndefined();+ });++ test('never passes repository-redirecting variables or secrets, and the no-prompt overrides win', () => {+ for (const platform of ['linux', 'darwin', 'win32'] as const) {+ const env = backupGitEnv(source, platform);+ expect(env.GIT_DIR).toBeUndefined();+ expect(env.GIT_WORK_TREE).toBeUndefined();+ expect(env.OPENAI_API_KEY).toBeUndefined();+ expect(env.GIT_TERMINAL_PROMPT).toBe('0');+ }+ expect(backupGitEnv(source, 'linux').GIT_ASKPASS).toBe('/bin/false');+ });+});diff --git a/test/backup-verification.serial.test.ts b/test/backup-verification.serial.test.tsindex c159a1aa57..2546957d81 100644--- a/test/backup-verification.serial.test.ts+++ b/test/backup-verification.serial.test.ts@@ -11,6 +11,7 @@ import { checkBackupCoverage } from '../src/commands/doctor/checks/backup-coveraimport { pushStatusPathForRoot } from '../src/core/workspace-push.ts';import { assessBackupRepository, BACKUP_REMOTE_PROBE_CAP, BACKUP_REMOTE_BUDGET_MS, BACKUP_REMOTE_TIMEOUT_MS } from '../src/core/backup/repository.ts';import { makeGitFixture } from './helpers/git-fixture.ts';+import { withEnv } from './helpers/with-env.ts';let tmp: string;let oldHome: string | undefined;@@ -279,3 +280,19 @@ test('retained evidence is invalidated by local identity, source, commit, remoteexpect(result.verification?.state).not.toBe('verified');}}, 15_000);++test('the remote probe reads the user git config through HOME, so an insteadOf rewrite reaches the remote (#5794)', async () => {+ const { root, remote } = await repository();+ const alias = 'https://example.invalid/private-backup.git';+ git(root, 'remote', 'set-url', 'origin', alias);+ const userHome = join(tmp, 'user-home');+ mkdirSync(userHome);+ writeFileSync(join(userHome, '.gitconfig'), `[url "${remote}"]\n\tinsteadOf = ${alias}\n`);+ const head = git(root, 'rev-parse', 'HEAD');+ await withEnv({ HOME: userHome, GIT_CONFIG_GLOBAL: undefined, XDG_CONFIG_HOME: undefined,+ GIT_DIR: join(tmp, 'not-a-repository'), GIT_WORK_TREE: join(tmp, 'not-a-worktree') }, async () => {+ const result = await assessBackupRepository(root, 'source_repo', 'source-id', now, { remaining: 1 });+ expect(result.verification).toMatchObject({ state: 'verified', local_commit: head, remote_commit: head });+ expect(result.state).toBe('ok');+ });+}, 15_000);