Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.27.0 fix(autopilot): daemon wrapper sources a gbrain-owned env file, warns on missing chat credentials (#2608) (#4471)
Garry Tan975886a399fb
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex bc16c78778..85021f455b 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.26.0",+ "version": "0.46.27.0","description": "Personal knowledge brain for your coding agent — 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 b800c64667..17079479b4 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.26.0",+ "version": "0.46.27.0","description": "Personal knowledge brain for your coding agent — 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 974e848f85..64976fae6d 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.26.0 -->+<!-- gbrain-runbook-stamp: 0.46.27.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 9f0f262f43..3d8ac5c39e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,48 @@All notable changes to GBrain will be documented in this file.+## [0.46.27.0] - 2026-08-21++**The autopilot daemon can no longer lose your API keys silently.** The+failure mode: `autopilot --install` generated a wrapper that loaded env only+from interactive shell rc files, which daemon supervisors (launchd, systemd,+cron) never run — so the daemon started green while every LLM phase+(chronicle, dream, enrich) quietly produced nothing, for days, with no error+anywhere. This release adopts the env-file fix from PR #4443 (thank you+@Masashi-Ono0611) and hardens the whole lane. Closes #2608.++### Added+- The daemon wrapper now sources a gbrain-owned `~/.gbrain/env` file (after+ your shell profiles, so it wins on conflicts; honors `GBRAIN_HOME`).+ `autopilot --install` creates it as a fully-commented, owner-only (0600)+ template — API keys plus the process-level env only a wrapper can deliver+ (`NODE_EXTRA_CA_CERTS`, proxy vars, custom base URLs). gbrain never+ overwrites or deletes it; a pre-existing group/world-readable file gets one+ warning and is left untouched.+- Autopilot prints one loud line at boot when no chat provider is available,+ naming both remediation paths and the reload step — the silent no-op is now+ visible in `autopilot.log` at startup instead of surfacing as "runs green,+ extracts nothing."++### Fixed+- `autopilot --install` now actually reloads a running daemon: launchd+ unloads before loading (a bare `launchctl load` over a loaded agent also+ errored and aborted every reinstall), systemd restarts an already-active+ unit, and the cron/container paths tell you when a running loop keeps its+ old environment and exactly how to end it.+- Env files with plain `KEY=value` lines (no `export`) now reach the daemon —+ the wrapper sources under `set -a`, matching how dedicated env files are+ usually written.++To take advantage of v0.46.27.0:+- Existing daemon installs: re-run `gbrain autopilot --install` once. The+ upgrade alone swaps the binary but does not regenerate the wrapper, so the+ env-file sourcing (and the template) only appear after a reinstall — which+ now also reloads the daemon for you on launchd and systemd.+- Then put your keys in `~/.gbrain/env` (or keep them in+ `~/.gbrain/config.json`); the wrapper sources the env file on every daemon+ start.+## [0.46.26.0] - 2026-08-20**Dream fan-out can no longer strand work in queues nobody owns.** Thediff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex bd04d296f4..d27aca6538 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -78,7 +78,12 @@ export ANTHROPIC_API_KEY=sk-ant-... # automatic fact extraction + chat models;Save to shell profile or `.env`, or store in `~/.gbrain/config.json` (file plane). DoNOT use `gbrain config set` for API keys — it writes the DB plane, which the provider-pipeline never reads. Without any embedding provider, keyword search still works.+pipeline never reads. For the autopilot daemon, put keys AND process-level env+(`NODE_EXTRA_CA_CERTS`, proxy vars, custom base URLs) in `~/.gbrain/env` — a 0600+file created by `gbrain autopilot --install` and sourced by the daemon wrapper;+interactive shell rc files never reach daemon shells, and the path honors+`GBRAIN_HOME`. Re-run `gbrain autopilot --install` after editing it so the daemon+reloads. Without any embedding provider, keyword search still works.Chat-shaped features (automatic fact extraction, enrichment, synthesis, queryexpansion) route to whichever supported chat key is present (Anthropic or OpenAI) —Anthropic when both are set, OpenAI when it is the only one; other chat providersdiff --git a/TODOS.md b/TODOS.mdindex 50d88a29ed..4aa5b7d741 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,55 @@# TODOS+## Daemon env-file lane follow-ups (#2608 / #4443 takeover, filed 2026-08-21)++- [ ] **P3 — Fix the stale `config set` DB-plane claim in the install docs.**+ **What:** `INSTALL_FOR_AGENTS.md` and `docs/INSTALL.md` say `gbrain config set`+ "writes the DB plane, which the provider pipeline never reads" — but+ `src/commands/config.ts` (FILE_PLANE_API_KEYS, ~line 259) routes API keys to+ the file plane (routed, not refused), which `mergedProviderEnv` folds.+ **Why:** the docs teach a prohibition whose stated rationale is no longer+ true; either document the routing or remove the scare. **Where to start:**+ `src/commands/config.ts` FILE_PLANE_API_KEYS; both install docs; regen+ `bun run build:llms`. **Effort:** S.++- [ ] **P3 — Refresh file-plane keys in the autopilot tick.** **What:** call+ `refreshGatewayEnvFromFilePlane()` (`src/core/ai/gateway.ts:~497`, today only+ called from `src/commands/jobs.ts`) from the autopilot tick so a key added to+ `~/.gbrain/config.json` after boot is picked up without a daemon reload.+ **Why:** shrinks the restart-required window the #2608 boot warning documents.+ **Where to start:** autopilot tick body next to the existing health probe.+ **Effort:** S.++- [ ] **P3 — Doctor check for a stale (pre-env-lane) daemon wrapper.** **What:**+ a doctor check that reads `<gbrainDir>/autopilot-run.sh` and warns when it+ lacks the env-file sourcing line (installed before v0.46.2x, binary upgraded,+ wrapper never regenerated). **Why:** self-upgrade swaps the binary but never+ the wrapper; the boot warning covers the no-key case, doctor should cover the+ wrapper-drift case. **Where to start:** `src/commands/doctor.ts` filesystem+ checks; `writeWrapperScript` in `src/commands/autopilot.ts`. **Effort:** S.++- [ ] **P3 — launchd/systemd log paths ignore `GBRAIN_HOME`.** **What:**+ `generateLaunchdPlist` and `generateSystemdUnit` hardcode+ `~/.gbrain/autopilot.{log,err}` (`src/commands/autopilot.ts` plist/unit+ templates) while the wrapper, lock, and env file all resolve through+ `gbrainPath()`. **Why:** on a `GBRAIN_HOME` install the daemon's diagnostics+ land in a different directory than every doc and status command names —+ pre-existing, but the #2608 boot warning is the first feature whose+ remediation depends on users finding autopilot.log. **Where to start:** the+ two generators + `showStatus` log-tail readers. **Effort:** M (migration for+ existing installs).++- [ ] **P3 — In-process env-file fold for foreground/doctor parity.** **What:**+ parse simple `KEY=value` lines of `<gbrainDir>/env` before `configureGateway`+ (`src/cli.ts:~3298`) so foreground runs and doctor see the same keys the+ daemon wrapper sources. **Why:** today an env-file-only key makes doctor+ report keyless while the daemon is keyed — the inverse of #2608's trap.+ Rejected as the PRIMARY fix because process-level vars+ (`NODE_EXTRA_CA_CERTS`) must exist before boot, which only wrapper sourcing+ delivers; a parity fold is additive. **Where to start:** `src/cli.ts`+ connectEngine preamble; reuse the template's grammar (export-optional+ KEY=value). **Effort:** M.+## Serve-delegated sync follow-ups (v0.46.24.0)- [ ] **P3 — `sync --all` under delegation.** **What:** delegate a multi-sourcediff --git a/VERSION b/VERSIONindex 1ad59821fc..4a85c1b17a 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.26.0+0.46.27.0diff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex 0a7ace68f1..f669a371d7 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -63,6 +63,8 @@ chat providers need an explicit `models.*` pin. With neither key, they stay offcalmly and memory comes from agent-authored `## Facts` fences and the`remember` verb.+For the autopilot daemon specifically, keys and process-level env (`NODE_EXTRA_CA_CERTS`, proxy vars, custom base URLs) belong in `~/.gbrain/env` — a 0600 file created by `gbrain autopilot --install` and sourced by the daemon wrapper (interactive shell rc files never reach daemon shells; the path honors `GBRAIN_HOME`). Re-run `gbrain autopilot --install` after editing it so the daemon reloads.+`ZEROENTROPY_API_KEY` is still honored but deprecated — the ZeroEntropy hosted API shuts down 2026-09-04. Off-ramp: the agent playbook at [`skills/migrations/v0.46.3.0.md`](../skills/migrations/v0.46.3.0.md) (one command migrates embeddings + reranker) with the full reference in [`docs/guides/embedding-migration.md`](guides/embedding-migration.md).Common follow-ups:diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 077c6bcc6a..577400bcca 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -297,7 +297,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue regression guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo — the #2194/#2227 mixed-scope fix) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output gains per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's #2849 size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable).v0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes.- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector.+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane (#2608): `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution).- `src/mcp/server.ts` — MCP stdio server (generated from operations). Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. On PGLite brains the resolve-IPC block also registers the serve-delegated sync handlers (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) in their OWN try/catch — a runner failure logs `[serve-sync] handlers unavailable` and the original kinds still start — gated off with `GBRAIN_SERVE_SYNC_IPC=0`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts`.- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the extracted validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface, D7), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock` (D8). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier (amendment 33/D10): true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the amendment-33 honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). New logging paths route through this helper, not `JSON.stringify(params)`.- `src/mcp/validate-params.ts` — param normalization + validation extracted from dispatch (WP3, direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per process — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts.diff --git a/llms-full.txt b/llms-full.txtindex ee1d696296..8731140596 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1138,7 +1138,12 @@ export ANTHROPIC_API_KEY=sk-ant-... # automatic fact extraction + chat models;Save to shell profile or `.env`, or store in `~/.gbrain/config.json` (file plane). DoNOT use `gbrain config set` for API keys — it writes the DB plane, which the provider-pipeline never reads. Without any embedding provider, keyword search still works.+pipeline never reads. For the autopilot daemon, put keys AND process-level env+(`NODE_EXTRA_CA_CERTS`, proxy vars, custom base URLs) in `~/.gbrain/env` — a 0600+file created by `gbrain autopilot --install` and sourced by the daemon wrapper;+interactive shell rc files never reach daemon shells, and the path honors+`GBRAIN_HOME`. Re-run `gbrain autopilot --install` after editing it so the daemon+reloads. Without any embedding provider, keyword search still works.Chat-shaped features (automatic fact extraction, enrichment, synthesis, queryexpansion) route to whichever supported chat key is present (Anthropic or OpenAI) —Anthropic when both are set, OpenAI when it is the only one; other chat providersdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 1175afe45e..ba4afdb4ff 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.26.0",+ "version": "0.46.27.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 34aae501e8..9a7ffbc7fb 100644--- a/package.json+++ b/package.json@@ -170,7 +170,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.26.0",+ "version": "0.46.27.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 f6501a3b9a..1de58ad2da 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.26.0",+ "version": "0.46.27.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 813a72849b..5e259aeb04 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.26.0",+ "version": "0.46.27.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 879c7600f4..b86c708dcd 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.26.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.27.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-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 51188cc4ae..471db7c74e 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.26.0",+ "version": "0.46.27.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 2d4c49dc93..a1cce5ddd6 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.26.0",+ "version": "0.46.27.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 3da15e8872..9bf4407737 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.26.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.27.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/README.md b/plugin/README.mdindex 9412651503..6e4edc201c 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.26.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.27.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/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 082a29db16..568b910bb6 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -16,7 +16,7 @@ src/commands/serve-http.ts 3294 ratchet grown v0.46.25.0 D2: /mcp per-request tesrc/commands/jobs.ts 3093 ratchet grown v0.46.25.0 (--json #3685) + v0.46.26.0: maybeRunWorkerStartupRecovery extraction + stats gating + help textsrc/core/search/hybrid.ts 2703 ratchet grown v0.46.25.0 fix waves: cache scope isolation + pool floor + offset bypass (#3871 #3002)src/core/engine.ts 2415 ratchet grown v0.46.25.0 fix waves: timeline dedup contract + registry write contract (#3827 #1262)-src/commands/autopilot.ts 2356 ratchet grown v0.46.25.0 (#1525 #4300) + v0.46.26.0: GBRAIN_SUPERVISED strip+src/commands/autopilot.ts 2487 ratchet grown: daemon env-file lane + boot warning + reload-safe install (#2608 #4443)src/commands/extract.ts 2066 ratchet lowered: timeline extractor hoisted to core/timeline-extract.ts (module-cycle fix)src/commands/extract-conversation-facts.ts 2045 ratchet grown v0.46.x per-provider gateway-unavailable copysrc/core/import-file.ts 2016 ratchet grown v0.46.24.0 overnight wave: embedding_plane_split named error (#4287)diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 64826d97af..c05bd5a224 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -13,9 +13,12 @@ test/autopilot-auto-drain-wiring.test.ts autopilot auto-drain wiring 8 readFileStest/autopilot-cycle-failure-classification.test.ts autopilot cycle-failure classification — only 'failed' trips the circuit breaker 2 readFileSynctest/autopilot-cycle-failure-classification.test.ts runPhaseOrphans ratio threshold — no more absolute count > 20 3 readFileSynctest/autopilot-fanout-wiring.test.ts autopilot.ts ↔ dispatchPerSource wiring 13 readFileSync+test/autopilot-install.test.ts autopilot install — reload-safety (#2608) 1 readFileSynctest/autopilot-install.test.ts autopilot showStatus — wrapper-path detection 1 readFileSync+test/autopilot-install.test.ts autopilot wiring: chat-unavailable boot warning (#2608) 1 readFileSynctest/autopilot-install.test.ts autopilot wrapper script — bun PATH export (v0.42.x regression) 1 readFileSynctest/autopilot-install.test.ts autopilot wrapper script — env source order (v0.36.1.x #966) 1 readFileSync+test/autopilot-install.test.ts autopilot wrapper script — gbrain-owned env file (#2608) 5 readFileSynctest/autopilot-pause-marker.test.ts pause marker fences minion job pickup 1 readFileSynctest/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressions 4 readFileSynctest/autopilot-shutdown-engine-close.test.ts autopilot.ts graceful engine shutdown (#1872) 6 readFileSyncdiff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 11bc2a4acc..fe40e08ff4 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -521,6 +521,35 @@ export function resolveAutopilotPositionals(args: string[]): string[] {return out;}+/**+ * #2608 — pure function (test seam, same pattern as generateLaunchdPlist):+ * the boot-time warning emitted when no chat provider is available, so the+ * silent no-op of every LLM phase (chronicle, dream, enrich) is visible in+ * the daemon log instead of manifesting as "autopilot runs green but+ * nothing gets extracted".+ *+ * gbrainDir is a param (not resolved here) to keep the function pure AND so+ * both remediation paths honor GBRAIN_HOME — a literal `~/.gbrain` lies on+ * custom-home installs. `gbrain config set` is deliberately NOT named: the+ * canonical key guidance (INSTALL_FOR_AGENTS.md Step 2) tells users not to+ * use it for API keys. The reload instruction is load-bearing: the wrapper+ * sources the env file only at exec and the gateway folds env once+ * pre-dispatch, so a key written after boot changes nothing until+ * `--install` regenerates the wrapper and reloads the daemon.+ */+export function chatBootWarning(chatAvailable: boolean, gbrainDir: string): string | null {+ if (chatAvailable) return null;+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- warning-message hint construction, no fs operation; gbrainDir is configDir()-validated (absolute, no ..), same pattern as import.ts:43+ const envFile = join(gbrainDir, 'env');+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same: log-string construction only+ const configJson = join(gbrainDir, 'config.json');+ return (+ '[autopilot] WARNING: no chat provider available — LLM phases (chronicle, dream, enrich) will no-op. ' ++ `Put an API key (ANTHROPIC_API_KEY or OPENAI_API_KEY) in ${envFile} (sourced by the daemon wrapper) ` ++ `or in ${configJson} (file plane), then re-run \`gbrain autopilot --install\` to reload the daemon.`+ );+}+export async function runAutopilot(engine: BrainEngine, args: string[]) {args = resolveAutopilotPositionals(args);if (args.includes('--help') || args.includes('-h')) {@@ -585,6 +614,24 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {console.log(`Autopilot starting. Repo: ${repoPath}, interval: ${baseInterval}s`);+ // #2608: LLM phases (chronicle extract, dream synthesis, enrich) gate on+ // isAvailable('chat') and silently no-op when no chat provider resolves —+ // the classic symptom of a daemon shell that never sourced the API keys+ // (see writeWrapperScript below). One loud boot-time line makes that+ // failure mode visible in the daemon log instead of manifesting as+ // "autopilot runs green but nothing gets extracted".+ // console.log, NOT console.error: launchd/systemd route stderr to+ // autopilot.err, which install output and showStatus never reference —+ // stdout is the autopilot.log sink on all four install targets.+ // Bare isAvailable('chat') probes the GLOBAL chat model on purpose — it+ // mirrors the phases named above; facts extraction gates model-aware+ // (core/facts/extract.ts) and doctor owns that diagnosis.+ try {+ const { isAvailable } = await import('../core/ai/gateway.ts');+ const warn = chatBootWarning(isAvailable('chat'), gbrainHomePath());+ if (warn) console.log(warn);+ } catch { /* diagnostic only — never blocks the loop */ }+// Mode resolution: Minions dispatch when the user has opted in AND the// worker daemon can actually run (Postgres only; PGLite's exclusive file// lock blocks a separate worker process).@@ -1644,7 +1691,35 @@ rm -f '${q(strikes)}' 2>/dev/null || true`;}-function writeWrapperScript(repoPath: string, target: InstallTarget): string {+/**+ * #2608: contents of the install-time `<gbrainDir>/env` template. All lines+ * commented — the install must never ship a live secret. GBRAIN_HOME is+ * deliberately absent: the wrapper bakes it at install time AFTER sourcing+ * this file, so setting it here would be clobbered (or diverge the daemon's+ * home from the file's own location).+ */+const GBRAIN_ENV_TEMPLATE = `# gbrain daemon environment — sourced by autopilot-run.sh before the daemon+# starts (set -a: plain KEY=value lines are exported too). Created once by+# \`gbrain autopilot --install\`; gbrain never overwrites or deletes it.+# Interactive shell rc files do NOT reach daemon shells — put anything the+# daemon needs here, then re-run \`gbrain autopilot --install\` to reload.+#+# API keys (~/.gbrain/config.json file plane works too):+# export ANTHROPIC_API_KEY=sk-ant-...+# export OPENAI_API_KEY=sk-...+# export VOYAGE_API_KEY=pa-...+#+# Process-level env that must exist before the daemon boots:+# export NODE_EXTRA_CA_CERTS=/path/to/corp-ca.pem+# export HTTPS_PROXY=http://proxy:3128+# export GBRAIN_DATABASE_URL=postgres://...+#+# Do NOT set GBRAIN_HOME here — --install bakes it into the wrapper after+# this file is sourced, so a value here is clobbered or diverges the+# daemon's home from this file's own location.+`;++export function writeWrapperScript(repoPath: string, target: InstallTarget): string {// gbrainHomePath, not raw $HOME: the daemon writes its lock/markers through// it and the status command reads through it, so a GBRAIN_HOME install must// keep its wrapper (and the start-script detection that looks for it) in@@ -1660,6 +1735,25 @@ function writeWrapperScript(repoPath: string, target: InstallTarget): string {const gbrainPath = resolveGbrainCliPath();const safeRepoPath = repoPath.replace(/'/g, "'\\''");const safeGbrainPath = gbrainPath.replace(/'/g, "'\\''");+ // #2608: same gbrain home the daemon itself uses (honors GBRAIN_HOME),+ // baked as an absolute path so the sourcing below never depends on a+ // literal ~/.gbrain guess drifting from a custom install.+ const gbrainEnvFile = join(gbrainDir, 'env');+ const safeGbrainEnvFile = gbrainEnvFile.replace(/'/g, "'\\''");+ // #2608: install-time template so the boot warning points at a file that+ // exists, secret-safe (0600) from birth. Never overwrite — it may hold+ // user secrets — and never chmod a pre-existing file (warn instead). A+ // failed template write must not abort an otherwise-working install+ // (untested by design: dir-permission tricks don't bite under root CI).+ try {+ if (!existsSync(gbrainEnvFile)) {+ writeFileSync(gbrainEnvFile, GBRAIN_ENV_TEMPLATE, { mode: 0o600 });+ } else if ((statSync(gbrainEnvFile).mode & 0o077) !== 0) {+ console.error(`[autopilot] warning: ${gbrainEnvFile} is group/world-readable and may hold API keys — consider: chmod 600 '${safeGbrainEnvFile}'`);+ }+ } catch (e) {+ console.error(`[autopilot] warning: could not create env template at ${gbrainEnvFile}: ${e instanceof Error ? e.message : String(e)}`);+ }// Bake the dir of the bun runtime actually executing this install onto PATH,// so the wrapper finds bun wherever it lives — Homebrew (/opt/homebrew/bin),// npm -g, Docker (/usr/local/bin), a custom BUN_INSTALL, or nix — not just@@ -1680,6 +1774,18 @@ function writeWrapperScript(repoPath: string, target: InstallTarget): string {# OPENAI/ANTHROPIC keys exported in zshenv reach autopilot.[ -f ~/.zshenv ] && source ~/.zshenv 2>/dev/nullsource ~/.zshrc 2>/dev/null || source ~/.bashrc 2>/dev/null || true+# gbrain-owned env file (#2608), additive to the profiles above: daemon+# shells are non-interactive, so exports that live only in an interactive+# rc file never reach them — and the ~/.bashrc guard below means even+# ~/.bashrc-only exports can be lost on a common Linux config. This is the+# deterministic place for API keys AND process-level env the daemon needs+# before boot (NODE_EXTRA_CA_CERTS, proxy vars, GBRAIN_DATABASE_URL) —+# things an in-process config read could never deliver. Created 0600 by+# --install. Sourced AFTER the profiles so it wins on conflicts; a missing+# file is a normal no-op, not an error. set -a exports dotenv-style+# KEY=value lines too — without it a plain assignment never reaches the+# exec'd daemon.+[ -f '${safeGbrainEnvFile}' ] && { set -a; source '${safeGbrainEnvFile}' 2>/dev/null; set +a; }# Belt-and-suspenders PATH fix. ~/.bashrc ships with a non-interactive guard# (\`case $- in *i*) ;; *) return;; esac\`) that exits early when launched from# cron/systemd/launchd — so its PATH exports never reach this subprocess.@@ -1781,6 +1887,12 @@ function installLaunchd(wrapperPath: string, home: string, repoPath: string) {// plist written under an umask-0 parent stays 0666 forever) — so// normalize unconditionally.chmodSync(plistPath(), 0o644);+ // Unload-before-load (same pattern as uninstall): bare `launchctl load`+ // on an already-loaded agent errors and aborted every reinstall — and a+ // running daemon must be relaunched anyway to pick up a regenerated+ // wrapper / env file (#2608: the boot warning tells users to re-run+ // --install to reload; this line is what makes that true on macOS).+ execSync(`launchctl unload "${plistPath()}" 2>/dev/null || true`, { stdio: 'pipe' });execSync(`launchctl load "${plistPath()}"`, { stdio: 'pipe' });console.log(`Installed launchd service: ${autopilotLaunchdLabel()}`);console.log(` Repo: ${repoPath}`);@@ -1897,6 +2009,13 @@ function installSystemd(wrapperPath: string, repoPath: string) {chmodSync(unitPath, 0o644);execSync('systemctl --user daemon-reload', { stdio: 'pipe', timeout: 10_000 });execSync(`systemctl --user enable --now ${AUTOPILOT_SYSTEMD_UNIT}`, { stdio: 'pipe', timeout: 15_000 });+ // enable --now does NOT restart an already-active unit, so a reinstall+ // over a running daemon would keep the old process (and its stale env)+ // alive indefinitely (#2608: the boot warning tells users to re-run+ // --install to reload; this line is what makes that true on systemd).+ // try-restart only bounces a running unit — a fresh install just started+ // above is restarted at worst, never left stopped.+ execSync(`systemctl --user try-restart ${AUTOPILOT_SYSTEMD_UNIT}`, { stdio: 'pipe', timeout: 15_000 });console.log(`Installed systemd user service: ${AUTOPILOT_SYSTEMD_UNIT}`);console.log(` Repo: ${repoPath}`);console.log(' Log: ~/.gbrain/autopilot.log');@@ -1930,6 +2049,11 @@ echo \$! > ~/.gbrain/autopilot.pidconsole.log('Ephemeral container detected (Render / Railway / Fly / Docker).');console.log(`Repo: ${repoPath}`);console.log(`Start script: ${scriptPath}`);+ // Rewriting the start script cannot reload an autopilot already launched+ // from it — that process keeps its old environment until the container+ // restarts. Never auto-kill; say how (#2608, same honesty as the cron path).+ console.log(' An already-running autopilot keeps its old environment until the container');+ console.log(' restarts (or: kill $(cat ~/.gbrain/autopilot.pid), then re-run the start script).');console.log('');console.log('Crontab is unreliable here (wiped on deploy). Add ONE LINE to your');console.log('agent bootstrap to launch autopilot on every start:');@@ -1986,6 +2110,13 @@ function installCrontab(wrapperPath: string, home: string) {const existing = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });if (existing.includes('gbrain autopilot') || existing.includes('autopilot-run.sh')) {console.log('Crontab entry already exists. Remove with: gbrain autopilot --uninstall');+ // The wrapper (and env template) were regenerated above, but cron+ // cannot reload a loop that is already running — it keeps its old+ // environment until it exits. Never auto-kill a user process; tell+ // them exactly how (#2608: makes the boot warning's re-run---install+ // remediation honest on the cron target).+ console.log(` A running autopilot loop keeps its old environment until it exits — end it with: kill $(cat '${autopilotLockPath().replace(/'/g, "'\\''")}')`);+ console.log(' The next cron tick relaunches it with the refreshed wrapper and env file.');return;}// Use a temp file instead of echo pipe to avoid shell escaping issues (#1)diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 22c2156fe6..90aad460f8 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.26.0 -->+<!-- gbrain-template-stamp: 0.46.27.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/autopilot-install.test.ts b/test/autopilot-install.test.tsindex 00d8be9de7..25f4d46f5e 100644--- a/test/autopilot-install.test.ts+++ b/test/autopilot-install.test.ts@@ -15,18 +15,20 @@* - Linux crontab still writes the same every-5-min line.*/-import { describe, test, expect, beforeEach, afterEach } from 'bun:test';+import { describe, test, expect, beforeEach, afterEach, spyOn } from 'bun:test';import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync, statSync } from 'fs';+import { spawnSync } from 'child_process';import { join } from 'path';import { tmpdir } from 'os';-import { detectInstallTarget } from '../src/commands/autopilot.ts';+import { detectInstallTarget, writeWrapperScript, chatBootWarning } from '../src/commands/autopilot.ts';+import { gbrainPath } from '../src/core/config.ts';let tmp: string;const envSnapshot: Record<string, string | undefined> = {};function envKeys() {- return ['HOME', 'RENDER', 'RAILWAY_ENVIRONMENT', 'FLY_APP_NAME', 'OPENCLAW_HOME'] as const;+ return ['HOME', 'GBRAIN_HOME', 'RENDER', 'RAILWAY_ENVIRONMENT', 'FLY_APP_NAME', 'OPENCLAW_HOME'] as const;}beforeEach(() => {@@ -34,6 +36,7 @@ beforeEach(() => {tmp = mkdtempSync(join(tmpdir(), 'gbrain-install-test-'));process.env.HOME = tmp;// Start each test with a clean slate for ephemeral env vars.+ delete process.env.GBRAIN_HOME;delete process.env.RENDER;delete process.env.RAILWAY_ENVIRONMENT;delete process.env.FLY_APP_NAME;@@ -148,3 +151,316 @@ describe('autopilot showStatus — wrapper-path detection', () => {expect(src).toMatch(/crontabIndicatesAutopilotInstall\(crontab\)/);});});++// #2608: the wrapper's ONLY env channel was the shell rc files (zshenv,+// zshrc||bashrc). Non-interactive daemon shells (launchd/systemd/cron) never+// run zshrc-only exports, and the stock Debian ~/.bashrc non-interactive+// guard blocks even the .bashrc fallback — a common config, not a rare one.+// The fix is additive: the wrapper now ALSO sources a gbrain-owned env file+// (same resolved gbrain home the daemon itself uses, so it honors+// GBRAIN_HOME) after the profiles, and silently no-ops when that file is+// absent.+describe('autopilot wrapper script — gbrain-owned env file (#2608)', () => {+ function makeFakeGbrainOnPath(): { binDir: string; restore: () => void } {+ // writeWrapperScript() calls resolveGbrainCliPath(), which shells out to+ // `which gbrain`. Put a harmless shim on PATH so the test is deterministic+ // regardless of whether the CI/dev machine has a real gbrain on PATH.+ const binDir = mkdtempSync(join(tmpdir(), 'gbrain-fake-bin-'));+ writeFileSync(join(binDir, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ const originalPath = process.env.PATH;+ process.env.PATH = `${binDir}:${originalPath ?? ''}`;+ return {+ binDir,+ restore: () => {+ process.env.PATH = originalPath;+ rmSync(binDir, { recursive: true, force: true });+ },+ };+ }++ test('wrapper additively sources <gbrainDir>/env after the rc-file profiles, before PATH export/exec', () => {+ const fakeBin = makeFakeGbrainOnPath();+ try {+ const repoDir = join(tmp, 'repo');+ mkdirSync(repoDir, { recursive: true });+ const wrapperPath = writeWrapperScript(repoDir, 'linux-cron');+ const src = readFileSync(wrapperPath, 'utf8');++ // Ground truth: ask the SAME resolver the production code uses for the+ // gbrain-owned home, rather than hand-assuming ~/.gbrain — this is what+ // makes the assertion honor a GBRAIN_HOME override too.+ const envFilePath = gbrainPath('env');+ // set -a wrap: plain KEY=value lines (no `export`) must reach the+ // exec'd daemon too — bare `source` leaves them unexported.+ expect(src).toContain(`[ -f '${envFilePath}' ] && { set -a; source '${envFilePath}' 2>/dev/null; set +a; }`);++ // Existing rc-file sourcing is UNCHANGED (additive fix, not a+ // replacement) and still runs in the same order: zshenv, then+ // zshrc||bashrc.+ const zshenvIdx = src.indexOf('~/.zshenv');+ const zshrcIdx = src.indexOf('~/.zshrc');+ const bashrcIdx = src.indexOf('~/.bashrc');+ expect(zshenvIdx).toBeGreaterThan(-1);+ expect(zshrcIdx).toBeGreaterThan(zshenvIdx);+ expect(bashrcIdx).toBeGreaterThan(zshrcIdx);++ // New sourcing line runs AFTER the profiles (so it wins on conflicts)+ // and BEFORE the PATH export / exec (so the daemon actually sees it).+ const envFileIdx = src.indexOf(`'${envFilePath}'`);+ const pathExportIdx = src.indexOf('export PATH=');+ const execIdx = src.indexOf("exec '");+ expect(envFileIdx).toBeGreaterThan(bashrcIdx);+ expect(envFileIdx).toBeLessThan(pathExportIdx);+ expect(pathExportIdx).toBeGreaterThan(-1);+ expect(pathExportIdx).toBeLessThan(execIdx);+ } finally {+ fakeBin.restore();+ }+ });++ test('honors GBRAIN_HOME: sources <GBRAIN_HOME>/.gbrain/env, not a hardcoded ~/.gbrain', () => {+ const fakeBin = makeFakeGbrainOnPath();+ const customHome = mkdtempSync(join(tmpdir(), 'gbrain-custom-home-'));+ const originalGbrainHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = customHome;+ try {+ const repoDir = join(tmp, 'repo-custom');+ mkdirSync(repoDir, { recursive: true });+ const wrapperPath = writeWrapperScript(repoDir, 'linux-cron');+ const src = readFileSync(wrapperPath, 'utf8');+ const expectedEnvFile = join(customHome, '.gbrain', 'env');+ expect(src).toContain(`[ -f '${expectedEnvFile}' ] && { set -a; source '${expectedEnvFile}' 2>/dev/null; set +a; }`);+ // Must NOT fall back to a bare ~/.gbrain/env guess that ignores GBRAIN_HOME.+ expect(src).not.toContain(`[ -f '${join(tmp, '.gbrain', 'env')}'`);+ } finally {+ if (originalGbrainHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = originalGbrainHome;+ rmSync(customHome, { recursive: true, force: true });+ fakeBin.restore();+ }+ });++ test('behavior: real bash actually sets the var when the file is present, and no-ops (exit 0, var unset) when absent', () => {+ const fakeBin = makeFakeGbrainOnPath();+ try {+ const repoDir = join(tmp, 'repo-behavior');+ mkdirSync(repoDir, { recursive: true });+ const wrapperPath = writeWrapperScript(repoDir, 'linux-cron');+ const fullSrc = readFileSync(wrapperPath, 'utf8');++ // Execute the REAL generated sourcing preamble (everything up to, but+ // excluding, the final `exec '<gbrain>' autopilot ...` line) so this+ // proves runtime behavior of the actual generated code, not a+ // hand-duplicated copy of it — without launching autopilot for real.+ const execIdx = fullSrc.indexOf("exec '");+ expect(execIdx).toBeGreaterThan(-1);+ const preamble = fullSrc.slice(0, execIdx);++ const envFilePath = gbrainPath('env');+ const runPreamble = () => spawnSync('bash', ['-c', `${preamble}\necho "MARKER=[$GBRAIN_TEST_MARKER_2608]"`], {+ env: { HOME: tmp, PATH: process.env.PATH || '' },+ encoding: 'utf8',+ timeout: 15_000,+ });++ // Absent case: no ~/.gbrain/env yet. Must be a clean no-op — exit 0,+ // marker stays unset (not an error, not a partial/garbled sourcing).+ rmSync(envFilePath, { force: true });+ const absent = runPreamble();+ expect(absent.status).toBe(0);+ expect(absent.stdout).toContain('MARKER=[]');+ expect(absent.stderr).toBe('');++ // Present case: write the gbrain-owned env file with a marker export.+ mkdirSync(gbrainPath(), { recursive: true });+ writeFileSync(envFilePath, 'export GBRAIN_TEST_MARKER_2608=from-envfile\n');+ const present = runPreamble();+ expect(present.status).toBe(0);+ expect(present.stdout).toContain('MARKER=[from-envfile]');++ // Dotenv-style case: a plain KEY=value line (no `export`) must ALSO+ // reach the exec'd daemon — the #2608 reporter's env file is exactly+ // this shape. Only the set -a wrap makes the assignment exported.+ writeFileSync(envFilePath, 'GBRAIN_TEST_MARKER_2608=dotenv-style\n');+ const dotenv = runPreamble();+ expect(dotenv.status).toBe(0);+ expect(dotenv.stdout).toContain('MARKER=[dotenv-style]');+ } finally {+ fakeBin.restore();+ }+ });++ // #2608 hardening: --install writes a fully-commented 0600 template at+ // <gbrainDir>/env so the boot warning points at a file that exists, with+ // secret-safe perms from birth. GBRAIN_HOME (not HOME) scopes these tests:+ // config's homedir() fallback ignores runtime HOME mutation under bun, but+ // GBRAIN_HOME is read at call time — proven by the test above.+ test('install creates a 0600 fully-commented env template (no GBRAIN_HOME example), never overwrites', () => {+ const fakeBin = makeFakeGbrainOnPath();+ const customHome = mkdtempSync(join(tmpdir(), 'gbrain-tpl-home-'));+ const originalGbrainHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = customHome;+ try {+ const repoDir = join(tmp, 'repo-template');+ mkdirSync(repoDir, { recursive: true });+ writeWrapperScript(repoDir, 'linux-cron');++ const envFile = join(customHome, '.gbrain', 'env');+ expect(existsSync(envFile)).toBe(true);+ expect(statSync(envFile).mode & 0o777).toBe(0o600);++ const body = readFileSync(envFile, 'utf8');+ // Every non-empty line is a comment: the install must never ship a+ // live secret or a live assignment.+ for (const line of body.split('\n')) {+ if (line.trim() === '') continue;+ expect(line.startsWith('#')).toBe(true);+ }+ // Names the key lanes and the process-level vars that justify the file.+ expect(body).toContain('ANTHROPIC_API_KEY');+ expect(body).toContain('NODE_EXTRA_CA_CERTS');+ // GBRAIN_HOME must NOT be offered as an example: the wrapper bakes it+ // AFTER sourcing this file, so a value here is clobbered/divergent.+ expect(body).toContain('Do NOT set GBRAIN_HOME here');+ expect(body).not.toMatch(/^#?\s*export GBRAIN_HOME=/m);++ // Reinstall must never overwrite a user's existing env file.+ writeFileSync(envFile, '# user-owned sentinel\nexport USER_KEY=real\n', { mode: 0o600 });+ writeWrapperScript(repoDir, 'linux-cron');+ expect(readFileSync(envFile, 'utf8')).toContain('user-owned sentinel');+ } finally {+ if (originalGbrainHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = originalGbrainHome;+ rmSync(customHome, { recursive: true, force: true });+ fakeBin.restore();+ }+ });++ test('install warns on a loose-permission pre-existing env file but never chmods it', () => {+ const fakeBin = makeFakeGbrainOnPath();+ const customHome = mkdtempSync(join(tmpdir(), 'gbrain-perm-home-'));+ const originalGbrainHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = customHome;+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});+ try {+ const repoDir = join(tmp, 'repo-perms');+ mkdirSync(repoDir, { recursive: true });+ const gbrainDir = join(customHome, '.gbrain');+ mkdirSync(gbrainDir, { recursive: true });+ const envFile = join(gbrainDir, 'env');+ writeFileSync(envFile, 'export USER_KEY=real\n', { mode: 0o644 });++ writeWrapperScript(repoDir, 'linux-cron');++ // File untouched: content AND mode are the user's business.+ expect(readFileSync(envFile, 'utf8')).toContain('USER_KEY=real');+ expect(statSync(envFile).mode & 0o777).toBe(0o644);+ const warned = errSpy.mock.calls.some((c) => String(c[0]).includes('group/world-readable'));+ expect(warned).toBe(true);+ } finally {+ errSpy.mockRestore();+ if (originalGbrainHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = originalGbrainHome;+ rmSync(customHome, { recursive: true, force: true });+ fakeBin.restore();+ }+ });+});++// #2608: chronicle/dream/enrich gate on isAvailable('chat') and silently+// return empty results when it's false — an ordinary-looking success that+// gives the operator zero signal that the daemon has no LLM credentials.+describe('chatBootWarning (#2608)', () => {+ test('returns null when a chat provider is available', () => {+ expect(chatBootWarning(true, '/custom/.gbrain')).toBeNull();+ });++ test('returns a warning naming the failure mode and the fix when unavailable', () => {+ const warn = chatBootWarning(false, '/custom/.gbrain');+ expect(warn).not.toBeNull();+ expect(warn).toContain('[autopilot]');+ expect(warn).toMatch(/no chat provider/i);+ // Names both remediation paths so the operator isn't left guessing —+ // derived from the passed gbrain dir, never a literal ~/.gbrain guess+ // that lies on GBRAIN_HOME installs.+ expect(warn).toContain('/custom/.gbrain/env');+ expect(warn).toContain('/custom/.gbrain/config.json');+ expect(warn).not.toContain('~/.gbrain');+ // `gbrain config set` is banned for API keys by the canonical install+ // docs — the warning must not teach it.+ expect(warn).not.toContain('config set');+ // Load-bearing: the wrapper sources the env file only at exec and the+ // gateway folds env once pre-dispatch — without a reload nothing changes.+ expect(warn).toContain('gbrain autopilot --install');+ });+});++describe('autopilot wiring: chat-unavailable boot warning (#2608)', () => {+ test('runAutopilot checks isAvailable("chat") and logs chatBootWarning before the daemon loop starts', async () => {+ // Same source-shape regression style as the nightly-probe / parser-probe+ // wiring tests in this suite: runAutopilot's daemon loop runs forever and+ // spawns a real engine + worker supervisor, so it isn't practical to+ // drive end-to-end in a unit test. Pin the wiring instead — the warning+ // logic itself is covered by the direct chatBootWarning() tests above.+ const { readFileSync } = await import('fs');+ const src = readFileSync('src/commands/autopilot.ts', 'utf8');++ const startingIdx = src.indexOf('Autopilot starting. Repo:');+ const chatCheckIdx = src.indexOf(`isAvailable('chat')`);+ const loopModeIdx = src.indexOf('Mode resolution: Minions dispatch');+ expect(startingIdx).toBeGreaterThan(-1);+ expect(chatCheckIdx).toBeGreaterThan(startingIdx);+ expect(loopModeIdx).toBeGreaterThan(chatCheckIdx);++ expect(src).toContain('chatBootWarning(isAvailable(');+ // console.log, NOT console.error: launchd/systemd route stderr to+ // autopilot.err, which install output and showStatus never reference —+ // stdout is the autopilot.log sink on all four install targets.+ expect(src).toMatch(/if \(warn\) console\.log\(warn\)/);+ // Diagnostic-only: a gateway import failure must never block the loop.+ expect(src).toMatch(/diagnostic only — never blocks the loop/);+ });+});++// #2608 hardening: the boot warning tells users to re-run --install to+// reload the daemon — these pins keep that instruction TRUE. Source-shape+// style (same rationale as the wiring test above): the install functions+// shell out to launchctl/systemctl/crontab, which a unit test cannot drive.+describe('autopilot install — reload-safety (#2608)', () => {+ test('launchd unloads before load, systemd try-restarts, cron/container explain the residual process', async () => {+ const { readFileSync } = await import('fs');+ const src = readFileSync('src/commands/autopilot.ts', 'utf8');++ // installLaunchd: bare `launchctl load` on an already-loaded agent errors+ // (aborting reinstall) and never relaunches the running daemon. The+ // unload must precede the load INSIDE installLaunchd — anchor on the+ // function body, not the file-wide first occurrence (uninstall also+ // unloads, much later in the file).+ const launchdFnIdx = src.indexOf('function installLaunchd(');+ expect(launchdFnIdx).toBeGreaterThan(-1);+ const launchdBody = src.slice(launchdFnIdx, src.indexOf('function generateSystemdUnit'));+ // Anchor on the execSync calls, not bare command names — the explanatory+ // comment above the unload also says "launchctl load".+ const unloadIdx = launchdBody.indexOf('execSync(`launchctl unload');+ const loadIdx = launchdBody.indexOf('execSync(`launchctl load');+ expect(unloadIdx).toBeGreaterThan(-1);+ expect(loadIdx).toBeGreaterThan(-1);+ expect(unloadIdx).toBeLessThan(loadIdx);++ // installSystemd: enable --now does not restart an active unit; only+ // try-restart bounces a running daemon onto the regenerated wrapper.+ const systemdFnIdx = src.indexOf('function installSystemd(');+ expect(systemdFnIdx).toBeGreaterThan(-1);+ const systemdBody = src.slice(systemdFnIdx, src.indexOf('function installEphemeralContainer'));+ const enableIdx = systemdBody.indexOf('enable --now');+ const tryRestartIdx = systemdBody.indexOf('try-restart');+ expect(enableIdx).toBeGreaterThan(-1);+ expect(tryRestartIdx).toBeGreaterThan(enableIdx);++ // cron + container cannot reload a running loop — install must say so+ // (and how to end it) rather than silently pretending the reinstall+ // took effect.+ expect(src).toMatch(/keeps its old environment until it exits/);+ expect(src).toMatch(/keeps its old environment until the container/);+ });+});