Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-224 W5: boring default install; Phase F never installs autopilot on a brain without one

garrytan555a7fca17b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9bdfa4a6c8..cc4e9b76b0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,25 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A fresh install and an upgrade add nothing you didn't turn on.**
+
+The default install (keyless PGLite, no repo) already started no daemon and installed no service. That is now locked by tests for `gbrain setup claude-code`, `gbrain setup codex` and `gbrain init --pglite --no-embedding`: no process outlives the command, no systemd unit, launchd plist, crontab entry or autopilot script is written, no connector is connected, and self-upgrade stays in `notify` mode.
+
+One upgrade path did install a daemon. On a Postgres brain with `sync.repo_path` set and no autopilot, the v0.11.0 migration's Phase F ran `gbrain autopilot --install`. That migration runs on `apply-migrations --yes`, `post-upgrade` and package postinstall, so a brain that never asked for autopilot could get one. Phase F now installs nothing on a brain without an autopilot: it is skipped (reason `not_installed`), prints the install command and records it, and `gbrain doctor` shows it as a `minions_migration` line until you run it. A brain that already runs autopilot gets it reinstalled as before, and an upgrade still rewrites only a service unit that is already installed.
+
+### For operators
+
+- INSTALL_FOR_AGENTS.md has one **Opt-ins** list (keys and embeddings, autopilot, dream schedule, connectors, auto-upgrade, release channel), one command each, and `gbrain setup <harness>` prints one line pointing to it.
+- To get autopilot on a brain that has none, run the command doctor shows: `gbrain autopilot --install --yes --repo <path>`.
+- `docs/integrations/reliability-repair.md` is linked from llms-full.txt instead of inlined, to stay under the size budget.
+
+### Tests
+
+- `test/boring-default.test.ts`: fresh setup (both harnesses) and init add nothing; `post-upgrade` without the opt-out on repo-less and repo brains installs no unit; an installed unit is the only one rewritten.
+- `test/apply-migrations-safety.serial.test.ts`: Phase F with `sync.repo_path` set and no autopilot installs none (the postinstall argv); with one installed it reinstalls as before.
+
## [0.60.476.0] - 2026-10-27
**Text someone else wrote can no longer add facts to your brain.**
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index d928ddc015..c65efbfcd5 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -582,6 +582,21 @@ only in the due-job list, which runs only when a session starts.
If skipped, minimal defaults are installed automatically.
+## Opt-ins
+
+The default install (keyless PGLite, no repo) adds nothing: no daemon, service
+unit, cron entry, connector or dream schedule, and self-upgrade stays `notify`
+(it reports releases and installs none). An upgrade never installs autopilot on
+a brain without one. Turn each on only when the user asks:
+
+- **Keys and embeddings:** the key (Step 2), then
+ `gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024`.
+- **Autopilot** (Postgres): `gbrain autopilot --install --repo <path>`; PGLite uses `gbrain serve`.
+- **Dream schedule:** cron `0 2 * * * <wrapper> dream` ([wrapper](docs/guides/cron-schedule.md#calling-gbrain-unattended)).
+- **Connectors:** `gbrain connectors auth <provider>` ([guide](docs/guides/chat-connectors.md)).
+- **Auto-upgrade:** `gbrain config set self_upgrade.mode auto`.
+- **Release channel:** `gbrain config set self_upgrade.channel latest` (every release) or `stable`.
+
## Step 7: Recurring Jobs
Optional: skip this entire step for memory-only installs. Ask before scheduling
@@ -625,11 +640,8 @@ timeout of at least 10 s. The wrapper and its rules:
paused), 2 the daemon took itself out of rotation. Filesystem-only, so it
works during DB outages.
- **Auto-update** (daily): `gbrain check-update --json` (tell user, never auto-install).
-- **Dream cycle** (nightly): `gbrain dream` runs the 8-phase overnight maintenance cycle.
- Entity sweep, citation fixes, memory consolidation, plus overnight conversation
- synthesis and cross-session pattern detection. One cron-friendly command. This is what
- is an opt-in maintenance capability. See `docs/guides/cron-schedule.md` for the
- full protocol.
+- **Dream cycle** (nightly): `gbrain dream`, the opt-in maintenance cycle
+ ([Opt-ins](#opt-ins), [protocol](docs/guides/cron-schedule.md)).
- **Weekly**: `gbrain doctor --json && gbrain embed --stale`
## Step 8: Integrations
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 9a6af8e8b5..71b856c900 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending` with `schema_pending`, `database_error` for `--require-db`, `migrations_running` exit 75, `migration_lease_lost` exit 1 with `lease`). #6089: the run never exits 0 with the schema behind (`src/commands/apply-migrations-schema.ts`); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: `assertHeld` raises `MigrationLeaseLostError` (`migration_lease_lost`, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of `migrations_running`; tests `e2e/migration-lease-lost.test.ts`. A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains and a `wedged[]` entry (version, `fix.argv` `--force-retry <v>`) per wedged migration; a run that leaves a wedged migration (3+ consecutive partials) that no newer migration ran past (doctor's forward-progress rule, `forwardProgressPast` in `src/core/migration-ledger.ts`; a superseded wedge is listed as `wedged_superseded` in the plan and is history) never reports up to date: it fails `migrations_pending` reason `wedged` (exit 1, fix `next: ask_user`, verify `--list --json`), so `post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged`; tests `apply-migrations-wedged-6696.test.ts`; every wedged-migration message (run envelope, `--list`, stderr, `gbrain upgrade`) points at the migration's partial rows in this brain's `migrations/completed.jsonl` (`phases[].detail`, if present) through `wedgedLedgerHint` (`src/core/migration-ledger.ts`); a phase's `argv` prints as its next step. v0.11.0 Phase F (`src/commands/migrations/v0_11_0-install.ts`) installs the autopilot only for the brain's `sync.repo_path`; without one it installs nothing, is `skipped` with the exact install command (the default source's `local_path`, else `<REPO_PATH>`), records an `autopilot-install-needs-repo` pending host-work item, and the migration completes; doctor's `minions_migration` line (`src/commands/doctor/checks/autopilot-install-pending.ts`) carries that argv (`persistent_install`) until an autopilot is installed for this brain. Phase F records a `reason` code on those outcomes (`no_repo_path`, `autopilot_already_installed`, `install_failed`). `clearRepoPathWedge` writes a `retry` marker (reason `phase_f_no_repo_path`) before the plan when every partial behind a v0.11.0 wedge failed only the install phase (whatever its detail; the old child's stderr was never captured) and this Postgres brain's `sync.repo_path` is unset, so Phase F would now skip; with it set, or any other wedge, the `--force-retry` advice stands. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.
+- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Phase F (`v0_11_0-install.ts`) reinstalls only an existing autopilot. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending` with `schema_pending`, `database_error` for `--require-db`, `migrations_running` exit 75, `migration_lease_lost` exit 1 with `lease`). #6089: the run never exits 0 with the schema behind (`src/commands/apply-migrations-schema.ts`); an applied reconcile re-check is not pending work, so with nothing else pending a schema the pre-flight left behind fails before the re-check, and after orchestrators the version is read again. #6028 diagnostic: `assertHeld` raises `MigrationLeaseLostError` (`migration_lease_lost`, details say whether the acquisition token and time still match, never the token) when the conflicting lease row names this pid and host, instead of `migrations_running`; tests `e2e/migration-lease-lost.test.ts`. A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains and a `wedged[]` entry (version, `fix.argv` `--force-retry <v>`) per wedged migration; a run that leaves a wedged migration (3+ consecutive partials) that no newer migration ran past (doctor's forward-progress rule, `forwardProgressPast` in `src/core/migration-ledger.ts`; a superseded wedge is listed as `wedged_superseded` in the plan and is history) never reports up to date: it fails `migrations_pending` reason `wedged` (exit 1, fix `next: ask_user`, verify `--list --json`), so `post-upgrade` exits non-zero and `gbrain upgrade` prints `Migrations: wedged`; tests `apply-migrations-wedged-6696.test.ts`; every wedged-migration message (run envelope, `--list`, stderr, `gbrain upgrade`) points at the migration's partial rows in this brain's `migrations/completed.jsonl` (`phases[].detail`, if present) through `wedgedLedgerHint` (`src/core/migration-ledger.ts`); a phase's `argv` prints as its next step. v0.11.0 Phase F (`src/commands/migrations/v0_11_0-install.ts`) installs the autopilot only for the brain's `sync.repo_path`; without one it installs nothing, is `skipped` with the exact install command (the default source's `local_path`, else `<REPO_PATH>`), records an `autopilot-install-needs-repo` pending host-work item, and the migration completes; doctor's `minions_migration` line (`src/commands/doctor/checks/autopilot-install-pending.ts`) carries that argv (`persistent_install`) until an autopilot is installed for this brain. Phase F records a `reason` code on those outcomes (`no_repo_path`, `autopilot_already_installed`, `install_failed`). `clearRepoPathWedge` writes a `retry` marker (reason `phase_f_no_repo_path`) before the plan when every partial behind a v0.11.0 wedge failed only the install phase (whatever its detail; the old child's stderr was never captured) and this Postgres brain's `sync.repo_path` is unset, so Phase F would now skip; with it set, or any other wedge, the `--force-retry` advice stands. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.
- `src/commands/migrations/run-engine.ts` — one PGLite engine for consecutive migrations of an apply-migrations run (each open starts an embedded Postgres, about 130 ms). `withRunEngineSession` wraps the locked run; `setRunEngineSharing` enables sharing for the opt-out read, each migration flagged `sharesRunEngine` (v0.11.0, v0.14.0, v0.22.4, v0.28.0, v0.53.0) and the post-orchestrator schema check, and disabling it (before an unflagged migration, `--list`, `--dry-run` or a consent prompt) closes the engine. `connectMigrationEngine` returns the shared engine with a no-op close while sharing, otherwise a new engine its caller closes (Postgres always). `releaseRunEngine` closes it before a `gbrain` child that needs the brain (v0.11.0's `jobs smoke`). A fresh setup's migration child opens the brain three times instead of eight (counting the `jobs smoke` child); the ledger it writes is pinned by `test/fixtures/goldens/setup/fresh-setup-migration-ledger.json`. Tests: `test/migrations-run-engine.test.ts`.
- `src/commands/apply-migrations-schema.ts` — #6089 schema half of the apply-migrations exit contract. `connectAtSchemaVersion` connects the configured brain and reads `config.version` (pre-flight, `--force-schema`); the post-orchestrator check opens it through `connectMigrationEngine`. `checkSchemaAfterOrchestrators` re-reads the version after the orchestrators ran: on Postgres only when the pre-flight connected; on PGLite in-process once the orchestrators released the datastore (the pre-flight stays skipped, #1100; never a child process), applying the schema migrations under `--yes`/`--non-interactive`; a busy PGLite datastore is rethrown. `schemaPendingError` builds `migrations_pending` with reason `not_applied` (fix reruns with `--yes`), `still_behind` (after an authorized run) or `schema_unreadable` (both fix `next: report` with `gbrain doctor --json` as verify, never another `--yes`), each naming the pending schema versions. `reportDatabaseUnreachable` keeps an unreachable Postgres non-fatal but prints the `GBRAIN_DB_ACCESS <reason>` marker. Tests: `test/apply-migrations-schema-exit.test.ts` (PGLite, unreachable Postgres, post-upgrade, postinstall) and `test/e2e/apply-migrations-schema-exit.test.ts` (Postgres).
diff --git a/llms-full.txt b/llms-full.txt
index 8bb509c82f..0818ddee39 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -3247,6 +3247,21 @@ only in the due-job list, which runs only when a session starts.
If skipped, minimal defaults are installed automatically.
+## Opt-ins
+
+The default install (keyless PGLite, no repo) adds nothing: no daemon, service
+unit, cron entry, connector or dream schedule, and self-upgrade stays `notify`
+(it reports releases and installs none). An upgrade never installs autopilot on
+a brain without one. Turn each on only when the user asks:
+
+- **Keys and embeddings:** the key (Step 2), then
+ `gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024`.
+- **Autopilot** (Postgres): `gbrain autopilot --install --repo <path>`; PGLite uses `gbrain serve`.
+- **Dream schedule:** cron `0 2 * * * <wrapper> dream` ([wrapper](docs/guides/cron-schedule.md#calling-gbrain-unattended)).
+- **Connectors:** `gbrain connectors auth <provider>` ([guide](docs/guides/chat-connectors.md)).
+- **Auto-upgrade:** `gbrain config set self_upgrade.mode auto`.
+- **Release channel:** `gbrain config set self_upgrade.channel latest` (every release) or `stable`.
+
## Step 7: Recurring Jobs
Optional: skip this entire step for memory-only installs. Ask before scheduling
@@ -3290,11 +3305,8 @@ timeout of at least 10 s. The wrapper and its rules:
paused), 2 the daemon took itself out of rotation. Filesystem-only, so it
works during DB outages.
- **Auto-update** (daily): `gbrain check-update --json` (tell user, never auto-install).
-- **Dream cycle** (nightly): `gbrain dream` runs the 8-phase overnight maintenance cycle.
- Entity sweep, citation fixes, memory consolidation, plus overnight conversation
- synthesis and cross-session pattern detection. One cron-friendly command. This is what
- is an opt-in maintenance capability. See `docs/guides/cron-schedule.md` for the
- full protocol.
+- **Dream cycle** (nightly): `gbrain dream`, the opt-in maintenance cycle
+ ([Opt-ins](#opt-ins), [protocol](docs/guides/cron-schedule.md)).
- **Weekly**: `gbrain doctor --json && gbrain embed --stale`
## Step 8: Integrations
@@ -11140,87 +11152,4 @@ the [CHANGELOG](../../CHANGELOG.md#exit-code-changes-by-command).
---
-## docs/integrations/reliability-repair.md
-
-Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/integrations/reliability-repair.md
-
-# Reliability repair
-
-Two data-corruption classes can affect a brain on real Postgres or Supabase:
-JSONB values stored double-encoded, and markdown bodies truncated at import.
-`gbrain doctor` detects both, and the standalone `gbrain repair-jsonb`
-command fixes the mechanically fixable class. PGLite brains are not affected
-(PGLite parses text to jsonb natively, so the double-encode never happens
-there).
-
-## What the checks look for
-
-**JSONB double-encode.** Writing `${JSON.stringify(x)}::jsonb` through
-postgres.js stores a JSONB *string literal* instead of an object.
-`frontmatter ->> 'key'` returns NULL; GIN indexes are ineffective. Columns
-checked: `pages.frontmatter`, `raw_data.data`, `ingest_log.pages_updated`,
-`files.metadata`. The write-side rule that prevents it is in
-`docs/ENGINES.md` ("JSONB writes: never double-encode").
-
-**Markdown body truncation.** A page whose `compiled_truth` is much shorter
-than its `raw_data.data ->> 'content'` lost body content at import time (for
-example, when a `---` horizontal rule was treated as a body/timeline
-delimiter). Wiki-style pages with multiple `##`/`###` sections are the usual
-casualty.
-
-## Detect
-
-```
-gbrain doctor
-```
-
-Reports two checks:
-
-- `jsonb_integrity` — counts double-encoded rows per table and points you
- at `gbrain repair-jsonb`.
-- `markdown_body_completeness` — heuristic for pages whose `compiled_truth`
- is suspiciously short compared to `raw_data.data ->> 'content'`. A page
- stored in segments has no `compiled_truth` column to compare, so it is not
- checked; the check reports how many with `skipped_segmented: N`.
-
-## Repair
-
-For JSONB (mechanically fixable):
-
-```
-gbrain repair-jsonb
-```
-
-Runs `UPDATE <table> SET <col> = (<col>#>>'{}')::jsonb WHERE jsonb_typeof(<col>) = 'string'`
-across every affected column. Idempotent. Second run reports 0 rows. Use
-`--dry-run` to preview, `--json` for structured output. The `v0_12_2`
-version migration runs this automatically on `gbrain upgrade`.
-
-For truncated markdown bodies (source-dependent): the importer skips a file
-whose content hash has not changed, and trailing whitespace is trimmed before
-hashing, so a re-import needs a real edit to the page body. Make the edit, then
-re-import:
-
-```
-gbrain sync # git-backed brain: commit the edit first
-gbrain sync --working-tree # or import the uncommitted working tree
-gbrain import <brain-root> --fresh # or re-import the root you originally imported;
- # --fresh ignores a resume checkpoint that would skip the path
-```
-
-gbrain cannot recover content that is already lost if you no longer have
-the source markdown file. `gbrain doctor` tells you which pages look short;
-you decide whether to re-import from source or accept the truncation.
-
-## Verify
-
-```
-gbrain doctor
-```
-
-All four `jsonb_integrity` rows should read zero. `markdown_body_completeness`
-should match your expectations for the corpus.
-
----
-
# Migrations
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index e0118e417e..a57a4fb9a6 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -376,6 +376,8 @@ export const SECTIONS: DocSection[] = [
title: "docs/integrations/reliability-repair.md",
description: "Data integrity recovery.",
path: "docs/integrations/reliability-repair.md",
+ // Linked, not inlined: the INSTALL_FOR_AGENTS.md Opt-ins list (GBRA-224 W5) put llms-full.txt over FULL_SIZE_BUDGET.
+ includeInFull: false,
},
],
},
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bfa01bceb3..197501cbad 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)
src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
-src/core/behavior-change-notice.ts 1518 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this row
+src/core/behavior-change-notice.ts 1520 ratchet +2 GBRA-224 W5 upgrade_installs_no_autopilot row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this row
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index c691eed4bc..1d560ab32d 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -40,6 +40,7 @@ test/bootstrap-contract.test.ts bootstrap same-turn write-back contract 6 readFi
test/bootstrap-opencode-door.serial.test.ts opencode door — rendered AGENTS.md pull protocol 1 readFileSync
test/bootstrap-render.test.ts renderWorkspace — OpenClaw host keeps its schedule list out of HEARTBEAT.md (#7470) 6 readFileSync
test/bootstrap-shared-skills.test.ts (file-level) 19 readFileSync
+test/boring-default.test.ts the default install adds nothing (GBRA-224 W5) 3 readFileSync
test/brain-durability-hook.serial.test.ts #4682 — push-lock timeout is fail-loud for the helper only 1 readFileSync
test/brain-durability-hook.serial.test.ts brain-commit-push.sh (D13 guarantee) 4 readFileSync
test/brain-durability-hook.serial.test.ts durability push remote confirmation (#5138) 9 readFileSync
diff --git a/skills/migrations/v0.11.0.md b/skills/migrations/v0.11.0.md
index df2af8caac..1b49addcba 100644
--- a/skills/migrations/v0.11.0.md
+++ b/skills/migrations/v0.11.0.md
@@ -169,11 +169,11 @@ automatically (it dedupes on file path, so no duplicate rows).
## `type: autopilot-install-needs-repo`
-The upgrade skipped the autopilot install (Phase F) because the brain has
-no `sync.repo_path`: an upgrade installs no new background daemon on a
-guess. The row's `install_argv` is the exact command; `repo` is the
-default source's `local_path`, or null when the brain names no repo at
-all (the argv then carries `<REPO_PATH>`; ask the user for the brain
+The upgrade skipped the autopilot install (Phase F): an upgrade installs no
+daemon on a brain that has none, and reinstalls only one already installed
+for a set `sync.repo_path`. The row's `install_argv` is the exact command;
+`repo` is `sync.repo_path`, else the default source's `local_path`, or null
+when the brain names no repo at all (the argv then carries `<REPO_PATH>`; ask the user for the brain
repo's path). Installing a daemon is a persistent install, so ask the user
before you run it. `gbrain doctor` shows the same command as a
`minions_migration` line until an autopilot is installed for this brain;
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index d6f73e4d80..e8e6368b2a 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -105,7 +105,7 @@
"migrate/SKILL.md": "ab7d7874bdd6cf1ef34538c2888b93b0a416f49bf04bd608dc5eccf9af9a5936",
"migrations/.gitkeep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"migrations/v0.10.3.md": "1e12db6fdb88d21df479659e236bad111a041a205d47aa0894afde2f04903124",
- "migrations/v0.11.0.md": "2a45f374a24a19c90416745e97e21e48148c1c45ace9b59e1f2beef27da49786",
+ "migrations/v0.11.0.md": "308836b12faf0d5397315bb13d4c03087f0b605c347d9ef218f2ff9b82d47332",
"migrations/v0.12.0.md": "f30b452caed5ce2679cbd60dc2d0b9e60449bab20c3a3e0c895e6cd167644f44",
"migrations/v0.12.1.md": "a461d8fcd6b19dabe3a0ce849a54e3c577667ae2af41870c6f456c6195e76064",
"migrations/v0.13.0.md": "9725da5d889b488de14c312fadaa81800e5167e0ecf6adc5a083d721a329e5ba",
diff --git a/src/commands/doctor/checks/autopilot-install-pending.ts b/src/commands/doctor/checks/autopilot-install-pending.ts
index 002144bf8e..5e992b78e2 100644
--- a/src/commands/doctor/checks/autopilot-install-pending.ts
+++ b/src/commands/doctor/checks/autopilot-install-pending.ts
@@ -1,6 +1,6 @@
/**
* `minions_migration` line for a v0.11.0 Phase F the upgrade skipped because
- * the brain names no repo (#6755). Reads the pending host-work item Phase F
+ * the brain names no repo (#6755) or has no autopilot installed (GBRA-224 W5). Reads the pending host-work item Phase F
* recorded and this brain's installed autopilot job (job files, crontab); no
* engine. Quiet once an autopilot is installed for this brain.
*/
@@ -17,7 +17,7 @@ export function autopilotInstallPendingCheck(): Check | null {
return {
name: 'minions_migration',
status: 'warn',
- message: `No autopilot is installed: the v0.11.0 upgrade skipped its install because sync.repo_path is unset. Install it: ${autopilotInstallCommand(todo.repo)}`,
+ message: `No autopilot is installed: the v0.11.0 upgrade installs none (background maintenance is opt-in). Install it: ${autopilotInstallCommand(todo.repo)}`,
fix: agentFix(todo.install_argv,
'Installs the background maintenance daemon (sync, extract, embed) for this brain repo under the host supervisor; a persistent install, so ask the user first.',
'minions_migration', { consent: ['persistent_install'], ...(inputs ? { inputs } : {}) }),
diff --git a/src/commands/migrations/v0_11_0-install.ts b/src/commands/migrations/v0_11_0-install.ts
index d505881f7d..7a6ac80dc5 100644
--- a/src/commands/migrations/v0_11_0-install.ts
+++ b/src/commands/migrations/v0_11_0-install.ts
@@ -2,13 +2,13 @@
* v0.11.0 Phase F: the autopilot install, and an upgrade on a brain that names
* no repo (#6755).
*
- * Phase F installs the daemon only for the repo the brain names in
- * sync.repo_path, the same one `gbrain autopilot --install` resolves first.
- * Without it the phase installs nothing during an upgrade: it is skipped with
- * the exact install command (the default source's local_path when there is
- * one), a pending host-work item records that command, and doctor's
- * `minions_migration` line carries it until an autopilot is installed for
- * this brain. The migration completes instead of ending partial.
+ * An upgrade never installs autopilot on a brain that has none (GBRA-224 W5):
+ * Phase F only reinstalls an autopilot already installed for this brain, for
+ * the repo it names in sync.repo_path. Otherwise the phase installs nothing:
+ * it is skipped with the exact install command (sync.repo_path, else the
+ * default source's local_path), a pending host-work item records that command,
+ * and doctor's `minions_migration` line carries it until an autopilot is
+ * installed for this brain. The migration completes instead of ending partial.
*
* The old Phase F ran the install anyway and wedged such brains after three
* partials. Its ledger rows cannot say why the install failed (the child's
@@ -16,7 +16,7 @@
* `Command failed: <command>`), so `clearRepoPathWedge` keys on the shape
* and the brain as it is now: every trailing partial failed only the install
* phase, and the new phase would skip because sync.repo_path is unset. Phase F
- * now records a `reason` code on its outcomes (`no_repo_path`,
+ * now records a `reason` code on its outcomes (`no_repo_path`, `not_installed`,
* `autopilot_already_installed`, `install_failed`) for later readers.
*/
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'fs';
@@ -71,7 +71,7 @@ export function pendingAutopilotInstall(): AutopilotInstallTodo | null {
}
/** Record the skipped install as a pending host-work item, once per install command. */
-export function recordSkippedAutopilotInstall(repo: string | null): void {
+export function recordSkippedAutopilotInstall(repo: string | null, why = 'sync.repo_path is unset'): void {
const argv = autopilotInstallArgv(repo);
if (pendingAutopilotInstall()?.install_argv.join('\0') === argv.join('\0')) return;
const todo: AutopilotInstallTodo = {
@@ -81,7 +81,7 @@ export function recordSkippedAutopilotInstall(repo: string | null): void {
repo,
install_argv: argv,
recommendation: repo
- ? `The upgrade installed no autopilot because sync.repo_path is unset. Install it for this brain's repo: ${autopilotInstallCommand(repo)}`
+ ? `The upgrade installed no autopilot because ${why}. Install it for this brain's repo: ${autopilotInstallCommand(repo)}`
: `The upgrade installed no autopilot because the brain names no repo (no sync.repo_path, no default source path). Install it with the brain repo's path: ${autopilotInstallCommand(null)}`,
};
mkdirSync(dirname(pendingHostWorkPath()), { recursive: true });
@@ -118,6 +118,18 @@ function skipWithoutRepo(defaultSourcePath: string | null): OrchestratorPhaseRes
};
}
+function skipNotInstalled(repo: string | null): OrchestratorPhaseResult {
+ const why = 'no autopilot is installed for this brain, and an upgrade never installs one';
+ recordSkippedAutopilotInstall(repo, why);
+ const command = autopilotInstallCommand(repo);
+ console.log(`No autopilot was installed: ${why}. Install it when you want background maintenance: ${command} `
+ + `(recorded in ${pendingHostWorkPath()}; gbrain doctor shows it until an autopilot is installed)`);
+ return {
+ name: 'install', status: 'skipped', reason: 'not_installed', detail: `${why}. Install it: ${command}`,
+ ...(repo ? { argv: autopilotInstallArgv(repo) } : {}),
+ };
+}
+
export async function phaseFInstall(opts: OrchestratorOpts): Promise<OrchestratorPhaseResult> {
if (opts.dryRun) return { name: 'install', status: 'skipped', detail: 'dry-run' };
if (opts.noAutopilotInstall) return { name: 'install', status: 'skipped', detail: '--no-autopilot-install' };
@@ -127,13 +139,16 @@ export async function phaseFInstall(opts: OrchestratorOpts): Promise<Orchestrato
if (config?.engine === 'pglite') {
return { name: 'install', status: 'skipped', detail: 'PGLite is single-writer; use gbrain serve for background maintenance' };
}
+ let repoPath: string | null = null;
try {
const repo = await readRepoPaths(config);
if (!repo.syncRepoPath) return skipWithoutRepo(repo.defaultSourcePath);
- repoNote = `sync.repo_path ${repo.syncRepoPath}`;
+ repoPath = repo.syncRepoPath;
+ repoNote = `sync.repo_path ${repoPath}`;
} catch (e) {
repoNote = `repo path unreadable (${e instanceof Error ? e.message : String(e)}); the install resolves it itself`;
}
+ if (!autopilotInstalledForBrain()) return skipNotInstalled(repoPath);
execSync(gbrainChildCommand('gbrain autopilot --install --yes'), { stdio: cliChildStdio(), timeout: 60_000, env: process.env });
return { name: 'install', status: 'complete' };
} catch (e) {
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 43cf61a904..6add9e43cc 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -24,7 +24,7 @@
*/
import { realpathSync } from 'node:fs';
import { opError, OperationError } from '../core/ops/contract.ts';
-import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
+import { cliRenderContext, docsUrl, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
import { writeCliNotices } from '../core/interop-notices.ts';
import { setupFirstRunNotices } from './init-first-run.ts';
import { hostedOptionMuted, hostedOptionNotice, writeHostedOption } from '../core/onboard/hosted-option.ts';
@@ -617,6 +617,7 @@ async function finish(out: Out, doc: {
: 'Next: open a new Claude Code session (config is read at session start) and check that /mcp lists gbrain.');
if (state && !doc.remove) say(out, 'Memory: save what the user asks you to remember as a fact with gbrain remember "<fact>", naming its entity and provenance (MCP tool: remember). '
+ 'World-visible facts (the default) are pushed into new sessions; a private fact is not (local CLI recall only). capture writes a page, not a fact.');
+ if (state && !doc.remove) say(out, `Opt-ins (nothing is on until you turn it on): keys and embeddings, autopilot, dream schedule, connectors, auto-upgrade, release channel: ${docsUrl('INSTALL_FOR_AGENTS.md#opt-ins')}`);
writeCliNotices(doc.notices.filter((n) => n.code !== 'hosted_option'));
if (doc.notices.some((n) => n.code === 'hosted_option')) writeHostedOption('setup', new Set());
return 0;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 59b8c1aa07..2832c5836a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1320,6 +1320,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.471.0', id: 'door_planned_state', text: 'On a source with `canonical: git`, a page write now commits exactly the bytes it published, or nothing. A file edited on disk while the write was publishing refuses `git_target_changed`: nothing is committed, the edit stays on disk and the source\'s writes pause until `gbrain repair stuck-recovery` resolves it (before, Git committed the edit while the database recorded the write\'s content). A staged change of the page\'s file refuses `git_index_conflict`, with the index untouched; commit or unstage it, then retry (before, the write replaced the staged change in the index). When the index still holds the version from before an earlier gbrain commit whose index update failed, the next write restores it and says so with a `git_index_restored` notice.' },
// #7679 / #7685 orphaned worktree refresh. `since` is stamped at the merge slot.
{ since: '0.60.472.0', id: 'refresh_orphan_7679', text: 'A managed `gbrain sources refresh` whose process died (for example a container replaced mid-refresh) no longer wedges the checkout: the next plain `gbrain sources refresh` on the owner host finishes the orphaned refresh through the `--resume` path before its own refresh and reports it as `recovered`, and the owner completes an orphaned `syncing` refresh once every member has synced to its target. A refresh whose holder is still running, or is recorded on another host, is never taken over. `gbrain sources writer status` and `gbrain sync status` now name the holder and its `liveness` (`live`, `orphaned`, `unknown`) with a fix naming `--resume`. With `--json`, a refusal that carries a structured fix (`refresh_in_progress`, `refresh_diverged`, a git read failure) now prints `fix` as an object (argv, actor, next) instead of a string; the prose stays in `suggestion`, so read that when a script needs text. A plain refresh of a checkout whose interrupted refresh needs a reset decision now refuses `refresh_recovery_required` (it refused `refresh_in_progress`).' },
+ // GBRA-224 W5 (an upgrade installs no autopilot). `since` is stamped at the merge slot.
+ { since: 'TBD', id: 'upgrade_installs_no_autopilot', text: 'An upgrade no longer installs autopilot on a Postgres brain that has none, even with sync.repo_path set: the v0.11.0 migration\'s Phase F is skipped (reason not_installed), prints the install command and records it, and `gbrain doctor` shows it as a minions_migration line until you run it. An autopilot already installed for the brain is reinstalled as before.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/test/apply-migrations-safety.serial.test.ts b/test/apply-migrations-safety.serial.test.ts
index b8fd014f08..e55435b908 100644
--- a/test/apply-migrations-safety.serial.test.ts
+++ b/test/apply-migrations-safety.serial.test.ts
@@ -21,6 +21,13 @@ async function fixture(run: (home: string, ledger: string) => Promise<void>): Pr
}
}
+/** A systemd user unit for this brain's autopilot, as `gbrain autopilot --install` writes it; HOME and GBRAIN_HOME are both `home`. */
+function installedAutopilotUnit(home: string): void {
+ const unitDir = join(home, '.config/systemd/user');
+ mkdirSync(unitDir, { recursive: true });
+ writeFileSync(join(unitDir, 'gbrain-autopilot.service'), `[Unit]\nDescription=GBrain Autopilot\n[Service]\nExecStart=${join(home, '.gbrain', 'autopilot-run.sh')}\nRestart=always\n`);
+}
+
function entries(ledger: string): CompletedMigrationEntry[] {
return readFileSync(ledger, 'utf8').trim().split('\n').map(row => JSON.parse(row));
}
@@ -105,6 +112,7 @@ await runApplyMigrations(['--yes']);
test.each(['file-postgres', 'env-overrides-pglite'])('failed applicable install retries in %s, while a historical complete requires explicit force-retry', async (context) => {
await fixture(async (home, ledger) => {
+ installedAutopilotUnit(home);
const databaseUrl = 'postgresql://fixture:[email protected]:1/gbrain_test';
if (context === 'file-postgres') {
writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify({ engine: 'postgres', database_url: databaseUrl }));
@@ -259,7 +267,7 @@ describe('v0.11.0 Phase F without a repo path (#6755)', () => {
{ name: 'install', status: 'failed', detail: installDetail }, { name: 'record', status: 'complete' },
];
- async function postgresBrain(brain: { syncRepoPath?: string; defaultSourcePath?: string; autopilotExit?: number }, run: (h: {
+ async function postgresBrain(brain: { syncRepoPath?: string; defaultSourcePath?: string; autopilotExit?: number; autopilotInstalled?: boolean }, run: (h: {
home: string; ledger: string; calls: () => string; apply: (args: string[]) => { exitCode: number | null; stdout: string; stderr: string };
script: (body: string) => { exitCode: number | null; stdout: string; stderr: string };
}) => Promise<void>): Promise<void> {
@@ -270,6 +278,7 @@ describe('v0.11.0 Phase F without a repo path (#6755)', () => {
const callsPath = join(home, 'calls.log');
writeFileSync(callsPath, '');
writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${callsPath}'\nif [ "$1" = autopilot ]; then exit ${brain.autopilotExit ?? 0}; fi\nexit 0\n`, { mode: 0o755 });
+ if (brain.autopilotInstalled) installedAutopilotUnit(home);
const env: Record<string, string> = { HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH ?? ''}` };
const setup = `
import { mock } from 'bun:test';
@@ -376,8 +385,23 @@ console.log('CHECK=' + JSON.stringify(autopilotInstallPendingCheck()));
});
}, 60_000);
- test('sync.repo_path set: Phase F installs as before', async () => {
- await postgresBrain({ syncRepoPath: '/srv/brain' }, async ({ home, ledger, calls, apply }) => {
+ test('sync.repo_path set and no autopilot installed: an upgrade installs none, completes, and records the install command', async () => {
+ await postgresBrain({ syncRepoPath: '/srv/brain' }, async ({ home, ledger, calls, apply, script }) => {
+ const run = apply(['--yes', '--non-interactive', '--migration', '0.11.0']);
+ expect(run.exitCode, run.stderr).toBe(0);
+ expect(calls()).not.toContain('autopilot');
+ expect(existsSync(join(home, '.config/systemd/user/gbrain-autopilot.service'))).toBe(false);
+ const record = entries(ledger).at(-1)!;
+ expect(record).toMatchObject({ version: '0.11.0', status: 'complete', autopilot_installed: false });
+ expect(record.phases!.find(phase => phase.name === 'install')).toMatchObject({ status: 'skipped', reason: 'not_installed' });
+ expect(run.stdout).toContain('gbrain autopilot --install --yes --repo /srv/brain');
+ expect(pendingInstallItems(home)[0].install_argv).toEqual(['gbrain', 'autopilot', '--install', '--yes', '--repo', '/srv/brain']);
+ expect(doctorLine(script).fix.argv).toEqual(['gbrain', 'autopilot', '--install', '--yes', '--repo', '/srv/brain']);
+ });
+ }, 60_000);
+
+ test('sync.repo_path set and an autopilot already installed for this brain: Phase F reinstalls it as before', async () => {
+ await postgresBrain({ syncRepoPath: '/srv/brain', autopilotInstalled: true }, async ({ home, ledger, calls, apply }) => {
const run = apply(['--yes', '--migration', '0.11.0']);
expect(run.exitCode, run.stderr).toBe(0);
expect(calls()).toContain('autopilot --install --yes');
@@ -387,7 +411,7 @@ console.log('CHECK=' + JSON.stringify(autopilotInstallPendingCheck()));
}, 60_000);
test('a failing install with sync.repo_path set records reason install_failed', async () => {
- await postgresBrain({ syncRepoPath: '/srv/brain', autopilotExit: 1 }, async ({ ledger, apply }) => {
+ await postgresBrain({ syncRepoPath: '/srv/brain', autopilotExit: 1, autopilotInstalled: true }, async ({ ledger, apply }) => {
const run = apply(['--yes', '--migration', '0.11.0']);
expect(run.exitCode).toBe(1);
expect(entries(ledger).at(-1)!.phases).toContainEqual(expect.objectContaining({ name: 'install', status: 'failed', reason: 'install_failed' }));
diff --git a/test/boring-default.test.ts b/test/boring-default.test.ts
new file mode 100644
index 0000000000..d9185cf522
--- /dev/null
+++ b/test/boring-default.test.ts
@@ -0,0 +1,139 @@
+/**
+ * GBRA-224 W5: the default install adds nothing. A fresh `gbrain setup
+ * claude-code`, `gbrain setup codex` or `gbrain init --pglite --no-embedding`
+ * (keyless, PGLite, no repo) starts no process that outlives it, calls no
+ * service manager, writes no systemd unit, launchd plist, crontab entry or
+ * autopilot start script, connects no connector, and leaves self-upgrade in
+ * notify mode. An upgrade (`gbrain post-upgrade` without the opt-out, the
+ * path `gbrain upgrade` takes) on a brain that never had autopilot installs
+ * none, repo-less or with a repo; it only rewrites a unit that is already
+ * installed. Postgres brains (where Phase F can install) are covered in
+ * apply-migrations-safety.serial.test.ts, with the postinstall argv.
+ *
+ * systemctl, launchctl and crontab are PATH shims that log every call, so a
+ * daemon install or a crontab write shows up even where the real tool is
+ * missing.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { runCli, type CliResult } from './helpers/cli-spawn.ts';
+
+const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+interface Box { root: string; home: string; bin: string; launcher: string; log: string }
+
+function box(): Box {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-boring-default-'));
+ roots.push(root);
+ const home = join(root, 'home');
+ const bin = join(root, 'bin');
+ mkdirSync(home, { recursive: true });
+ mkdirSync(bin);
+ const log = join(root, 'supervisor-calls.log');
+ for (const tool of ['systemctl', 'launchctl', 'crontab']) {
+ writeFileSync(join(bin, tool), `#!/bin/sh\necho "${tool} $*" >> '${log}'\n`);
+ chmodSync(join(bin, tool), 0o755);
+ }
+ const launcher = join(bin, 'gbrain');
+ writeFileSync(launcher, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);
+ chmodSync(launcher, 0o755);
+ return { root, home, bin, launcher, log };
+}
+
+const CLEAN = {
+ CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, GBRAIN_HOOKS: undefined,
+ GBRAIN_NO_AUTOPILOT_INSTALL: undefined, GBRAIN_RELEASE_CHANNEL: undefined,
+};
+
+function gbrain(b: Box, args: string[]): Promise<CliResult> {
+ return runCli(args, { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home, PATH: `${b.bin}:${process.env.PATH ?? ''}` }, timeoutMs: 180_000 });
+}
+
+function liveProcesses(b: Box): string[] {
+ const ps = execFileSync('ps', ['-eo', 'pid=,args='], { encoding: 'utf8' });
+ return ps.split('\n').filter(line => line.includes(b.root) && !line.includes('ps -eo'));
+}
+
+async function expectNothingAdded(b: Box): Promise<void> {
+ expect(existsSync(b.log) ? readFileSync(b.log, 'utf8') : '').toBe('');
+ for (const dir of ['.config/systemd', 'Library/LaunchAgents']) expect(existsSync(join(b.home, dir))).toBe(false);
+ expect(readdirSync(join(b.home, '.gbrain')).filter(name => /autopilot|start-.*\.sh$/.test(name))).toEqual([]);
+ expect(liveProcesses(b)).toEqual([]);
+ const config = JSON.parse(readFileSync(join(b.home, '.gbrain', 'config.json'), 'utf8'));
+ expect(config.self_upgrade.mode).toBe('notify');
+ expect(config.self_upgrade.channel).toBeUndefined();
+ const status = await gbrain(b, ['connectors', 'status', '--json']);
+ expect(status.exitCode, status.stderr).toBe(0);
+ const providers = JSON.parse(status.stdout).providers as Array<{ provider: string; auto_sync: boolean; credential_present: boolean }>;
+ expect(providers.length).toBeGreaterThan(0);
+ expect(providers.filter(p => p.auto_sync || p.credential_present)).toEqual([]);
+}
+
+describe('the default install adds nothing (GBRA-224 W5)', () => {
+ for (const harness of ['claude-code', 'codex'] as const) {
+ test(`fresh \`gbrain setup ${harness}\` on a repo-less keyless brain starts and installs nothing`, async () => {
+ const b = box();
+ const r = await runCli(['setup', harness, '--gbrain-bin', b.launcher, '--json'],
+ { env: { ...CLEAN, HOME: b.home, GBRAIN_HOME: b.home, PATH: `${b.bin}:${process.env.PATH ?? ''}` }, timeoutMs: 180_000 });
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(JSON.parse(r.stdout).target.brain.kind).toBe('new-local-pglite');
+ await expectNothingAdded(b);
+ }, 240_000);
+ }
+
+ test('`gbrain init --pglite --no-embedding` starts and installs nothing', async () => {
+ const b = box();
+ const r = await gbrain(b, ['init', '--pglite', '--no-embedding', '--json']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ await expectNothingAdded(b);
+ }, 240_000);
+});
+
+test('INSTALL_FOR_AGENTS.md lists every opt-in in one section, under the anchor setup prints', () => {
+ const doc = readFileSync(resolve(import.meta.dir, '..', 'INSTALL_FOR_AGENTS.md'), 'utf8');
+ expect(doc.match(/^## Opt-ins$/gm)).toHaveLength(1);
+ const section = doc.split(/^## Opt-ins$/m)[1]!.split(/^## /m)[0]!;
+ for (const command of ['--embedding-model', 'gbrain autopilot --install', ' dream`', 'gbrain connectors auth', 'self_upgrade.mode auto', 'self_upgrade.channel']) {
+ expect(section).toContain(command);
+ }
+});
+
+describe('an upgrade on a brain that never had autopilot installs none (GBRA-224 W5)', () => {
+ for (const shape of ['repo-less', 'repo'] as const) {
+ test(`post-upgrade without the opt-out on a ${shape} brain runs v0.11.0 and adds nothing`, async () => {
+ const b = box();
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ if (shape === 'repo') {
+ const repo = join(b.root, 'brain-repo');
+ mkdirSync(repo);
+ execFileSync('git', ['init', '-q', repo]);
+ const set = await gbrain(b, ['config', 'set', 'sync.repo_path', repo]);
+ expect(set.exitCode, set.stderr).toBe(0);
+ }
+ const r = await gbrain(b, ['post-upgrade']);
+ expect(r.exitCode, r.stderr + r.stdout).toBe(0);
+ const ledger = readFileSync(join(b.home, '.gbrain', 'migrations', 'completed.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
+ expect(ledger.filter(e => e.version === '0.11.0').at(-1)).toMatchObject({ status: 'complete', autopilot_installed: false });
+ await expectNothingAdded(b);
+ }, 300_000);
+ }
+
+ test.if(process.platform === 'linux')('post-upgrade rewrites only an autopilot unit that is already installed', async () => {
+ const b = box();
+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ const unitDir = join(b.home, '.config', 'systemd', 'user');
+ mkdirSync(unitDir, { recursive: true });
+ const unit = join(unitDir, 'gbrain-autopilot.service');
+ writeFileSync(unit, `[Unit]\nDescription=GBrain Autopilot\n[Service]\nExecStart=${join(b.home, '.gbrain', 'autopilot-run.sh')}\nRestart=on-failure\nStandardOutput=append:%h/.gbrain/autopilot.log\n`);
+ const r = await gbrain(b, ['post-upgrade']);
+ expect(r.exitCode, r.stderr + r.stdout).toBe(0);
+ expect(readFileSync(unit, 'utf8')).toContain('Restart=always');
+ expect(readdirSync(unitDir)).toEqual(['gbrain-autopilot.service']);
+ expect(existsSync(join(b.home, 'Library', 'LaunchAgents'))).toBe(false);
+ }, 300_000);
+});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index c0acaa41f7..e8ef1db7ab 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -108,6 +108,10 @@ describe('gbrain setup claude-code: install lifecycle', () => {
expect(next).toBeGreaterThan(-1);
expect(block).toBeGreaterThan(next);
expect(r.stdout.match(/\[AGENT\]/g)).toHaveLength(2);
+ const optIns = r.stdout.indexOf('Opt-ins (nothing is on until you turn it on)');
+ expect(optIns).toBeGreaterThan(next);
+ expect(optIns).toBeLessThan(block);
+ expect(r.stdout.match(/INSTALL_FOR_AGENTS\.md#opt-ins/g)).toHaveLength(1);
const hosted = r.stdout.indexOf('[hosted_option]');
expect(r.stdout.indexOf('[first_run_decisions]')).toBeGreaterThan(next);
expect(hosted).toBeGreaterThan(r.stdout.indexOf('[first_run_decisions]'));