Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(upgrade): stable release channel, one-command restart and verify, doctor fails on build skew (GBRA-175)

garrytan6e53d7c8bf1d
diff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.yml
new file mode 100644
index 0000000000..8099812392
--- /dev/null
+++ b/.github/workflows/promote-stable.yml
@@ -0,0 +1,83 @@
+name: Promote stable
+
+# Maintainer-only promotion of a published release to the stable channel
+# (docs/RELEASING.md#stable-channel-promotion). Weekly or manual promotions
+# both go through this dispatch; there is no schedule.
+#
+# scripts/promote-stable.ts refuses unless: the actor has the admin or
+# maintain role; v<version> is an existing release tag; soak_run_url is a
+# successful completed run of the workflow named by the STABLE_SOAK_WORKFLOW
+# repository variable; that run's head commit has the release's exact git
+# tree; and the version is newer than the current stable (an older one only
+# with rollback=true and a reason). It then creates the immutable annotated
+# record tag stable-v<version> (first promotion only) and moves the annotated
+# `stable` tag to the release commit, both carrying the same key: value body.
+# Clients read refs/tags/stable^{}; the update check reads
+# raw.githubusercontent.com/<repo>/stable/VERSION, mirroring latest-stable
+# in release.yml.
+#
+# Inputs reach the script through env only, never interpolated into run:
+# (script injection). No dependency install runs in this job, so the
+# checkout credentials that push the tags are only ever used by git.
+
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: Release VERSION to promote (an existing v<VERSION> tag), e.g. 0.60.361.0
+ required: true
+ type: string
+ soak_run_url:
+ description: GitHub Actions run URL of the passed soak on this release's tree
+ required: true
+ type: string
+ scoreboard_url:
+ description: Scoreboard URL (defaults to soak_run_url)
+ required: false
+ type: string
+ default: ''
+ rollback:
+ description: Allow moving stable to an older release
+ required: false
+ type: boolean
+ default: false
+ reason:
+ description: Why (required when rollback is true)
+ required: false
+ type: string
+ default: ''
+
+permissions:
+ contents: write # create and push the stable-v<version> and stable tags
+ actions: read # read the soak run
+
+concurrency:
+ group: promote-stable
+ cancel-in-progress: false
+
+jobs:
+ promote:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ # Full history and every tag: the script resolves v<version>,
+ # peels the current stable tag and compares trees locally.
+ fetch-depth: 0
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.4.3
+ - name: Promote the release to stable
+ env:
+ GH_TOKEN: ${{ github.token }}
+ STABLE_SOAK_WORKFLOW: ${{ vars.STABLE_SOAK_WORKFLOW }}
+ PROMOTE_VERSION: ${{ inputs.version }}
+ PROMOTE_SOAK_RUN_URL: ${{ inputs.soak_run_url }}
+ PROMOTE_SCOREBOARD_URL: ${{ inputs.scoreboard_url }}
+ PROMOTE_ROLLBACK: ${{ inputs.rollback }}
+ PROMOTE_REASON: ${{ inputs.reason }}
+ run: |
+ git config user.name "gbrain-release-bot"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ bun run scripts/promote-stable.ts
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 9649b6a2f6..179872d912 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -587,6 +587,61 @@ release already exists with all assets):
git push origin "+refs/tags/v<VERSION>^{commit}:refs/tags/latest-stable"
```
+### Stable channel promotion
+
+The stable channel is a slower ref than `latest-stable`: a release reaches it
+only after the production-shaped soak passed on its exact git tree. A
+maintainer promotes with `.github/workflows/promote-stable.yml`
+(`scripts/promote-stable.ts`), weekly or whenever a soak passes; both go
+through the same dispatch:
+
+```bash
+gh workflow run promote-stable.yml -f version=<VERSION> \
+ -f soak_run_url=https://github.com/<owner>/<repo>/actions/runs/<run id>
+```
+
+- **Refs.** `refs/tags/stable` is an annotated tag on the promoted release
+ commit, moved only by this workflow. Clients peel it (`refs/tags/stable^{}`)
+ and take the `v<VERSION>` tag on that commit; the update check reads
+ `https://raw.githubusercontent.com/<owner>/<repo>/stable/VERSION`.
+ `refs/tags/stable-v<VERSION>` is an immutable annotated record created on a
+ version's first promotion and never moved or deleted. Both carry the same
+ message: a `gbrain stable channel: v<VERSION>` title, then one
+ `key: value` line each for `version`, `commit`, `tree`, `soak_run`,
+ `scoreboard`, `promoted_by`, `promoted_at` (UTC), `previous`
+ (`none` on the first promotion), `rollback` and `reason` (`-` when
+ empty).
+- **Inputs.** `version` (an existing `v<VERSION>` release tag),
+ `soak_run_url` (the soak's Actions run URL, optionally
+ `/attempts/<n>`), `scoreboard_url` (optional, defaults to the run URL),
+ `rollback` (default false) and `reason` (required with rollback).
+- **Who.** Only an actor with the admin or maintain role; anyone else is
+ refused.
+- **Soak run.** The run must belong to this repository, be completed with
+ conclusion `success`, and run the workflow file named by the
+ `STABLE_SOAK_WORKFLOW` repository variable (Settings → Secrets and
+ variables → Actions → Variables; a bare file name like `soak.yml` or the
+ full `.github/workflows/soak.yml` path). With the variable unset, every
+ promotion is refused.
+- **Published release.** The tag's `VERSION` file must say the version, and
+ its GitHub release must exist and not be a draft, so binary clients can
+ fetch the stable release.
+- **Exact tree.** The soak run's head commit must have the same git tree as
+ the release tag. A soak of another tree is refused with both trees and the
+ run's head commit, even when the version string matches; soak the release
+ itself, then promote that run.
+- **Ordering and rollback.** The version must be newer than the current
+ stable (numeric 3- or 4-part comparison); promoting the current stable is a
+ no-op refusal. `rollback=true` with a `reason` moves stable to an older
+ release, or back to one promoted before (its record tag already exists and
+ is kept; without rollback an existing record tag is refused).
+- **One atomic push.** The record tag and `stable` land together or not at
+ all, `stable` leased on the value the run read, so a concurrent move fails
+ the run instead of being overwritten and a failed push leaves nothing to
+ clean up before the re-run. The `promote-stable` concurrency group runs one promotion at a
+ time. The run's step summary lists the version, commit, tree, soak run,
+ scoreboard, previous stable and rollback reason.
+
### The `publish-template` job
After the release job, a `publish-template` job force-pushes the rendered
diff --git a/docs/UPGRADING_DOWNSTREAM_AGENTS.md b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
index 403f085cde..093b5673e6 100644
--- a/docs/UPGRADING_DOWNSTREAM_AGENTS.md
+++ b/docs/UPGRADING_DOWNSTREAM_AGENTS.md
@@ -44,6 +44,52 @@ not know to backfill the structured timeline.
Total time: ~10 minutes for all four skills.
+## Upgrading a production agent's brain: the stable channel
+
+A downstream agent whose brain is large or always on (an OpenClaw deployment, a
+team brain behind `gbrain serve --http`) should not track every PATCH release.
+Put that brain on the **stable channel**: the newest release a maintainer
+promoted after the production-shaped soak passed on that release's exact git
+tree. Promotion is weekly or manual; `git show stable` prints the promoted
+version, the soak run and its scoreboard link.
+
+```bash
+gbrain config set self_upgrade.channel stable # once per brain home; update checks then offer only the stable release
+gbrain upgrade # installs the stable release, then restarts every gbrain process onto it
+```
+
+`gbrain upgrade --channel stable` does the same for one run without changing
+the config. The stable channel never downgrades: a build at or above the stable
+release changes nothing.
+
+**Restarts are part of the upgrade.** `gbrain upgrade` restarts serve, autopilot,
+the jobs supervisor and its worker onto the new build, then verifies that every
+gbrain process on the host reports one build and that serve's warm CLI socket
+accepts it. When a process cannot be restarted automatically it refuses before
+installing anything (`restart_refused`, exit 3) and names the exact step for
+each one. Teach your agent's upgrade skill to handle that refusal:
+
+1. Read the refusal's `fix`. When it is `ask_user` (only MCP servers block the
+ restart), relay `user_message`; after the user agrees, run the `fix.argv` it
+ names (the same upgrade with `--stop-mcp`) and reconnect gbrain in each
+ harness afterwards.
+2. When it is `tell_user_to_run`, a serve, worker or autopilot was started by
+ hand, or a `gbrain sync` is running: give the user the listed steps, then run
+ the upgrade again. Run serve and autopilot under their installed services
+ (`gbrain autopilot --install`) and workers under
+ `gbrain jobs supervisor start --detach` so later upgrades restart them on
+ their own.
+3. Verify with `gbrain doctor --only runtime_build_skew --json`: it fails while
+ two builds run, and its fix (`gbrain upgrade --restart-only`, after the user
+ agrees) restarts every process onto the installed build.
+
+`gbrain upgrade --restart-only --dry-run --json` lists every gbrain process on
+the host with its build and how it restarts, and changes nothing. A routine
+upgrade-and-restart onto the stable release is a good candidate for a standing
+approval from the operator; data-changing repairs still need a yes each time.
+Full reference: [upgrades](guides/upgrades-auto-update.md#stable-channel) and
+[restart](guides/upgrades-auto-update.md#restart).
+
---
## 1. brain-ops/SKILL.md
diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.md
index f0911d6099..6e735a024e 100644
--- a/docs/architecture/key-files/ci-health-and-test-guards.md
+++ b/docs/architecture/key-files/ci-health-and-test-guards.md
@@ -10,6 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/lib/ci-run.ts` — one run's failure evidence (`collectEvidence`): jobs, failing jobs' annotations and, for test.yml and e2e.yml, the `ci-manifest` artifact, returned as structured records (job, step, every failing test file and identity) apart from sanitized excerpts; a cancelled job is not run (listed in `cancelled`) unless its annotation says it timed out, and a red run whose only failures are aggregators of cancelled jobs is `ignored`; with `complete`/`problems` (an unreadable page, annotation or manifest is incomplete evidence, never zero failures). A push run with a succeeded `reused-full-suite` job is judged by the run its `reuse.json` names (`checkRecord` from `scripts/ci-reuse.ts`, recorded attempt, identical commit tree): that run's succeeded jobs and complete `ci-manifest` stand in for the push, and any gap is incomplete. `reproduceCommand` builds `bun run test:stress <file> --iterations 10 [--postgres]` from a validated test path only. `exemptionRows` turns failing identities with an exact test name and signature into the stress gate's `<!-- gbrain-stress-exemption -->` records (backend per `stressBackend`, owner `agent on release duty`), written into master-red, flake and nightly-red bodies; `test/fixtures/nightly-watch/stress-exemption-contract.ts` vendors the gate's parser so the tests prove it accepts them.
- `scripts/ci-manifest.ts` — the versioned failure and execution manifest (`gbrain-ci-manifest/v1`). The `executed-receipts` job of test.yml and e2e.yml builds it from every lane's receipts (via `scripts/ci-executed-counts.ts`, declared skips from the expected-deltas TSV), binds it to the workflow, event, SHA, run id and attempt, and uploads it as `ci-manifest`; each failure carries the JUnit message (credentials redacted) and the stress gate's `failureSignature` (omitted when the message holds a credential); `checkManifest` refuses a manifest for another run or attempt; `passedFiles` lists files that executed tests and failed none. Docs: `docs/ci-red-runbook.md#ci-failure-manifest`.
- `scripts/release-gate.ts` — release.yml's `ci-gate` job. Polls the push-to-master runs of Test and E2E Tests on the release commit and writes `publish`/`sha`: both green publishes; a failed run publishes nothing and fails with the next step; a run cancelled by a newer push is followed to the next master commit with the same VERSION (published there) or marks the version superseded; non-master refs are refused; it fails with the backfill command after 110 minutes. Build, release, `latest-stable` and the publish jobs use the gated commit. Tests: `test/scripts/release-gate.test.ts`. Docs: `docs/RELEASING.md#release-ci-gate`.
+- `.github/workflows/promote-stable.yml` + `scripts/promote-stable.ts` — maintainer-only stable channel promotion (`workflow_dispatch`: `version`, `soak_run_url`, `scoreboard_url`, `rollback`, `reason`; concurrency group `promote-stable`). `promote()` refuses unless the actor's `role_name` is admin or maintain, `v<VERSION>` exists with a `VERSION` file naming it and a published (non-draft) GitHub release, the soak run URL names a completed, successful run of this repository's `STABLE_SOAK_WORKFLOW` workflow (repository variable; bare file name or path), the run's head commit has the release tag's exact tree (fetched when missing), and the version is newer than the current stable (the highest `v*` tag on `refs/tags/stable^{commit}`), or older with `rollback` and a reason; re-promoting the current stable refuses. It creates the immutable annotated `stable-v<VERSION>` record (refused when it exists, except on a rollback re-promotion of the same commit) and moves the annotated `stable` tag, both with `renderTagMessage()`'s `key: value` body, then pushes both in one `--atomic` push (`stable` leased on the tag object it read, so a failed push changes nothing) and writes the step summary. Side effects come in through `PromoteDeps`. Tests: `test/scripts/promote-stable.test.ts`. Docs: `docs/RELEASING.md#stable-channel-promotion`.
- `scripts/regen-all.ts` — one entry point for every generated artifact (`ARTIFACTS`: regen and check command per artifact). `bun run regen:all` regenerates offline and keyless (provider keys and database URLs removed) and lists what changed; a second run changes nothing. `--check` is read-only and runs in `verify` as `check:regen-all`; `--goldens` also regenerates the offline contract goldens. Postgres goldens are named with their own commands, and `llms.txt` regenerates last because it inlines other generated docs. Every `bun test` it spawns (two checks and the goldens) carries `--timeout=60000` through one `BUN_TEST` prefix, because Bun does not apply bunfig.toml's `[test] timeout`. Tests: `test/scripts/regen-all.test.ts`.
- `scripts/release-restamp.ts` + `scripts/lib/restamp.ts` — `bun run release:restamp`, run when a PR is next to merge. The CLI refuses a dirty tree, fetches `origin/master`, captures the branch CHANGELOG entry and migration inventory, merges master with a merge commit (version-only stamp hunks, `CHANGELOG.md` and the `GENERATED_PATHS` files resolve mechanically; anything else stops), sets VERSION to master's PATCH + 1, renumbers branch-only migrations from master's latest + 1 (filename, export name and `version:` literal only; `migrationPayloadKey` proves the rest is token-identical and refuses a copy of a published migration or an edited published one), rewrites `STAMPS` (the CLAUDE.md "Version locations" Required rows) plus CHANGELOG and TODOS, runs `DEFAULT_STEPS`, lists branch-added lines that still name an old number (`findLeftoverRefs`, never rewritten), runs `DEFAULT_CHECKS` and commits once. Stops save `.git/gbrain-restamp.json` for `--continue` / `--abort`; `--dry-run` prints the plan, `--no-commit` stages. Generators run through `offlineEnv` (no database URLs, no provider keys). Tests: `test/scripts/release-restamp.test.ts` (fixture repos with the real migration generator; also pins CLAUDE.md table coverage and docs anchors).
- `scripts/ci-convergence-scope.sh` — #6712 PR 0: classifies a pull request's changed files (stdin) for the managed-sync convergence gate (`persistence-validation.yml` `convergence`): `run` for persistence, sync commands and sync core, page projections and storage, `bun.lock` and `vendor/postgres/`, the harness (`test/sync-convergence.serial.test.ts`, `test/fixtures/convergence-fault-kill.ts`), this script and its workflows (`persistence-validation.yml`, `convergence-nightly.yml`); `skip` otherwise, and never selected by `package.json` alone, so a release-stamp PR does not run it; an empty list runs. test.yml `changes` calls it for pull requests only (step `convergence`, passed as the `convergence` input). Tests: `test/scripts/ci-pr-scope.test.ts`.
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 2eb72a793b..5ce895d04d 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. The failure count is history: the message gives the incidents in the rolling 24 h window and when the newest ages out, and `details.facts_absorb` (`incidents_24h`, `ages_out_at`, `jobs_still_dead`, `dead_jobs`) adds the current state, the `facts-absorb` jobs dead or failed in the last 24 h with no later completed job for the same page (source and slug); they never change the status, and when no other fix applies the newest one gets the paid `gbrain jobs retry <id>` fix (`retry_job` over MCP, asks first). Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`, `test/doctor-facts-absorb-history-6761.test.ts`.
- `src/commands/doctor/checks/persistence-consumers.ts` — #6317 (B3, T1c): doctor `two_consumers_on_host` (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a `put` or a row younger than 30 s, is listed in `details`) and `consumers_without_heartbeat` (a `claim_phase.owner` pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured `agentFix` (`gbrain sources writer status --json`) and `doctorVerify`; with `persistence.single_consumer` off the overlap is reported as the configured behavior. `serve_build_drift` (#6696 C6, its own `serveBuildDriftEntry`, one `listHostConsumers` read, ok on PGLite with no read) compares the live resident rows (not this process) with this binary's `VERSION` through `compareWriterVersions` (an unparsable version counts as older): an older row warns "serve is running an older build than this checkout; restart serve and workers" with `details { count, this_version, owner, older, newer }` and a `fix` (actor `user`, `doctorVerify`) whose argv is the installed serve service's restart (`systemctl --user restart gbrain-serve.service` when `systemdUnitPath` exists on Linux, `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when `launchdPlistPath` exists on macOS; `serveBuildDriftCheck`'s `ServiceHost` argument injects platform, home and uid) or else `kill <pid>`; a newer row is reported in an ok message; no rows names `consumers_without_heartbeat` for a pre-heartbeat serve. Registered in `DOCTOR_CHECK_REGISTRY` (the consumer entry, then `serveBuildDriftEntry`) before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`. Tests: `test/doctor-serve-build-drift.test.ts`.
-- `src/commands/doctor/checks/runtime-build-skew.ts` — #7245: doctor `runtime_build_skew` (standard tier, both engines, read-only). Collects serve and the other live resident consumers from their heartbeat rows (Postgres), worker parents from the worker registry (`version`, `install_root`), the supervisor from its PID file (`readSupervisorBuild`), and job-child builds from `job_build_skew:` history entries on the newest 500 jobs updated in the last 24 h, counted only while their worker pid is live. Warns when the running builds differ or a process's install now holds another version; the fix restarts serve (`restartArgv`, exported from persistence-consumers.ts), else the supervisor (`gbrain jobs supervisor stop`), else a worker pid. Output carries pids and versions only. Pinned by `test/doctor-runtime-build-skew.test.ts`.
+- `src/commands/doctor/checks/runtime-build-skew.ts` — #7245: doctor `runtime_build_skew` (standard tier, both engines, read-only). Collects serve and the other live resident consumers from their heartbeat rows (Postgres), worker parents from the worker registry (`version`, `install_root`), the supervisor from its PID file (`readSupervisorBuild`), and job-child builds from `job_build_skew:` history entries on the newest 500 jobs updated in the last 24 h, counted only while their worker pid is live. Fails when two or more builds run (GBRA-175), warns when only an install holds another; the fix asks, then runs `gbrain upgrade --restart-only`; the message names the manual restart: serve (`restartArgv`, exported from persistence-consumers.ts), else the supervisor (`gbrain jobs supervisor stop`), else a worker pid. Output carries pids and versions only. Pinned by `test/doctor-runtime-build-skew.test.ts`.
- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) through `requireConsent` (effect `paid`; `--yes`, `--max-usd`, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload, `--json` never implying it); the budget (`--max-usd`, else the derived consent cap) soft-stops via the pass's `shouldStop` seam (estimate-based) and bounds the `--audit-rejects` half. `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index 5a732bad69..8592bcd4ee 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -12,7 +12,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (a part whose publication would change nothing is screened request-free first and takes no admission; unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan (a Codex sub-agent rollout, `session_meta` payload.source.subagent, has no user turn by design: the adapter reports `subagentRollout`, the scan counts it in `subagentRollouts` and prints `N sub-agent rollouts (no user turns by design)`, and it keeps the scan clean; an ordinary assistant-only rollout is still `userTurnsMissing` drift); no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.
-- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). A verified version equal to the running one after the install step is no swap (#6828): it prints `No newer version was installed`, skips `last_upgrade`, `JUST_UPGRADED`, the cache reset and the smoke, and on a tag pin with no newer published tag the hint moves the install off the pin with `to_version: latest`, never a cached unpublished version (#6718). With `GBRAIN_SWAP_RECEIPT` set it writes a `SwapReceipt` (`installed` / `not_installed` / `installed_broken`) for the autopilot channel (`test/autopilot-unpublished-target-6828.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report).
+- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). A verified version equal to the running one after the install step is no swap (#6828): it prints `No newer version was installed`, skips `last_upgrade`, `JUST_UPGRADED`, the cache reset and the smoke, and on a tag pin with no newer published tag the hint moves the install off the pin with `to_version: latest`, never a cached unpublished version (#6718). With `GBRAIN_SWAP_RECEIPT` set it writes a `SwapReceipt` (`installed` / `not_installed` / `installed_broken`) for the autopilot channel (`test/autopilot-unpublished-target-6828.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report). GBRA-175: `--channel latest|stable` (default `self_upgrade.channel`): `resolveStableRelease` maps the commit `refs/tags/stable` peels to onto its `v<version>` tag through `git ls-remote`, and `installStableRelease` installs exactly that release (bun: remove then add `#v<version>`, restoring the previous release on failure; bun-link: fast-forward only; binary: `fetchReleaseByTag`), never downgrading. Before the swap `preflightHostRestart` refuses (`restart_refused`, exit 3) when a running process could not be restarted; after post-upgrade the new build runs `gbrain upgrade --restart-only` (`--no-restart` skips it). Tests: `upgrade-stable-channel.test.ts`.
+- `src/commands/upgrade-restart.ts` — GBRA-175: the host side of the upgrade restart. Real process sources (consumer heartbeat rows on Postgres, the supervisor PID file, the worker registry, `ps -U <uid> -ww -o pid=,ppid=,etime=,command=` with `/proc/<pid>/environ` GBRAIN_HOME matching on Linux; the install version above each entry point), the installed serve and autopilot services with the pid each manager runs (`hostServices`: `systemctl --user show -p MainPID`, `launchctl list`), `terminateIfUnchanged` (SIGTERM an MCP pid only while `ps` still shows the same server and start time), `restartRefusal` (ask_user + `--stop-mcp` when only MCP servers block, else the first manual step for the user), `preflightHostRestart` (pre-swap, every process stale) and `runHostRestart` (`gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]`: plan, run, verify for up to 180 s with the warm-socket probe `probeCliSocket`). Tests: `upgrade-restart.test.ts`.
+- `src/core/upgrade-restart.ts` — GBRA-175: the pure half of the upgrade restart. `collectHostProcesses` (the process table is the authority: a heartbeat, PID-file or registry record whose pid `ps` does not show as gbrain is dropped; `gbrainEntry` skips wrappers such as tini, and a process's parent is its nearest gbrain ancestor), `planRestart` (a service restarts only processes under its manager's pid; `supervisorRestartArgv` keeps the launch options and PID file; anything else is a `ManualStep`), `runRestartSteps`, `restartProblems` (old pids gone, one build, roles and the supervised worker back, warm socket accepts) and `unverifiedBuilds`.
- `src/commands/watch.ts` — `gbrain watch`: the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 65604ff27c..b35861a29b 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cli-preflight.ts` — `runCliPreflight()`, the first statement of `cli.ts:main()`. (0) Re-run detection: `GBRAIN_CWD_ENV_QUARANTINED` (`CWD_ENV_QUARANTINED_MARKER`) is parsed as JSON `{cwd, neutral, wrapperPid}` and honoured ONLY when the process's startup cwd realpath-equals `neutral` and `neutral` holds none of `CWD_DOTENV_FILES` (`wrapperPid` is informational — accepted only as a positive safe integer, otherwise ignored); on a verified hop it deletes the marker, `chdir(cwd)`s back, skips step 1 (the parent already warned), and arms `installWrapperWatchdog`: an `unref()`ed 1 s interval comparing `process.ppid` (live in Bun) with `wrapperPid` — a mismatch prints one `[env]` line, `rmdirSync`s the empty neutral dir the wrapper's `finally` never reached, and exits 137, so a supervisor that SIGKILLs the wrapper pid (`restartCurrentChild`, job-isolation children, hook pushes) takes the real re-run down within about a second instead of leaving an orphan; an unverified marker is ignored, never chdir'd on. (1) `parseCwdDotenv(cwd)` ONCE, shared by the cwd == config dir check and `quarantineCwdDotenv(process.env, cwd, { assignments })`. (1a) If the drop removed a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, print `GUARDRAILS_ASSIGNED_BY_CWD_DOTENV` and exit 1 — fail-closed, never a re-run without the operator's firewall (the `~/.gbrain/.env` home is read after the quarantine and unaffected). (1b) Otherwise, whenever anything was dropped: `Bun.spawn([execPath, ...execArgv (dev runtime only; `resolveRuntimePaths` resolves a `./`/`../`-relative — or bare-and-existing — value of `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file`, `--tsconfig-override`, both spellings, against the ORIGINAL cwd because the re-run starts in the empty neutral dir; everything else passes through verbatim, in order), entry/user args], { cwd: <fresh mkdtemp dir, realpath'd so `neutral` is absolute+canonical>, env: process.env minus undefined + marker, plus the operator's real `HOME` (`USERPROFILE` on win32, from `os.userInfo().homedir`, which Bun derives from the startup environ before the `.env` merge) when a planted one was dropped, stdio: inherit })` — the re-run's Bun never loads the hostile `.env`, so dropped keys are absent (never `''`, which git and the loader presence-check); signal handlers are installed BEFORE the spawn (no orphan window); `reexecSanitized` first removes every pre-existing SIGINT/SIGTERM/SIGHUP listener (cli.ts installs process-cleanup handlers before `main()`; the wrapper relays the child and nothing else), then forwards SIGINT only when `hasControllingTerminal()` is false (`/dev/tty` `O_NOCTTY` probe; isTTY flags on win32 — a terminal delivers Ctrl-C to both processes itself), always forwards SIGTERM/SIGHUP, removes the neutral dir, and exits with the child's code or 128+signal — never earlier. Termination is structural (a re-run's startup cwd has no `.env`); gbrain self-spawns starting in the hostile cwd hop once per subtree. (2) `loadGbrainEnvFile(configDir)`; (3) the #3688 guardrails loader (moved from cli.ts; fail-closed; passes `skipCwdCheck: collision`). cwd == config dir (`cwdIsOperatorConfigDir`, exported for tests): quarantine skipped only when no cwd `.env` assigns any of `GBRAIN_HOME`, `HOME`, `USERPROFILE` and `realpath(cwd) === realpath(configDir())`. Script mode (`isScriptRuntime()`: `process.execPath` is a bun runtime, not a compiled binary): `warnScriptModeBunfig` prints `SCRIPT_MODE_BUNFIG_WARNING` once when the STARTUP cwd's `bunfig.toml` declares a top-level `preload` and the cwd is not the checkout containing the running entry (Bun ran that preload before this code; the compiled binary is built with `--no-compile-autoload-bunfig`); never repeated on the re-run. Zero cost when nothing protected is assigned. Pinned by `test/cli-cwd-dotenv-quarantine.test.ts` (hostile git checkout with planted `core.fsmonitor` via `GIT_CONFIG_*` AND via `XDG_CONFIG_HOME`; `sh` presence probe for `GIT_SSL_NO_VERIFY`; four forged-marker shapes; depth-2 re-spawn; SIGTERM/SIGKILL; native Bun terminal (`Bun.spawn({ terminal })`, skipped on win32) tty-SIGINT ignore vs non-tty SIGINT forward; SIGHUP forward; execArgv preservation across the hop; chdir-back-when-original-cwd-vanished; relative-`TMPDIR` hop; guardrails fail-closed refusal + control; wrapper outlives SIGTERM until the child exits (exit = child's, neutral dir removed); planted-`HOME` drop → real home restored in both the cron and the exported-HOME shapes; forged-home config-dir exemption refused; script-mode bunfig warning (foreign cwd warns once, own checkout silent, `[test]`-section preload silent); cwd + relative-argv restoration; compiled binary from `GBRAIN_COMPILED_BIN ?? bin/gbrain`, including a cwd `bunfig.toml` `preload` staying inert).
-- `src/core/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`, which `loadConfigWithEngine` merges from its bulk snapshot only (`mergeServeCliSocket`: `serve_cli_socket` in the config `connectEngine` publishes in `MERGED_CONFIG_BY_ENGINE`, both in `src/core/published-config.ts`), so serve decides without loading this module or reading config; off, it does neither. `server.ts` `startCliSocket` (called from both serve lanes only when on; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine whose resolved brain (`resolveBrainId`, the tier chain `connectEngine` used) is the host (a mount serve logs why and never binds), after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused; GBRAIN_HOME and `.gbrain` above it must be this uid's with no group/other write bit unless sticky, checked by `ancestorProblem` on both sides and never repaired), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; `listen()` binds synchronously under `process.umask(0o177)` (restored right after), so the kernel creates the socket 0600, and `verifyBoundSocket` only checks it (lstat: our private socket; nothing is chmod'ed through the path); it is unlinked on exit only while its inode is still ours. At most 8 requests are active, and a request counts until every promise it started settles (`ExecutedRequest.settled`), not until it answered; one still unsettled at the 30 s round-trip cap is logged once. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never binds (fail closed). `protocol.ts`: one newline-JSON request per connection (256 KiB cap), a handshake line (`accepted` or a refusal reason: `identity_mismatch` with the differing part in `mismatch`, `busy`, `malformed_request`) and one result frame (16 MiB cap; `result`, `error` with a plain OperationError's own fields, or `fallback`); the client checks every field it reads per kind (`isHandshakeFrame`, `isResultFrame`) and treats anything else as `malformed_response`. `identity.ts` `cliSocketIdentity`: the resolved brain id, `databaseTarget` (host, port, database, user and the `options` parameter; password and driver-only parameters dropped; the serve's from the engine's `connectedDatabaseUrl`, the URL it actually connected with), config dir and file realpaths, the config file's SHA-256, VERSION and `behaviorEnv` (SHA-256 values of the explicit `READ_BEHAVIOR_ENV` list, which test/cli-socket.test.ts checks against every `GBRAIN_*` name in src, the names, never values, of the recipe registry's provider credentials that are set, and SHA-256 values of its other provider variables: base URLs, endpoints, deployments, API versions, org/project/group ids); `cliSocketIdentityMismatch` compares serve and CLI part by part and returns the first differing part's name (sent as the refusal's `mismatch` and logged once per part by the serve), and a port may differ only on a Supavisor pooler host. `execute.ts` runs only `search`/`query`/`get_page` (read scope, non-mutating) through the op handler with `cliRequestContext` (makeContext's fields, remote false, source resolved from the caller's cwd and GBRAIN_SOURCE via `resolveSourceWithTier`'s `env` option; DB-plane config merged fresh per request) inside one request-scoped config snapshot (`withRequestConfigSnapshot`, `src/core/config-snapshot.ts`, the MCP read-op snapshot: one bulk config read per request, dropped when it settles) and `recall`'s op-backed forms through `recallVerbForCaller` (`src/commands/recall.ts`); the read deadline is the shorter of 30 s and the CLI's `--timeout`, and passing it answers `fallback` (the CLI runs the call itself); a search/query adds the cold path's `recallInteropNotices` (`captureRetrievalNotices`) after the handler; a segmented `get`, a non-OperationError or an OperationError subclass answers `fallback`. `output-capture.ts` records the request's console/stderr output, its `warnOncePerProcess` keys and its first noted source and its first chat-fallback hop notice in an AsyncLocalStorage scope (`setWarnOnceScope`, `setSourceNoteScope`, `setFallbackHopScope`), so MCP work on the same serve is untouched. The client (one gated call before CLI_ONLY dispatch in `src/cli/main.ts`) gives up silently (`GBRAIN_DEBUG=1` prints `[cli-socket] cold path: <reason>`) on a missing or unsafe socket, no peer-credential reader (it never connects), mount brain, `--explain`, stdin or image input, a 150 ms connect or 1 s handshake timeout, a whole exchange over `cliSocketRoundTripMs` (30 s, or a shorter `--timeout`), a refusal, a malformed frame, a frame its renderer throws on (rendered into a buffer first, so nothing prints), a serve uid mismatch, or a connection lost mid-request, and otherwise replays the captured output and renders with the cold path's `formatResult`/`applyCliOpNotices`/`writeCliError` and exit codes; `GBRAIN_CLI_SOCKET=0` skips it. Pinned by `test/cli-socket.test.ts` (identity incl. brain and env, directory/ancestor/socket checks, post-bind chmod, foreign and unreadable peer uids, unsupported platform on both sides, mount refusal, slots held until settled, frame shapes, round-trip cap, per-request hop queue, wedged and dying serves), `test/serve-cli-socket-off.test.ts` (a socket-off serve boot loads no cli-socket module and makes no engine call for it, each boot in its own process), `test/cli-socket-context.test.ts` (context parity with makeContext per source tier, serve-side timeout fallback) and `test/e2e/cli-socket-postgres.test.ts` (byte-identical output, round trips, writes bypass, handshake refusal for config and env, mount serve never answering the host CLI, stale socket, off by default, on from `serve.cli_socket`).
+- `src/core/cli-socket/` + `src/cli/cli-socket-client.ts` — the opt-in warm CLI socket for Postgres brains ([guide](../../guides/cli-socket.md)); off unless `gbrain serve --cli-socket` or DB-plane `serve.cli_socket`, which `loadConfigWithEngine` merges from its bulk snapshot only (`mergeServeCliSocket`: `serve_cli_socket` in the config `connectEngine` publishes in `MERGED_CONFIG_BY_ENGINE`, both in `src/core/published-config.ts`), so serve decides without loading this module or reading config; off, it does neither. `server.ts` `startCliSocket` (called from both serve lanes only when on; stdio after the stdout redirect) binds `$GBRAIN_HOME/.gbrain/run/cli.sock` only on a Postgres engine whose resolved brain (`resolveBrainId`, the tier chain `connectEngine` used) is the host (a mount serve logs why and never binds), after `fs-guard.ts` `ensurePrivateDir` (0700, this uid, never a symlink; an open directory this uid owns is tightened, anything else refused; GBRAIN_HOME and `.gbrain` above it must be this uid's with no group/other write bit unless sticky, checked by `ancestorProblem` on both sides and never repaired), a peer-credential self-test on a scratch socket, the native bind lock and a stale-socket probe; `listen()` binds synchronously under `process.umask(0o177)` (restored right after), so the kernel creates the socket 0600, and `verifyBoundSocket` only checks it (lstat: our private socket; nothing is chmod'ed through the path); it is unlinked on exit only while its inode is still ours. At most 8 requests are active, and a request counts until every promise it started settles (`ExecutedRequest.settled`), not until it answered; one still unsettled at the 30 s round-trip cap is logged once. Every accepted connection's uid comes from `peer-cred.ts` (bun:ffi `getsockopt(SO_PEERCRED)` on linux x64/arm64, `getpeereid` on darwin, on the socket's `_handle.fd`) and any other or unreadable uid is dropped before a byte is parsed; with no reader the serve logs why and never binds (fail closed). `protocol.ts`: one newline-JSON request per connection (256 KiB cap), a handshake line (`accepted` or a refusal reason: `identity_mismatch` with the differing part in `mismatch`, `busy`, `malformed_request`) and one result frame (16 MiB cap; `result`, `error` with a plain OperationError's own fields, or `fallback`); the client checks every field it reads per kind (`isHandshakeFrame`, `isResultFrame`) and treats anything else as `malformed_response`. `identity.ts` `cliSocketIdentity`: the resolved brain id, `databaseTarget` (host, port, database, user and the `options` parameter; password and driver-only parameters dropped; the serve's from the engine's `connectedDatabaseUrl`, the URL it actually connected with), config dir and file realpaths, the config file's SHA-256, VERSION and `behaviorEnv` (SHA-256 values of the explicit `READ_BEHAVIOR_ENV` list, which test/cli-socket.test.ts checks against every `GBRAIN_*` name in src, the names, never values, of the recipe registry's provider credentials that are set, and SHA-256 values of its other provider variables: base URLs, endpoints, deployments, API versions, org/project/group ids); `cliSocketIdentityMismatch` compares serve and CLI part by part and returns the first differing part's name (sent as the refusal's `mismatch` and logged once per part by the serve), and a port may differ only on a Supavisor pooler host. `execute.ts` runs only `search`/`query`/`get_page` (read scope, non-mutating) through the op handler with `cliRequestContext` (makeContext's fields, remote false, source resolved from the caller's cwd and GBRAIN_SOURCE via `resolveSourceWithTier`'s `env` option; DB-plane config merged fresh per request) inside one request-scoped config snapshot (`withRequestConfigSnapshot`, `src/core/config-snapshot.ts`, the MCP read-op snapshot: one bulk config read per request, dropped when it settles) and `recall`'s op-backed forms through `recallVerbForCaller` (`src/commands/recall.ts`); the read deadline is the shorter of 30 s and the CLI's `--timeout`, and passing it answers `fallback` (the CLI runs the call itself); a search/query adds the cold path's `recallInteropNotices` (`captureRetrievalNotices`) after the handler; a segmented `get`, a non-OperationError or an OperationError subclass answers `fallback`. `output-capture.ts` records the request's console/stderr output, its `warnOncePerProcess` keys and its first noted source and its first chat-fallback hop notice in an AsyncLocalStorage scope (`setWarnOnceScope`, `setSourceNoteScope`, `setFallbackHopScope`), so MCP work on the same serve is untouched. The client (one gated call before CLI_ONLY dispatch in `src/cli/main.ts`) gives up silently (`GBRAIN_DEBUG=1` prints `[cli-socket] cold path: <reason>`) on a missing or unsafe socket, no peer-credential reader (it never connects), mount brain, `--explain`, stdin or image input, a 150 ms connect or 1 s handshake timeout, a whole exchange over `cliSocketRoundTripMs` (30 s, or a shorter `--timeout`), a refusal, a malformed frame, a frame its renderer throws on (rendered into a buffer first, so nothing prints), a serve uid mismatch, or a connection lost mid-request, and otherwise replays the captured output and renders with the cold path's `formatResult`/`applyCliOpNotices`/`writeCliError` and exit codes; `GBRAIN_CLI_SOCKET=0` skips it. Pinned by `test/cli-socket.test.ts` (identity incl. brain and env, directory/ancestor/socket checks, post-bind chmod, foreign and unreadable peer uids, unsupported platform on both sides, mount refusal, slots held until settled, frame shapes, round-trip cap, per-request hop queue, wedged and dying serves), `test/serve-cli-socket-off.test.ts` (a socket-off serve boot loads no cli-socket module and makes no engine call for it, each boot in its own process), `test/cli-socket-context.test.ts` (context parity with makeContext per source tier, serve-side timeout fallback) and `test/e2e/cli-socket-postgres.test.ts` (byte-identical output, round trips, writes bypass, handshake refusal for config and env, mount serve never answering the host CLI, stale socket, off by default, on from `serve.cli_socket`). GBRA-175: `probe.ts` `probeCliSocket` sends a `probe` frame, which `server.ts` answers with the handshake alone (no op runs), so `gbrain upgrade --restart-only` checks that serve accepts the installed build; it lives outside the client so the upgrade path never loads the CLI.
- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), `withHumanLineSink(sink, fn)` (#6317: every `slog`/`serr` line under `fn`, Bun timers included, goes to `sink` instead of the streams; the serve captures a delegated managed drain's lines per job for `sync_status`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7792afac66..365de61256 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3457,6 +3457,26 @@ More: [docs/guides/troubleshooting.md#upstream-rewritten](../../docs/guides/trou
|---|---|---|---|---|---|---|
| Persistence response exceeds the local transport limit. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### restart_refused
+
+<a id="restart_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| `gbrain upgrade` (or `--restart-only`) found a gbrain process on this host it cannot restart onto the new build (a serve or worker started by hand, an autopilot without its service, a running sync, or an MCP server an agent harness started), so it restarted nothing and, before a swap, installed nothing. | A process keeps the build it started with, so restarting only some of them leaves serve, workers and MCP servers on different builds; the upgrade refuses instead of leaving that skew. Each process is named with the exact step that restarts it. | Handle each listed process as the message says (MCP servers only: rerun with --stop-mcp after the user agrees), then run the same command again; `gbrain upgrade --no-restart` installs without restarting. Run: gbrain upgrade --restart-only --dry-run --json | user | `repeat the read that failed` | 3 | no |
+
+More: [docs/guides/upgrades-auto-update.md#restart](../../docs/guides/upgrades-auto-update.md#restart)
+
+### restart_unverified
+
+<a id="restart_unverified"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| After `gbrain upgrade` restarted this host's gbrain processes, one of them still runs another build, did not come back, or the warm CLI socket refused the new build. | The restart is done only when every gbrain process on the host reports the installed build and serve's warm CLI socket accepts it; anything less is the version skew the restart exists to remove. | Restart each process the message lists with the command the plan printed, then run `gbrain upgrade --restart-only` again. Run: gbrain upgrade --restart-only --dry-run --json | agent | `gbrain doctor --only runtime_build_skew --json` | 1 | no |
+
+More: [docs/guides/upgrades-auto-update.md#restart](../../docs/guides/upgrades-auto-update.md#restart)
+
### result_too_large
<a id="result_too_large"></a>
@@ -3881,6 +3901,18 @@ More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write
|---|---|---|---|---|---|---|
| Split unparseable. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### stable_channel_unresolved
+
+<a id="stable_channel_unresolved"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| `gbrain upgrade --channel stable` (or `self_upgrade.channel stable`) could not name the stable release: the repository's tags could not be read, no release has been promoted to stable yet, or the `stable` tag does not share a commit with a `v<version>` release tag. Nothing was changed. | The stable channel installs only a release a maintainer promoted after the production-shaped soak passed on its exact tree; without that answer it installs nothing rather than guess. | Retry later, or upgrade on the latest channel with `gbrain upgrade --channel latest`. | agent | `gbrain doctor --json` | 1 | no |
+
+Reasons: `unreadable`, `no_stable`, `no_release_tag`.
+
+More: [docs/guides/upgrades-auto-update.md#stable-channel](../../docs/guides/upgrades-auto-update.md#stable-channel)
+
### stale_unavailable
<a id="stale_unavailable"></a>
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index f02958e61c..488792a39d 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -51,7 +51,7 @@
| [Doctor warns `two_consumers_on_host`](#two-consumers-on-host) | `gbrain sources writer status --json` lists the consumers alive on this host (`host.consumers`: pid, kind, mode, age); let the shorter-lived one finish (a `gbrain sync` run ends on its own) or restart it so it defers to the resident one | agent; a restart after the user agrees | none to inspect | `gbrain doctor --only two_consumers_on_host --json` |
| [Doctor warns `consumers_without_heartbeat`](#consumers-without-heartbeat) | upgrade and restart the process whose pid and kind the check names (it predates the heartbeat table and never defers) | brain host, after the user agrees | `persistent_install` when it rewrites services | `gbrain doctor --only consumers_without_heartbeat --json` |
| [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok |
-| [Doctor warns `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | restart the process the check names with the command it prints (serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid), then each other process listed on an older build | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok |
+| [Doctor fails `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | `gbrain upgrade --restart-only` restarts every listed process onto the installed build and verifies one build runs; it refuses with the exact step for a process it cannot restart (or restart each one by hand with the command the check prints: serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid) | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok |
| [Doctor warns `host_identity_mismatch`, or maintenance jobs report `owner_unavailable` / `host_mismatch` for weeks](#host-identity-mismatch) | set `GBRAIN_HOME` on that process's supervisor to the value the check prints (the owner's home; config appends `.gbrain` itself) and restart it; never edit or delete a `host.json` | brain host, after the user agrees | `persistent_install` when it rewrites a service definition | `gbrain doctor --only host_identity_mismatch --json` |
| [`fence_repair` or chronicle refused `owner_unavailable`, reason `host_mismatch`](#owner-unavailable) | `gbrain sources writer status --source <id> --json` on the brain host (the owner host id); run the step there, or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. Do not retry from the same host | brain host | none | `gbrain sources writer status --source <id> --json` shows this host's id as the owner |
| [`owner_unavailable`, reason `transfer_in_progress` or `clone_in_progress`](#owner-unavailable) | wait 30 s and retry the same step; the worktree is draining for a writer transfer or recovering from a topology clone | agent | none | `gbrain sources writer status --source <id> --json` shows state `active` |
@@ -174,7 +174,7 @@ A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation see
<a id="serve-build-drift"></a>**Doctor warns `serve_build_drift` ("serve is running an older build than this checkout; restart serve and workers")?** Upgrading or pulling the checkout does not restart the processes already running from it. Every live consumer on this host writes its gbrain version into its `persistence_consumers` heartbeat row, and the check compares the live `serve`, `sync`, `jobs`, `autopilot` and `mcp` rows with this binary's version in one read. Until they restart, one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts …`) run newer code against an older consumer. The check prints the restart for the serve: `systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when that service is installed, otherwise the pid to stop and start again the way it was launched. Restart each other listed process (the jobs worker, autopilot) the same way, after the user agrees; nothing restarts automatically. A serve older than the heartbeat table writes no row, so this check reads ok beside it and [`consumers_without_heartbeat`](#consumers-without-heartbeat) names it once it holds claims. A serve newer than this checkout is reported, not warned: upgrade the checkout before running one-shot commands from it. Verify with `gbrain doctor --only serve_build_drift --json`; on PGLite there is one process and the check reads ok.
-<a id="runtime-build-skew"></a>**Doctor warns `runtime_build_skew` (several gbrain builds are running on this host)?** Each long-running process keeps the build it loaded when it started, but `gbrain jobs run-child` starts a fresh process from the install on disk for every job. After a checkout reset, a pull or an upgrade on disk, one host can run serve on one build, the jobs supervisor and its workers on another (in memory) and their job children on a third (from disk). The check reads each process's own record: serve and the other resident consumers from their heartbeat rows (Postgres), the supervisor from lines 4 and 5 of its PID file, each `gbrain jobs work` (autopilot-spawned ones included) from its worker-registry entry, and the job children from the `job_build_skew:` line a child writes into a job's history (`gbrain jobs get <id>`) when its build differs from its worker's. It warns when the running builds differ, or when a process's install now holds another build than the one it runs, and lists every process with its pid and version (never a path). The fix names one restart, serve first, then the supervisor, then a worker: restart serve with its service command, stop the supervisor with `gbrain jobs supervisor stop` and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk), or stop a worker's pid (SIGTERM drains its jobs, and its supervisor starts a fresh one). Restart each other listed process the same way after the user agrees; nothing restarts automatically. A job child whose worker needs a readiness protocol or feature the child lacks refuses the job: the job is released without counting an attempt and the worker stops on a configuration block until it is restarted on one build. A process started before builds were recorded is named as unrecorded; restarting it makes it report one. `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. Verify with `gbrain doctor --only runtime_build_skew --json`.
+<a id="runtime-build-skew"></a>**Doctor fails `runtime_build_skew` (several gbrain builds are running on this host)?** Run `gbrain upgrade --restart-only` after the user agrees: it restarts every gbrain process on this host onto the installed build and verifies they all report it and the warm CLI socket accepts it ([restart](upgrades-auto-update.md#restart)); `--dry-run --json` previews it. Two or more running builds fail the check; one process older than its install alone warns. Each long-running process keeps the build it loaded when it started, but `gbrain jobs run-child` starts a fresh process from the install on disk for every job. After a checkout reset, a pull or an upgrade on disk, one host can run serve on one build, the jobs supervisor and its workers on another (in memory) and their job children on a third (from disk). The check reads each process's own record: serve and the other resident consumers from their heartbeat rows (Postgres), the supervisor from lines 4 and 5 of its PID file, each `gbrain jobs work` (autopilot-spawned ones included) from its worker-registry entry, and the job children from the `job_build_skew:` line a child writes into a job's history (`gbrain jobs get <id>`) when its build differs from its worker's. It fails when the running builds differ and warns when a process's install alone now holds another build than the one it runs, and lists every process with its pid and version (never a path). By hand, the message names one restart, serve first, then the supervisor, then a worker: restart serve with its service command, stop the supervisor with `gbrain jobs supervisor stop` and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk), or stop a worker's pid (SIGTERM drains its jobs, and its supervisor starts a fresh one). Restart each other listed process the same way after the user agrees; nothing restarts automatically. A job child whose worker needs a readiness protocol or feature the child lacks refuses the job: the job is released without counting an attempt and the worker stops on a configuration block until it is restarted on one build. A process started before builds were recorded is named as unrecorded; restarting it makes it report one. `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. Verify with `gbrain doctor --only runtime_build_skew --json`.
<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.
diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.md
index 7fce736080..392d8e927c 100644
--- a/docs/guides/upgrades-auto-update.md
+++ b/docs/guides/upgrades-auto-update.md
@@ -133,6 +133,35 @@ only after the release checks pass and the assets publish. Master's `VERSION`
is never offered: the next PR stamps it before release.yml tags it, and a
superseded version never gets a tag (#6718, #6828).
+<a id="stable-channel"></a>
+**The stable channel.** A large or production brain can follow a slower line:
+the newest release a maintainer promoted after the production-shaped soak
+passed on that release's exact git tree. Promotion is weekly or manual, through
+the maintainer-only `Promote stable` workflow
+([RELEASING.md](../RELEASING.md#stable-channel-promotion)), which moves the
+`stable` tag to the release commit and records the soak scoreboard link in the
+tag message (`git show stable`).
+
+```bash
+gbrain upgrade --channel stable # one run on the stable channel
+gbrain config set self_upgrade.channel stable # make stable the default for this brain home
+gbrain config set self_upgrade.channel latest # back to every published release
+```
+
+With `self_upgrade.channel stable`, every update surface above reads `VERSION`
+at the `stable` tag instead of `latest-stable`, so the marker, `check-update`,
+`self-upgrade` and the `auto` channel only ever offer the stable release.
+`gbrain upgrade` resolves it from `git ls-remote` (the `v<version>` tag on the
+commit `stable` peels to) and installs exactly that release: a bun install is
+reinstalled pinned to `#v<version>` (remove, then add; it restores the
+previous release if the add fails), a bun-link clone fast-forwards to the
+release commit (never backward or across a fork), and the binary install
+downloads that release's asset. A build already at or above the stable release
+changes nothing: the stable channel never downgrades. A ClawHub install follows
+ClawHub's own line and is refused with the reinstall command. When no release
+has been promoted yet, or the remote cannot be read, the upgrade stops with
+`stable_channel_unresolved` and changes nothing.
+
A swap is a swap only when the version changed. When `gbrain upgrade` finds
the same version running after the install step (`bun update` on a tag whose
head is already installed), it prints `No newer version was installed`, keeps
@@ -197,20 +226,63 @@ restart them for you, so they run on the new Bun. Hosts still running a
release from before this check do not run it, so a Bun floor raise reaches
them only after they have upgraded past this release.
+<a id="restart"></a>
+### Restart: one build on the host
+
+A long-running gbrain process keeps the code it started with, so an upgrade
+that restarts nothing leaves serve, the jobs supervisor and its worker,
+autopilot and every MCP server on the old build while one-shot commands and job
+children run the new one. `gbrain upgrade` therefore restarts every gbrain
+process this brain runs on the host, or refuses before it installs anything:
+
+1. **Before the swap** it lists the processes (`ps`, on Linux only processes
+ whose `GBRAIN_HOME` is this brain's, with the build each one loaded from
+ the consumer heartbeat rows on Postgres, the supervisor PID file and the
+ worker registry; a record whose pid `ps` does not show as gbrain is stale
+ and ignored) and checks that each one can be restarted: serve and autopilot
+ through their installed services when the service's own process runs them,
+ the supervisor with `gbrain jobs supervisor stop` then `start --detach` with
+ the queue, concurrency and PID file it was launched with (its worker, under
+ tini or not, restarts with it). A serve or worker started by hand, an
+ autopilot without its service, a running `gbrain sync`, or an MCP server an agent
+ harness started refuses the upgrade with `restart_refused` (exit 3), naming
+ the exact step for each process; nothing is installed. For MCP servers the
+ fix asks the user, then reruns with `--stop-mcp`: the upgrade stops them
+ (each pid only while `ps` still shows the same MCP server) and
+ each harness starts the new build when gbrain is reconnected (Claude Code:
+ `/mcp`, then reconnect; other harnesses: a new session).
+2. **After the swap and migrations** the new build runs
+ `gbrain upgrade --restart-only`: serve first, then autopilot, then the
+ supervisor, then the MCP servers `--stop-mcp` named. It then polls for up to
+ three minutes until no old pid is alive, every process reports the installed
+ build (a process that records no build must have started after the restart
+ from an install that holds it; a compiled binary's build is inferred from
+ its start time and listed as such), each restarted role and the supervisor's
+ worker came back, and, when serve had a warm CLI socket, the
+ socket accepts this build (a handshake-only probe). Anything short of that is
+ `restart_unverified` with the processes still on another build.
+
+```bash
+gbrain upgrade --restart-only --dry-run --json # read-only: every gbrain process, its build and how it restarts
+gbrain upgrade --restart-only # restart onto the installed build and verify (doctor's runtime_build_skew fix)
+gbrain upgrade --no-restart # install only; doctor fails runtime_build_skew until the restart runs
+```
+
+The autopilot `--swap-only` channel still exits for its own supervisor to
+relaunch and restarts nothing else; doctor's `runtime_build_skew` fails while
+two builds run, with `gbrain upgrade --restart-only` as its fix.
+
<a id="restart-and-verify"></a>
### Restart and verify: a deploy ends with data movement
-`gbrain upgrade` swaps the binary and runs `post-upgrade`; it never restarts a
-running `gbrain serve`, jobs worker or autopilot, and the autopilot `--swap-only`
-channel exits for its supervisor to relaunch. So an upgrade is not finished when
-the new version starts: a managed brain whose processes stay alive while no page
-commits reads healthy on `/health`, on the pid and on `sync_running: true`. Both
-`upgrade` and `post-upgrade` end by printing the supervisor's step, bare, so it
-inherits the default window:
+An upgrade is not finished when the new version starts: a managed brain whose
+processes stay alive while no page commits reads healthy on `/health`, on the
+pid and on `sync_running: true`. Both `upgrade` and `post-upgrade` end by
+printing the supervisor's step, bare, so it inherits the default window:
```bash
-# on the brain host, after the swap
-systemctl restart gbrain-serve gbrain-jobs gbrain-autopilot # or your supervisor's equivalent: every resident gbrain process
+# on the brain host, after the swap (gbrain upgrade has restarted every process; with --no-restart run:)
+gbrain upgrade --restart-only # every resident gbrain process onto the installed build, verified
gbrain sources writer movement # waits one window (max(300 s, preparation budget + 60 s)); exit 0 only when pending work moved or nothing is pending
gbrain doctor --json # managed_sync_not_moving, two_consumers_on_host, consumers_without_heartbeat, host_identity_mismatch all ok
```
diff --git a/llms-full.txt b/llms-full.txt
index 9026a08a0e..c07b6c4a67 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10491,7 +10491,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| [Doctor warns `two_consumers_on_host`](#two-consumers-on-host) | `gbrain sources writer status --json` lists the consumers alive on this host (`host.consumers`: pid, kind, mode, age); let the shorter-lived one finish (a `gbrain sync` run ends on its own) or restart it so it defers to the resident one | agent; a restart after the user agrees | none to inspect | `gbrain doctor --only two_consumers_on_host --json` |
| [Doctor warns `consumers_without_heartbeat`](#consumers-without-heartbeat) | upgrade and restart the process whose pid and kind the check names (it predates the heartbeat table and never defers) | brain host, after the user agrees | `persistent_install` when it rewrites services | `gbrain doctor --only consumers_without_heartbeat --json` |
| [Doctor warns `serve_build_drift`: serve is running an older build than this checkout](#serve-build-drift) | restart serve with the command the check prints (`systemctl --user restart gbrain-serve.service`, `launchctl kickstart -k gui/<uid>/com.gbrain.serve`, or stop the named pid and start it again), then restart each other listed worker | brain host, after the user agrees | none | `gbrain doctor --only serve_build_drift --json` is ok |
-| [Doctor warns `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | restart the process the check names with the command it prints (serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid), then each other process listed on an older build | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok |
+| [Doctor fails `runtime_build_skew`: serve, the jobs supervisor, workers and job children run different builds](#runtime-build-skew) | `gbrain upgrade --restart-only` restarts every listed process onto the installed build and verifies one build runs; it refuses with the exact step for a process it cannot restart (or restart each one by hand with the command the check prints: serve with its service command, the supervisor with `gbrain jobs supervisor stop` then `gbrain jobs supervisor start --detach`, a worker by stopping its pid) | brain host, after the user agrees | none | `gbrain doctor --only runtime_build_skew --json` is ok |
| [Doctor warns `host_identity_mismatch`, or maintenance jobs report `owner_unavailable` / `host_mismatch` for weeks](#host-identity-mismatch) | set `GBRAIN_HOME` on that process's supervisor to the value the check prints (the owner's home; config appends `.gbrain` itself) and restart it; never edit or delete a `host.json` | brain host, after the user agrees | `persistent_install` when it rewrites a service definition | `gbrain doctor --only host_identity_mismatch --json` |
| [`fence_repair` or chronicle refused `owner_unavailable`, reason `host_mismatch`](#owner-unavailable) | `gbrain sources writer status --source <id> --json` on the brain host (the owner host id); run the step there, or give the worker and the shell one `GBRAIN_HOME`. Never copy or regenerate `host.json`. Do not retry from the same host | brain host | none | `gbrain sources writer status --source <id> --json` shows this host's id as the owner |
| [`owner_unavailable`, reason `transfer_in_progress` or `clone_in_progress`](#owner-unavailable) | wait 30 s and retry the same step; the worktree is draining for a writer transfer or recovering from a topology clone | agent | none | `gbrain sources writer status --source <id> --json` shows state `active` |
@@ -10614,7 +10614,7 @@ A `drain_stalled` stop with `cause: owner_wedged_here` is the same situation see
<a id="serve-build-drift"></a>**Doctor warns `serve_build_drift` ("serve is running an older build than this checkout; restart serve and workers")?** Upgrading or pulling the checkout does not restart the processes already running from it. Every live consumer on this host writes its gbrain version into its `persistence_consumers` heartbeat row, and the check compares the live `serve`, `sync`, `jobs`, `autopilot` and `mcp` rows with this binary's version in one read. Until they restart, one-shot commands from the checkout (`gbrain sync`, `bun run src/cli.ts …`) run newer code against an older consumer. The check prints the restart for the serve: `systemctl --user restart gbrain-serve.service` or `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when that service is installed, otherwise the pid to stop and start again the way it was launched. Restart each other listed process (the jobs worker, autopilot) the same way, after the user agrees; nothing restarts automatically. A serve older than the heartbeat table writes no row, so this check reads ok beside it and [`consumers_without_heartbeat`](#consumers-without-heartbeat) names it once it holds claims. A serve newer than this checkout is reported, not warned: upgrade the checkout before running one-shot commands from it. Verify with `gbrain doctor --only serve_build_drift --json`; on PGLite there is one process and the check reads ok.
-<a id="runtime-build-skew"></a>**Doctor warns `runtime_build_skew` (several gbrain builds are running on this host)?** Each long-running process keeps the build it loaded when it started, but `gbrain jobs run-child` starts a fresh process from the install on disk for every job. After a checkout reset, a pull or an upgrade on disk, one host can run serve on one build, the jobs supervisor and its workers on another (in memory) and their job children on a third (from disk). The check reads each process's own record: serve and the other resident consumers from their heartbeat rows (Postgres), the supervisor from lines 4 and 5 of its PID file, each `gbrain jobs work` (autopilot-spawned ones included) from its worker-registry entry, and the job children from the `job_build_skew:` line a child writes into a job's history (`gbrain jobs get <id>`) when its build differs from its worker's. It warns when the running builds differ, or when a process's install now holds another build than the one it runs, and lists every process with its pid and version (never a path). The fix names one restart, serve first, then the supervisor, then a worker: restart serve with its service command, stop the supervisor with `gbrain jobs supervisor stop` and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk), or stop a worker's pid (SIGTERM drains its jobs, and its supervisor starts a fresh one). Restart each other listed process the same way after the user agrees; nothing restarts automatically. A job child whose worker needs a readiness protocol or feature the child lacks refuses the job: the job is released without counting an attempt and the worker stops on a configuration block until it is restarted on one build. A process started before builds were recorded is named as unrecorded; restarting it makes it report one. `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. Verify with `gbrain doctor --only runtime_build_skew --json`.
+<a id="runtime-build-skew"></a>**Doctor fails `runtime_build_skew` (several gbrain builds are running on this host)?** Run `gbrain upgrade --restart-only` after the user agrees: it restarts every gbrain process on this host onto the installed build and verifies they all report it and the warm CLI socket accepts it ([restart](upgrades-auto-update.md#restart)); `--dry-run --json` previews it. Two or more running builds fail the check; one process older than its install alone warns. Each long-running process keeps the build it loaded when it started, but `gbrain jobs run-child` starts a fresh process from the install on disk for every job. After a checkout reset, a pull or an upgrade on disk, one host can run serve on one build, the jobs supervisor and its workers on another (in memory) and their job children on a third (from disk). The check reads each process's own record: serve and the other resident consumers from their heartbeat rows (Postgres), the supervisor from lines 4 and 5 of its PID file, each `gbrain jobs work` (autopilot-spawned ones included) from its worker-registry entry, and the job children from the `job_build_skew:` line a child writes into a job's history (`gbrain jobs get <id>`) when its build differs from its worker's. It fails when the running builds differ and warns when a process's install alone now holds another build than the one it runs, and lists every process with its pid and version (never a path). By hand, the message names one restart, serve first, then the supervisor, then a worker: restart serve with its service command, stop the supervisor with `gbrain jobs supervisor stop` and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk), or stop a worker's pid (SIGTERM drains its jobs, and its supervisor starts a fresh one). Restart each other listed process the same way after the user agrees; nothing restarts automatically. A job child whose worker needs a readiness protocol or feature the child lacks refuses the job: the job is released without counting an attempt and the worker stops on a configuration block until it is restarted on one build. A process started before builds were recorded is named as unrecorded; restarting it makes it report one. `/health` on `gbrain serve --http` carries `build` (`version`, `installed_version`, `restart_pending`) on every 200. Verify with `gbrain doctor --only runtime_build_skew --json`.
<a id="host-identity-mismatch"></a>**Doctor warns `host_identity_mismatch`, or fence repair, chronicle and other maintenance jobs have reported `owner_unavailable` with reason `host_mismatch` for days?** Host identity is a file, `host.json` under the persistence home (`GBRAIN_HOME`, else `$HOME/.gbrain`). A job worker or container launched with a different `HOME` or without `GBRAIN_HOME` mints a new identity after every restart and sees the binding as another host's, so its writes never reach the owner while every health signal stays green. Doctor flags it when this process's identity differs from the binding owner's and the owner's checkout resolves on this filesystem (same machine id or volume), or, for a container without a stable machine id, when the checkout is present at the binding's path and this `host.json` was minted after the binding under a different `HOME`/`GBRAIN_HOME`. The check names both files, the environment each was minted under (`minted_under: {home, gbrain_home, hostname, machine_id}`; `unknown` for a file minted before it was recorded) and the one-line fix: set `GBRAIN_HOME` on that process's supervisor to the owner's home (the printed value; config appends `.gbrain` itself) and restart it. Nothing re-derives or rewrites an existing `host.json`: re-owning the binding would break every other host sharing the brain. Verify with `gbrain doctor --only host_identity_mismatch --json`.
diff --git a/scripts/agent-contract-baselines/legacy-advice-key.tsv b/scripts/agent-contract-baselines/legacy-advice-key.tsv
index 67f592cc09..85fac2ceee 100644
--- a/scripts/agent-contract-baselines/legacy-advice-key.tsv
+++ b/scripts/agent-contract-baselines/legacy-advice-key.tsv
@@ -28,7 +28,7 @@ src/commands/serve-http-registration.ts 1
src/commands/serve-http-webhooks.ts 4
src/commands/skillpack.ts 1
src/commands/sources-retry-held.ts 2
-src/commands/upgrade.ts 7
+src/commands/upgrade.ts 1
src/core/agent-install/entry.ts 1
src/core/agent-install/shared-skills.ts 7
src/core/ai/recipes/llama-server.ts 2
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 75884ada01..2d44698637 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 2003 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts)
+src/core/config.ts 2005 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts)
src/core/persistence/sync-run.ts 1682 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
diff --git a/scripts/promote-stable.ts b/scripts/promote-stable.ts
new file mode 100644
index 0000000000..c9161efefd
--- /dev/null
+++ b/scripts/promote-stable.ts
@@ -0,0 +1,306 @@
+#!/usr/bin/env bun
+/**
+ * Stable channel promotion (.github/workflows/promote-stable.yml).
+ *
+ * PROMOTE_VERSION=<v> PROMOTE_SOAK_RUN_URL=<url> [PROMOTE_SCOREBOARD_URL=<url>]
+ * [PROMOTE_ROLLBACK=true PROMOTE_REASON=<why>] bun run scripts/promote-stable.ts
+ *
+ * Promotes an already published release (the immutable `v<VERSION>` tag that
+ * release.yml minted) to the stable channel, only after the production-shaped
+ * soak passed on its exact git tree:
+ *
+ * 1. the dispatching actor has the admin or maintain role;
+ * 2. `refs/tags/v<VERSION>` exists, its VERSION file says <VERSION>, and its
+ * GitHub release is published (not a draft); its commit and tree are the
+ * release;
+ * 3. the soak run URL names a run of this repository whose workflow file is
+ * the STABLE_SOAK_WORKFLOW repository variable, completed with success;
+ * 4. the run's head commit has the release tree (the same bytes, not merely
+ * the same version);
+ * 5. the version is strictly newer than the current stable, unless this is a
+ * rollback with a reason; re-promoting the current stable is a no-op;
+ * 6. the annotated record tag `stable-v<VERSION>` is created (once per
+ * version, never moved) and the annotated `stable` tag is moved to the
+ * release commit, both carrying renderTagMessage(). One atomic push moves
+ * both, `stable` leased on the value read in step 5, so a failed push
+ * leaves the remote unchanged and a re-run starts clean.
+ *
+ * Clients peel `refs/tags/stable^{}`; the update check reads
+ * https://raw.githubusercontent.com/garrytan/gbrain/stable/VERSION, the same
+ * pattern as `latest-stable` (src/commands/check-update.ts RELEASE_REF_RAW).
+ * Side effects (gh, git, clock, log, step summary) come in through
+ * PromoteDeps, so the decisions are tested without network or a real remote
+ * (test/scripts/promote-stable.test.ts). Every refusal exits 1 with one
+ * sentence saying what to do. Docs: docs/RELEASING.md#stable-channel-promotion
+ */
+import { spawnSync } from 'node:child_process';
+import { appendFileSync } from 'node:fs';
+
+export const DOCS = 'docs/RELEASING.md#stable-channel-promotion';
+export const STABLE_REF = 'refs/tags/stable';
+const VERSION_RE = /^\d+\.\d+\.\d+(\.\d+)?$/;
+const SHA_RE = /^[0-9a-f]{40}$/;
+const PROMOTER_ROLES = new Set(['admin', 'maintain']);
+const ROLLBACK_NEEDS_REASON = 'A rollback needs a reason: re-run with the reason input saying why stable moves back.';
+
+export class Refusal extends Error {}
+
+export interface PromoteInputs {
+ version: string;
+ soakRunUrl: string;
+ scoreboardUrl: string;
+ rollback: boolean;
+ reason: string;
+}
+
+export interface GitResult { code: number; stdout: string; stderr: string }
+
+export interface PromoteDeps {
+ repo: string;
+ actor: string;
+ soakWorkflow: string;
+ ghApi(path: string): Promise<unknown>;
+ git(args: string[]): Promise<GitResult>;
+ now(): Date;
+ log(line: string): void;
+ summary(markdown: string): void;
+}
+
+export interface SoakRun {
+ status?: string | null;
+ conclusion?: string | null;
+ path?: string | null;
+ head_sha?: string | null;
+}
+
+export interface TagFields {
+ version: string;
+ commit: string;
+ tree: string;
+ soakRun: string;
+ scoreboard: string;
+ promotedBy: string;
+ promotedAt: string;
+ previous: string | null;
+ rollback: boolean;
+ reason: string;
+}
+
+export interface Promotion extends TagFields { recordCreated: boolean }
+
+export function compareVersions(a: string, b: string): number {
+ const pa = a.split('.').map(Number);
+ const pb = b.split('.').map(Number);
+ for (let i = 0; i < 4; i++) {
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
+ if (d !== 0) return Math.sign(d);
+ }
+ return 0;
+}
+
+export function parseRunUrl(url: string, repo: string): { runId: string; attempt: string | null } {
+ const m = /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/actions\/runs\/(\d+)(?:\/attempts\/(\d+))?\/?$/.exec(url.trim());
+ if (!m) throw new Refusal(`soak_run_url "${url}" is not a GitHub Actions run URL; pass https://github.com/${repo}/actions/runs/<run id> (optionally /attempts/<n>) of the soak run.`);
+ if (m[1]!.toLowerCase() !== repo.toLowerCase()) throw new Refusal(`soak_run_url names a run of ${m[1]}, not ${repo}; pass the soak run from this repository's Actions tab.`);
+ return { runId: m[2]!, attempt: m[3] ?? null };
+}
+
+export function normaliseWorkflowPath(value: string): string {
+ const bare = value.trim().replace(/@.*$/, '').replace(/^\.\//, '');
+ return bare.startsWith('.github/workflows/') ? bare : `.github/workflows/${bare}`;
+}
+
+export function requireSoakWorkflow(soakWorkflow: string): string {
+ if (!soakWorkflow.trim()) throw new Refusal('The soak workflow is not configured: set the repository variable STABLE_SOAK_WORKFLOW to the soak workflow\'s file (Settings → Secrets and variables → Actions → Variables), then re-run this workflow.');
+ return normaliseWorkflowPath(soakWorkflow);
+}
+
+export function checkSoakRun(run: SoakRun, soakWorkflow: string, url: string): void {
+ const expected = requireSoakWorkflow(soakWorkflow);
+ const actual = normaliseWorkflowPath(run.path ?? '');
+ if (actual !== expected) throw new Refusal(`Soak run ${url} ran ${actual}, not the soak workflow ${expected}; pass a run of ${expected} (or fix the STABLE_SOAK_WORKFLOW repository variable).`);
+ if (run.status !== 'completed') throw new Refusal(`Soak run ${url} is ${run.status ?? 'in an unknown state'}, not completed; wait for it to finish, then re-run this workflow.`);
+ if (run.conclusion !== 'success') throw new Refusal(`Soak run ${url} concluded ${run.conclusion ?? 'without a conclusion'}, not success; promote only a release whose soak passed.`);
+}
+
+export function checkOrder(next: string, current: string | null, rollback: boolean, reason: string): void {
+ if (rollback && !reason.trim()) throw new Refusal(ROLLBACK_NEEDS_REASON);
+ if (current === null) return;
+ const cmp = compareVersions(next, current);
+ if (cmp === 0) throw new Refusal(`v${next} is already the stable release, so there is nothing to promote.`);
+ if (cmp < 0 && !rollback) throw new Refusal(`v${next} is older than the current stable v${current}; to move stable back, re-run with rollback=true and a reason.`);
+}
+
+export function renderTagMessage(f: TagFields): string {
+ return [
+ `gbrain stable channel: v${f.version}`,
+ '',
+ `version: ${f.version}`,
+ `commit: ${f.commit}`,
+ `tree: ${f.tree}`,
+ `soak_run: ${f.soakRun}`,
+ `scoreboard: ${f.scoreboard}`,
+ `promoted_by: ${f.promotedBy}`,
+ `promoted_at: ${f.promotedAt}`,
+ `previous: ${f.previous ?? 'none'}`,
+ `rollback: ${f.rollback}`,
+ `reason: ${f.reason.trim().replace(/\s+/g, ' ') || '-'}`,
+ '',
+ ].join('\n');
+}
+
+export function renderSummary(p: Promotion): string {
+ const rows: Array<[string, string]> = [
+ ['Version', `v${p.version}`],
+ ['Commit', `\`${p.commit}\``],
+ ['Tree', `\`${p.tree}\``],
+ ['Soak run', p.soakRun],
+ ['Scoreboard', p.scoreboard],
+ ['Previous stable', p.previous ? `v${p.previous}` : 'none'],
+ ['Rollback', p.rollback ? `yes: ${p.reason.trim()}` : 'no'],
+ ['Record tag', p.recordCreated ? `\`stable-v${p.version}\` created` : `\`stable-v${p.version}\` already existed (re-promotion)`],
+ ['Promoted by', `${p.promotedBy} at ${p.promotedAt}`],
+ ];
+ const cell = (v: string) => v.replace(/\s+/g, ' ').replace(/\|/g, '\\|');
+ return [`## Stable channel: v${p.version}`, '', '| Field | Value |', '|---|---|', ...rows.map(([k, v]) => `| ${k} | ${cell(v)} |`), ''].join('\n');
+}
+
+async function gitOut(deps: PromoteDeps, args: string[], refusal: string): Promise<string> {
+ const r = await deps.git(args);
+ if (r.code !== 0) throw new Refusal(`${refusal}${r.stderr.trim() ? ` (git: ${r.stderr.trim().split('\n').at(-1)})` : ''}`);
+ return r.stdout.trim();
+}
+
+async function refExists(deps: PromoteDeps, ref: string): Promise<boolean> {
+ return (await deps.git(['rev-parse', '--verify', '--quiet', ref])).code === 0;
+}
+
+/** The current stable: the highest `v*` tag on the commit `refs/tags/stable` peels to (plus the tag object, for the push lease), or null when stable does not exist. */
+export async function currentStable(deps: PromoteDeps): Promise<{ version: string; tagObject: string } | null> {
+ if (!(await refExists(deps, STABLE_REF))) return null;
+ const tagObject = await gitOut(deps, ['rev-parse', STABLE_REF], `Could not read ${STABLE_REF}; re-run this workflow.`);
+ const commit = await gitOut(deps, ['rev-parse', `${STABLE_REF}^{commit}`], `Could not peel ${STABLE_REF} to a commit; repair the tag by hand (${DOCS}).`);
+ const versions = (await gitOut(deps, ['tag', '--points-at', commit, '--list', 'v*'], `Could not list the tags on ${commit}; re-run this workflow.`))
+ .split('\n').map(t => t.trim().replace(/^v/, '')).filter(v => VERSION_RE.test(v));
+ if (versions.length === 0) throw new Refusal(`${STABLE_REF} points at ${commit}, which carries no v<VERSION> release tag; repair the stable tag by hand before promoting (${DOCS}).`);
+ return { version: versions.sort(compareVersions).at(-1)!, tagObject };
+}
+
+export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promise<Promotion> {
+ const { version, rollback, reason } = inputs;
+
+ // `permission` is the legacy base role (maintain reads as write); `role_name` names maintain.
+ const perm = await deps.ghApi(`repos/${deps.repo}/collaborators/${encodeURIComponent(deps.actor)}/permission`) as { permission?: string; role_name?: string };
+ const role = perm.role_name || perm.permission || 'none';
+ if (perm.permission !== 'admin' && !PROMOTER_ROLES.has(role)) throw new Refusal(`${deps.actor} has the ${role} role on ${deps.repo}; only admins and maintainers promote to stable, so ask one to dispatch this workflow.`);
+ deps.log(`[promote-stable] ${deps.actor} has the ${role} role: allowed to promote.`);
+
+ if (!VERSION_RE.test(version)) throw new Refusal(`version "${version}" is not a release version; pass the VERSION of a published release, like 0.60.361.0.`);
+ if (rollback && !reason.trim()) throw new Refusal(ROLLBACK_NEEDS_REASON);
+ const releaseRef = `refs/tags/v${version}`;
+ if (!(await refExists(deps, `${releaseRef}^{commit}`))) throw new Refusal(`There is no release tag v${version}; promote a version release.yml has already published.`);
+ const commit = await gitOut(deps, ['rev-parse', `${releaseRef}^{commit}`], `Could not resolve ${releaseRef}; re-run this workflow.`);
+ const tree = await gitOut(deps, ['rev-parse', `${releaseRef}^{tree}`], `Could not resolve the tree of ${releaseRef}; re-run this workflow.`);
+ const taggedVersion = (await deps.git(['show', `${releaseRef}:VERSION`])).stdout.trim();
+ if (taggedVersion !== version) throw new Refusal(`v${version}'s VERSION file says "${taggedVersion || 'nothing'}"; promote a tag release.yml minted for its own VERSION.`);
+ let release: { draft?: boolean };
+ try {
+ release = await deps.ghApi(`repos/${deps.repo}/releases/tags/v${version}`) as { draft?: boolean };
+ } catch (error) {
+ throw new Refusal(`v${version} has no published GitHub release (${(error as Error).message.split('\n')[0]}); wait for release.yml to publish it, then promote.`);
+ }
+ if (release.draft) throw new Refusal(`The GitHub release for v${version} is still a draft; publish it (release.yml does), then promote.`);
+ deps.log(`[promote-stable] v${version} is commit ${commit}, tree ${tree}, and its GitHub release is published.`);
+
+ const { runId, attempt } = parseRunUrl(inputs.soakRunUrl, deps.repo);
+ const soakPath = requireSoakWorkflow(deps.soakWorkflow);
+ const run = await deps.ghApi(`repos/${deps.repo}/actions/runs/${runId}${attempt ? `/attempts/${attempt}` : ''}`) as SoakRun;
+ checkSoakRun(run, deps.soakWorkflow, inputs.soakRunUrl);
+ const headSha = run.head_sha ?? '';
+ if (!SHA_RE.test(headSha)) throw new Refusal(`Soak run ${inputs.soakRunUrl} reports no head commit; pass a run that checked out a commit.`);
+ deps.log(`[promote-stable] soak run ${runId}${attempt ? ` attempt ${attempt}` : ''} of ${soakPath} succeeded on ${headSha}.`);
+
+ if (!(await refExists(deps, `${headSha}^{commit}`))) await deps.git(['fetch', '--no-tags', 'origin', headSha]);
+ const soakTree = await gitOut(deps, ['rev-parse', `${headSha}^{tree}`], `Could not fetch the soak run's head commit ${headSha}; check it still exists on the remote, then re-run this workflow.`);
+ if (soakTree !== tree) throw new Refusal(`The soak ran tree ${soakTree} (run head ${headSha}) but v${version} is tree ${tree}; soak this exact release, then promote that run.`);
+ deps.log(`[promote-stable] the soak ran the release's exact tree ${tree}.`);
+
+ const current = await currentStable(deps);
+ checkOrder(version, current?.version ?? null, rollback, reason);
+ deps.log(`[promote-stable] current stable is ${current ? `v${current.version}` : 'none'}; ${rollback ? `rollback to v${version}: ${reason.trim()}` : `v${version} is newer`}.`);
+
+ const recordRef = `refs/tags/stable-v${version}`;
+ const recordExists = await refExists(deps, recordRef);
+ if (recordExists && !rollback) throw new Refusal(`stable-v${version} already exists, so v${version} was promoted before; to make it stable again, re-run with rollback=true and a reason.`);
+ if (recordExists) {
+ const recordCommit = await gitOut(deps, ['rev-parse', `${recordRef}^{commit}`], `Could not resolve ${recordRef}; re-run this workflow.`);
+ if (recordCommit !== commit) throw new Refusal(`stable-v${version} points at ${recordCommit}, not the release commit ${commit}; investigate the tags before promoting.`);
+ }
+ deps.log(`[promote-stable] record tag stable-v${version} ${recordExists ? 'exists (rollback re-promotion): keeping it' : 'is new: creating it'}.`);
+
+ const fields: TagFields = {
+ version, commit, tree,
+ soakRun: inputs.soakRunUrl.trim(),
+ scoreboard: inputs.scoreboardUrl.trim() || inputs.soakRunUrl.trim(),
+ promotedBy: deps.actor,
+ promotedAt: deps.now().toISOString().replace(/\.\d{3}Z$/, 'Z'),
+ previous: current?.version ?? null,
+ rollback, reason,
+ };
+ const message = renderTagMessage(fields);
+ if (!recordExists) {
+ await gitOut(deps, ['tag', '-a', '--cleanup=verbatim', '-m', message, `stable-v${version}`, commit], `Could not create the tag stable-v${version}; re-run this workflow.`);
+ }
+ await gitOut(deps, ['tag', '-a', '-f', '--cleanup=verbatim', '-m', message, 'stable', commit], 'Could not create the stable tag; re-run this workflow.');
+ // One atomic push: the record tag and stable land together or not at all. stable is leased on the tag object read above
+ // (empty: stable must not exist yet), so a concurrent move refuses instead of being overwritten.
+ await gitOut(deps, ['push', '--atomic', `--force-with-lease=${STABLE_REF}:${current?.tagObject ?? ''}`, 'origin',
+ ...(recordExists ? [] : [`${recordRef}:${recordRef}`]), `${STABLE_REF}:${STABLE_REF}`],
+ 'Moving the stable tag failed and nothing changed on the remote (stable may have moved since this run read it); re-run this workflow, which re-reads the current stable.');
+ if (!recordExists) deps.log(`[promote-stable] pushed record tag stable-v${version}.`);
+ deps.log(`[promote-stable] stable now points at v${version} (${commit}).`);
+
+ const promotion: Promotion = { ...fields, recordCreated: !recordExists };
+ deps.summary(renderSummary(promotion));
+ return promotion;
+}
+
+export function processDeps(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): PromoteDeps {
+ return {
+ repo: env.GITHUB_REPOSITORY ?? '',
+ actor: env.GITHUB_ACTOR ?? '',
+ soakWorkflow: env.STABLE_SOAK_WORKFLOW ?? '',
+ async ghApi(path) {
+ const r = spawnSync('gh', ['api', path], { cwd, env, encoding: 'utf8' });
+ if (r.status !== 0) throw new Error(`gh api ${path} failed: ${(r.stderr || r.error?.message || '').trim()}`);
+ return JSON.parse(r.stdout);
+ },
+ async git(args) {
+ const r = spawnSync('git', args, { cwd, env, encoding: 'utf8' });
+ return { code: r.status ?? 1, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
+ },
+ now: () => new Date(),
+ log: line => console.log(line),
+ summary: markdown => { if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, markdown); },
+ };
+}
+
+if (import.meta.main) {
+ const env = process.env;
+ const inputs: PromoteInputs = {
+ version: (env.PROMOTE_VERSION ?? '').trim().replace(/^v/, ''),
+ soakRunUrl: env.PROMOTE_SOAK_RUN_URL ?? '',
+ scoreboardUrl: env.PROMOTE_SCOREBOARD_URL ?? '',
+ rollback: env.PROMOTE_ROLLBACK === 'true',
+ reason: env.PROMOTE_REASON ?? '',
+ };
+ const deps = processDeps();
+ try {
+ if (!deps.repo || !deps.actor) throw new Refusal('GITHUB_REPOSITORY and GITHUB_ACTOR are unset; run this from the Promote stable workflow (gh workflow run promote-stable.yml).');
+ await promote(deps, inputs);
+ } catch (e) {
+ const why = e instanceof Refusal ? e.message : `the promotion stopped on an unexpected error (${e instanceof Error ? e.message : String(e)}); re-run this workflow, and read the log above if it repeats.`;
+ console.log(`::error::Stable not promoted: ${why} Docs: ${DOCS}`);
+ process.exit(1);
+ }
+}
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index e8d319d7d7..0de627e20c 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -329,6 +329,7 @@ test/scripts/nightly-issue.test.ts nightly-watch routing and guard 9 readFileSyn
test/scripts/nightly-issue.test.ts operator messages carry docs anchors that resolve 1 readFileSync
test/scripts/postgres-lane-coverage.test.ts check-postgres-lane-coverage.ts 9 readFileSync
test/scripts/postgres-unit-arms.test.ts postgres-unit-arms list 12 readFileSync
+test/scripts/promote-stable.test.ts promote-stable.yml 2 readFileSync
test/scripts/regen-all.test.ts regen:all 5 readFileSync
test/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSync
test/scripts/run-verify-parallel.test.ts run-verify-parallel.sh — no-timeout-binary fallback rc capture (regression) 7 readFileSync
diff --git a/src/commands/check-update.ts b/src/commands/check-update.ts
index b847a015cd..86975dd722 100644
--- a/src/commands/check-update.ts
+++ b/src/commands/check-update.ts
@@ -8,7 +8,8 @@ import {
semverGt,
semverLte,
} from '../core/semver.ts';
-import { readUpdateCache, writeUpdateCache, type UpdateMarker } from '../core/self-upgrade.ts';
+import { readUpdateCache, resolveReleaseChannel, writeUpdateCache, type ReleaseChannel, type UpdateMarker } from '../core/self-upgrade.ts';
+import { loadConfig } from '../core/config.ts';
/** Best-effort cache write — a read-only ~/.gbrain must never make the check throw. */
function safeWriteCache(marker: UpdateMarker): void {
@@ -57,9 +58,13 @@ function upgradeCommandForMethod(method: string): string {
* stays unread: it was a permanent 404 before releases existed (#3520). An npm
* fallback was rejected: the `gbrain` package on npm is an unrelated GPU
* library (#505), so it would produce false upgrade prompts pointing at a
- * stranger's package. */
+ * stranger's package. A brain on the stable channel (`self_upgrade.channel
+ * stable`) reads the VERSION file at the `stable` tag instead: the newest
+ * release a maintainer promoted after the production-shaped soak passed on its
+ * exact tree (.github/workflows/promote-stable.yml). */
const RELEASE_REF_RAW = 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable';
-const VERSION_SOURCE_URL = `${RELEASE_REF_RAW}/VERSION`;
+export const CHANNEL_REFS: Record<ReleaseChannel, string> = { latest: 'latest-stable', stable: 'stable' };
+const versionSourceUrl = (channel: ReleaseChannel) => `https://raw.githubusercontent.com/garrytan/gbrain/${CHANNEL_REFS[channel]}/VERSION`;
const RELEASE_NOTES_URL = 'https://github.com/garrytan/gbrain/blob/latest-stable/CHANGELOG.md';
/** Extract a version from the raw VERSION file body: first line, optional `v`
@@ -77,16 +82,16 @@ export type LatestReleaseResult =
| { ok: false; reason: 'network_error' | 'no_releases' };
/**
- * Resolve the latest published gbrain version (from VERSION at the
- * latest-stable tag — see VERSION_SOURCE_URL). Exported (v0.42) so the self-upgrade refresh path and
+ * Resolve the newest gbrain version on a release channel (from VERSION at the
+ * channel's tag — see CHANNEL_REFS). Exported (v0.42) so the self-upgrade refresh path and
* tests can reuse it. 5s timeout — this runs on the detached refresh, never the
* hot path. Failures are discriminated: `network_error` (offline/timeout) vs
* `no_releases` (endpoint answered but no usable version).
*/
-export async function fetchLatestRelease(): Promise<LatestReleaseResult> {
+export async function fetchLatestRelease(channel: ReleaseChannel = resolveReleaseChannel(loadConfig())): Promise<LatestReleaseResult> {
let res: Response;
try {
- res = await fetch(VERSION_SOURCE_URL, {
+ res = await fetch(versionSourceUrl(channel), {
headers: { 'User-Agent': `gbrain/${VERSION}` },
signal: AbortSignal.timeout(5_000),
});
@@ -212,10 +217,10 @@ export async function runCheckUpdate(args: string[]) {
}
const json = args.includes('--json');
- const method = detectInstallMethod();
- const upgradeCmd = upgradeCommandForMethod(method);
+ const channel = resolveReleaseChannel(loadConfig());
+ const upgradeCmd = channel === 'stable' ? 'gbrain upgrade' : upgradeCommandForMethod(detectInstallMethod());
- const release = await fetchLatestRelease();
+ const release = await fetchLatestRelease(channel);
if (!release.ok) {
preserveCacheOnFailedCheck();
diff --git a/src/commands/doctor/checks/persistence-consumers.ts b/src/commands/doctor/checks/persistence-consumers.ts
index c7c96c8f62..2c6b224de1 100644
--- a/src/commands/doctor/checks/persistence-consumers.ts
+++ b/src/commands/doctor/checks/persistence-consumers.ts
@@ -23,13 +23,12 @@
* installed service's restart command (else the pid) and a verify. A serve
* that predates heartbeats has no row; `consumers_without_heartbeat` names it.
*/
-import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import type { Check } from '../../doctor.ts';
import type { BrainEngine } from '../../../core/engine.ts';
import { listHostConsumers, RESIDENT_CONSUMER_KINDS, type ListedConsumer } from '../../../core/persistence/consumer-heartbeat.ts';
import { compareWriterVersions } from '../../../core/persistence/writer-versions.ts';
-import { launchdPlistPath, SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT, systemdUnitPath } from '../../../core/serve-service.ts';
+import { serveServiceRestartArgv } from '../../../core/serve-service.ts';
import { VERSION } from '../../../version.ts';
import { consumerOverlap, hostIdentityMismatches, ownersWithoutHeartbeat, OVERLAP_MIN_AGE_MS } from '../../../core/persistence/consumer-diagnostics.ts';
import { localHostIdentity } from '../../../core/persistence/identity.ts';
@@ -110,9 +109,7 @@ export interface ServiceHost { platform: string; home: string; uid: number }
/** The restart for one consumer: the installed serve service's own command, else stopping that pid for its supervisor or operator to start again. */
export function restartArgv(row: Pick<ListedConsumer, 'kind' | 'pid'>, service: ServiceHost): string[] {
- if (row.kind === 'serve' && service.platform === 'darwin' && existsSync(launchdPlistPath(service.home))) return ['launchctl', 'kickstart', '-k', `gui/${service.uid}/${SERVE_LAUNCHD_LABEL}`];
- if (row.kind === 'serve' && service.platform === 'linux' && existsSync(systemdUnitPath(service.home))) return ['systemctl', '--user', 'restart', SERVE_SYSTEMD_UNIT];
- return ['kill', String(row.pid)];
+ return (row.kind === 'serve' ? serveServiceRestartArgv(service) : null) ?? ['kill', String(row.pid)];
}
export async function serveBuildDriftCheck(engine: BrainEngine, hostId: string,
diff --git a/src/commands/doctor/checks/runtime-build-skew.ts b/src/commands/doctor/checks/runtime-build-skew.ts
index 26c5203292..3263e99be9 100644
--- a/src/commands/doctor/checks/runtime-build-skew.ts
+++ b/src/commands/doctor/checks/runtime-build-skew.ts
@@ -17,9 +17,13 @@
* build differs from its worker's (`jobChildBuildVerdict`), on the newest 500
* jobs of the last 24 h, counted while that worker is still alive.
*
- * Read-only. It warns with the processes and versions involved and names one
- * restart (serve first, then the supervisor, then a worker); nothing restarts
- * automatically. Output carries pids and versions only, never a path.
+ * Read-only. Two or more builds among the running processes (and their recent
+ * job children) fail the check (GBRA-175); one process older than its install
+ * alone warns. The fix asks the user, then runs `gbrain upgrade --restart-only`,
+ * which restarts every process onto the installed build and verifies one build
+ * runs; the message also names the first manual restart (serve first, then the
+ * supervisor, then a worker). Nothing restarts automatically. Output carries
+ * pids and versions only, never a path.
*/
import { homedir } from 'node:os';
import type { Check } from '../../doctor.ts';
@@ -39,6 +43,7 @@ const DOCS = 'docs/guides/troubleshooting.md#runtime-build-skew';
const CHILD_WINDOW_HOURS = 24;
const CHILD_SCAN_JOBS = 500;
const ROLE_ORDER = ['serve', 'supervisor', 'worker'];
+const RESTART_ARGV = ['gbrain', 'upgrade', '--restart-only'];
export interface RunningBuild { role: string; pid: number; version: string | null; installed_version: string | null }
export interface ChildBuild { job_id: number; child_version: string; worker_pid: number; worker_version: string; refused: boolean }
@@ -122,13 +127,16 @@ export async function runtimeBuildSkewCheck(engine: BrainEngine, hostId: string,
});
const restartHow = target.role === 'supervisor' ? ' and start it again with `gbrain jobs supervisor start --detach` (it respawns its worker from the install on disk)'
: argv[0] === 'kill' ? ' (SIGTERM: it drains its jobs; a supervisor respawns a worker from the install on disk) and start it again the way it was launched if nothing supervises it' : '';
- return { name: 'runtime_build_skew', status: 'warn', details,
+ const running = processes.filter(p => p.version).map(label).join('; ');
+ return { name: 'runtime_build_skew', status: versions.size > 1 ? 'fail' : 'warn', details,
message: `runtime_build_skew: ${versions.size > 1 ? `${versions.size} gbrain builds are running on this host` : 'a gbrain process runs an older build than its install'} (newest v${newest}): `
- + `${processes.filter(p => p.version).map(label).join('; ')}${childLines.length ? `; ${childLines.join('; ')}` : ''}. `
+ + `${running}${childLines.length ? `; ${childLines.join('; ')}` : ''}. `
+ 'A process keeps the build it started with, and every job child it spawns runs the build its install holds on disk now. '
- + `Restart with \`${argv.join(' ')}\`${restartHow}, then restart each other process listed on an older build; nothing restarts automatically.${unknownNote}`,
- fix: { argv, consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify('runtime_build_skew'), docs: DOCS,
- why: `Restarts ${label(target)} on the build its install holds (v${target.installed_version ?? newest}); restart every other listed process the same way.` } };
+ + `\`gbrain upgrade --restart-only\` restarts every listed process onto the installed build and verifies one build runs (it refuses, naming the step, for a process it cannot restart). `
+ + `By hand: restart with \`${argv.join(' ')}\`${restartHow}, then restart each other process listed on an older build. Nothing restarts automatically.${unknownNote}`,
+ fix: { ask_user: true, argv: RESTART_ARGV, consent: [], actor: 'agent', requires_exclusive: false, verify: doctorVerify('runtime_build_skew'), docs: DOCS,
+ why: `Restarts every gbrain process on this host that is not on the installed build (first ${label(target)}), drain-first, then verifies they all report one build and the warm CLI socket accepts it.`,
+ user_message: `gbrain processes on this host run different builds (${running}). Restart them onto the installed build with \`gbrain upgrade --restart-only\`? Serve and the jobs worker drain and come back within a minute.` } };
} catch (error) {
return checkError('runtime_build_skew', 'read the builds of this host\'s gbrain processes', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } });
}
diff --git a/src/commands/upgrade-restart.ts b/src/commands/upgrade-restart.ts
new file mode 100644
index 0000000000..fa41271da8
--- /dev/null
+++ b/src/commands/upgrade-restart.ts
@@ -0,0 +1,262 @@
+/**
+ * GBRA-175: the host side of the upgrade restart (src/core/upgrade-restart.ts
+ * holds the pure planning and verification). `gbrain upgrade` calls
+ * `preflightHostRestart` before it installs anything, so a process it could
+ * not restart refuses the upgrade instead of leaving two builds running, and
+ * the new build runs `gbrain upgrade --restart-only` after the swap, which
+ * calls `runHostRestart`. `--restart-only` on its own restarts every process
+ * onto the build already installed (doctor's `runtime_build_skew` fix);
+ * `--dry-run` prints the plan and changes nothing.
+ */
+import { existsSync, readFileSync, realpathSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { delimiter, dirname, join } from 'node:path';
+import { spawnSync } from '../core/spawn.ts';
+import { isThinClient, loadConfig, toEngineConfig } from '../core/config.ts';
+import { opError } from '../core/ops/contract.ts';
+import type { Action } from '../core/agent-output.ts';
+import { writeCliError } from '../cli/cli-error.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT, serveServiceRestartArgv } from '../core/serve-service.ts';
+import { resolveAutopilotJob } from '../core/autopilot-paths.ts';
+import { plistPath, systemdUnitPath } from './autopilot/jobs.ts';
+import { readSupervisorBuild, readSupervisorPid } from '../core/minions/supervisor-pid.ts';
+import { parseEtimeToMs, readWorkers } from '../core/minions/worker-registry.ts';
+import { installedVersion } from '../core/runtime-build.ts';
+import { VERSION } from '../version.ts';
+import {
+ classifyGbrainCommand, collectHostProcesses, gbrainEntry, planRestart, runRestartSteps, verifyRestart,
+ type HostProcess, type ProcessSources, type ProcessTableRow, type RestartPlan, type ServiceHandle, type WarmSocketState,
+} from '../core/upgrade-restart.ts';
+
+const DOCS = 'docs/guides/upgrades-auto-update.md#restart';
+const DRY_RUN_VERIFY = ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'];
+const VERIFY_TIMEOUT_MS = 180_000;
+const VERIFY_POLL_MS = 2_000;
+/** A pre-swap plan treats every process as stale: none can run the build that is not installed yet. */
+const PENDING_BUILD = 'pending';
+
+const brainHome = () => process.env.GBRAIN_HOME?.trim() || homedir();
+
+/** The GBRAIN_HOME (else HOME) in a process's environment; undefined when it cannot be read (only Linux exposes it). */
+function processHome(pid: number): string | null | undefined {
+ try {
+ const vars = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
+ const get = (name: string) => vars.find(v => v.startsWith(`${name}=`))?.slice(name.length + 1).trim() || null;
+ return get('GBRAIN_HOME') ?? get('HOME');
+ } catch {
+ return undefined;
+ }
+}
+
+/** This user's processes from `ps` (Linux and macOS), or the given pids; null when ps cannot run. */
+function readProcessTable(uid: number | undefined, pids?: number[]): ProcessTableRow[] | null {
+ const select = pids ? ['-p', pids.join(',')] : uid === undefined ? ['-x'] : ['-U', String(uid)];
+ const run = spawnSync('ps', [...select, '-ww', '-o', 'pid=,ppid=,etime=,command='], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] });
+ if (typeof run.stdout !== 'string' || (run.status !== 0 && !(pids && run.status === 1))) return null;
+ const now = Date.now();
+ return run.stdout.split('\n').flatMap(line => {
+ const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
+ if (!m) return [];
+ const elapsed = parseEtimeToMs(m[3]!);
+ const pid = Number(m[1]);
+ return [{ pid, ppid: Number(m[2]), command: m[4]!, started_ms: elapsed === null ? null : now - elapsed, gbrain_home: processHome(pid) }];
+ });
+}
+
+/** The version the install a gbrain command line starts from holds now: the package.json above its entry point (null for a compiled binary). */
+function installVersionOf(command: string): string | null {
+ const entry = gbrainEntry(command)?.entry;
+ if (!entry) return null;
+ try {
+ const found = entry.includes('/') ? entry : (process.env.PATH ?? '').split(delimiter).map(dir => join(dir, entry)).find(path => existsSync(path));
+ if (!found) return null;
+ let dir = dirname(realpathSync(found));
+ for (let i = 0; i < 4; i++, dir = dirname(dir)) {
+ const version = installedVersion(dir);
+ if (version) return version;
+ }
+ } catch { /* unknown */ }
+ return null;
+}
+
+/** The pid a service manager runs for a unit or label now; null when it is not running or cannot be read. */
+function servicePid(platform: string, unit: string, launchdLabel: string): number | null {
+ const r = platform === 'darwin' ? spawnSync('launchctl', ['list', launchdLabel], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] })
+ : spawnSync('systemctl', ['--user', 'show', '-p', 'MainPID', '--value', unit], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] });
+ if (r.status !== 0 || typeof r.stdout !== 'string') return null;
+ const pid = Number(platform === 'darwin' ? /"PID"\s*=\s*(\d+)/.exec(r.stdout)?.[1] : r.stdout.trim());
+ return Number.isInteger(pid) && pid > 1 ? pid : null;
+}
+
+/** The services this brain installed on this host: each one's restart command and the pid its manager runs. */
+export function hostServices(platform: string = process.platform, home: string = homedir(), uid: number = process.getuid?.() ?? 501): { serve: ServiceHandle | null; autopilot: ServiceHandle | null } {
+ const job = resolveAutopilotJob();
+ const autopilot = platform === 'darwin' && existsSync(plistPath(job.launchdLabel)) ? ['launchctl', 'kickstart', '-k', `gui/${uid}/${job.launchdLabel}`]
+ : platform === 'linux' && existsSync(systemdUnitPath(job.systemdUnit)) ? ['systemctl', '--user', 'restart', job.systemdUnit] : null;
+ const serve = serveServiceRestartArgv({ platform, home, uid });
+ return {
+ serve: serve ? { argv: serve, pid: servicePid(platform, SERVE_SYSTEMD_UNIT, SERVE_LAUNCHD_LABEL) } : null,
+ autopilot: autopilot ? { argv: autopilot, pid: servicePid(platform, job.systemdUnit, job.launchdLabel) } : null,
+ };
+}
+
+/** The real process sources; `close` releases the database connection the heartbeat read holds (Postgres only). */
+async function hostSources(): Promise<{ sources: ProcessSources; notes: string[]; close: () => Promise<void>; pidFile: string }> {
+ const notes: string[] = [];
+ let heartbeats: ProcessSources['heartbeats'] = async () => [];
+ let close = async () => {};
+ const config = loadConfig();
+ if (config?.engine === 'postgres' && !isThinClient(config)) {
+ try {
+ const { createEngine } = await import('../core/engine-factory.ts');
+ const { listHostConsumers } = await import('../core/persistence/consumer-heartbeat.ts');
+ const { localHostIdentity } = await import('../core/persistence/identity.ts');
+ const engine = await createEngine(toEngineConfig(config));
+ await engine.connect(toEngineConfig(config));
+ const hostId = localHostIdentity().id;
+ heartbeats = async () => (await listHostConsumers(engine, hostId)).filter(row => row.liveness === 'live' && !row.self)
+ .map(row => ({ pid: row.pid, kind: row.kind, version: row.version || null }));
+ close = () => engine.disconnect();
+ } catch (error) {
+ notes.push(`The consumer heartbeat rows could not be read (${(error as Error).message}); builds come from the PID file, the worker registry and process start times.`);
+ }
+ }
+ const { DEFAULT_PID_FILE } = await import('../core/minions/supervisor.ts');
+ const uid = process.getuid?.();
+ if (readProcessTable(uid, [process.pid]) === null) notes.push('ps could not run, so processes come from the heartbeat rows, the PID file and the worker registry, and no MCP server is signalled.');
+ const sources: ProcessSources = {
+ heartbeats,
+ supervisor: () => {
+ const status = readSupervisorPid(DEFAULT_PID_FILE);
+ return status.running && status.pid !== null ? { pid: status.pid, version: readSupervisorBuild(DEFAULT_PID_FILE)?.version ?? null } : null;
+ },
+ workers: () => { try { return readWorkers(() => null).map(w => ({ pid: w.pid, version: w.version ?? null })); } catch { return []; } },
+ processTable: () => readProcessTable(uid),
+ installVersion: installVersionOf,
+ home: brainHome(),
+ exclude: [process.pid, process.ppid],
+ };
+ return { sources, notes, close, pidFile: DEFAULT_PID_FILE };
+}
+
+/** SIGTERM pid only while it is still the MCP server the plan saw: same role, same start time (ps reports it to the second). */
+function terminateIfUnchanged(pid: number, startedMs: number | null): 'stopped' | 'gone' | 'changed' {
+ const row = readProcessTable(undefined, [pid])?.find(r => r.pid === pid);
+ if (!row) return 'gone';
+ if (classifyGbrainCommand(row.command) !== 'mcp' || startedMs === null || row.started_ms === null || Math.abs(row.started_ms - startedMs) > 2_000) return 'changed';
+ try { process.kill(pid, 'SIGTERM'); return 'stopped'; } catch { return 'gone'; }
+}
+
+const describe = (p: Pick<HostProcess, 'role' | 'pid' | 'version'>) => `${p.role} pid ${p.pid} (${p.version ? `v${p.version}` : 'build not recorded'})`;
+
+function describeSteps(plan: RestartPlan): string[] {
+ const byPid = new Map(plan.stale.map(p => [p.pid, p]));
+ const name = (pid: number) => byPid.has(pid) ? describe(byPid.get(pid)!) : `pid ${pid}`;
+ return plan.steps.map(step => step.kind === 'service' ? `${step.pids.map(name).join(', ')}: \`${step.argv.join(' ')}\``
+ : step.kind === 'supervisor' ? `${[step.pid, ...step.workers].map(name).join(', ')}: \`${step.stop.join(' ')}\`, then \`${step.start.join(' ')}\``
+ : `${name(step.pid)}: stop it (reconnect gbrain in its harness afterwards)`);
+}
+
+/** The refusal for a plan with manual steps, or null when every process restarts on its own. */
+export function restartRefusal(plan: RestartPlan, rerunArgv: readonly string[], installed: boolean) {
+ if (!plan.manual.length) return null;
+ const onlyMcp = plan.manual.every(m => m.role === 'mcp');
+ const first = plan.manual.find(m => m.role !== 'mcp') ?? plan.manual[0]!;
+ const fix: Action = onlyMcp
+ ? { ask_user: true, argv: [...rerunArgv.filter(a => a !== '--stop-mcp'), '--stop-mcp'], consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS,
+ why: 'Stops each listed MCP server during the restart; its harness starts the installed build when gbrain is reconnected.',
+ user_message: `${plan.manual.length} gbrain MCP server(s) started by agent harnesses run on this host (${plan.manual.map(m => `pid ${m.pid}`).join(', ')}). Upgrading leaves them on the old build unless they stop. May the upgrade stop them? Reconnect gbrain in each harness afterwards.`,
+ verify: { argv: DRY_RUN_VERIFY } }
+ : { argv: first.argv, consent: [], actor: 'user', requires_exclusive: false, docs: DOCS, why: first.instruction, verify: { argv: DRY_RUN_VERIFY } };
+ return opError('restart_refused',
+ `${plan.manual.length} gbrain process(es) on this host cannot be restarted automatically, so nothing was restarted${installed ? '' : ' and nothing was installed'}: ${plan.manual.map(m => m.instruction).join(' ')}`,
+ `Handle each process as listed, then run \`${rerunArgv.join(' ')}\` again; \`gbrain upgrade --no-restart\` installs without restarting (doctor then reports runtime_build_skew).`,
+ { fix, docs: DOCS });
+}
+
+export interface HostRestartOptions { stopMcp: boolean; json: boolean; rerunArgv: string[] }
+
+/**
+ * Before the swap: refuse (exit 3, nothing installed) when a running process could not be restarted afterwards.
+ * Returns true when the upgrade may proceed.
+ */
+export async function preflightHostRestart(opts: HostRestartOptions): Promise<boolean> {
+ const { sources, close } = await hostSources();
+ try {
+ const services = hostServices();
+ const plan = planRestart(await collectHostProcesses(sources), { expected: PENDING_BUILD, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp });
+ const refusal = restartRefusal(plan, opts.rerunArgv, false);
+ if (!refusal) return true;
+ setCliExitVerdict(writeCliError(refusal, 'upgrade', { json: opts.json }));
+ return false;
+ } finally {
+ await close();
+ }
+}
+
+/** `gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]`: restart every process onto the installed build and verify. */
+export async function runHostRestart(opts: HostRestartOptions & { dryRun: boolean }): Promise<void> {
+ const { sources, notes, close, pidFile } = await hostSources();
+ try {
+ const services = hostServices();
+ const before = await collectHostProcesses(sources);
+ const plan = planRestart(before, { expected: VERSION, serveService: services.serve, autopilotService: services.autopilot, stopMcp: opts.stopMcp });
+ const { probeCliSocket } = await import('../core/cli-socket/probe.ts');
+ const warmBefore = await probeCliSocket();
+ const planDoc = { expected: VERSION, processes: before, steps: plan.steps, manual: plan.manual, warm_socket: warmBefore, notes };
+ if (opts.dryRun) {
+ if (opts.json) console.log(JSON.stringify({ status: plan.manual.length ? 'refused' : 'ok', dry_run: true, ...planDoc }, null, 2));
+ else printPlan(plan, warmBefore, notes);
+ return;
+ }
+ const refusal = restartRefusal(plan, opts.rerunArgv, true);
+ if (refusal) { setCliExitVerdict(writeCliError(refusal, 'upgrade', { json: opts.json })); return; }
+ if (!opts.json) printPlan(plan, warmBefore, notes);
+ const startedMs = Date.now();
+ const results = await runRestartSteps(plan, {
+ run: argv => {
+ const r = spawnSync(argv[0]!, argv.slice(1), { encoding: 'utf8', timeout: 600_000, stdio: ['ignore', 'pipe', 'pipe'] });
+ return { status: r.error ? null : r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}${r.error ? r.error.message : ''}` };
+ },
+ terminate: terminateIfUnchanged,
+ supervisorPid: file => { const status = readSupervisorPid(file ?? pidFile); return status.running ? status.pid : null; },
+ sleep: ms => new Promise(r => setTimeout(r, ms)),
+ });
+ if (!opts.json) for (const r of results) console.log(` ${r.ok ? 'ok' : 'FAILED'}: ${r.detail}`);
+ const verified = await verifyRestart(plan, startedMs, warmBefore, {
+ collect: () => collectHostProcesses(sources), probeWarmSocket: () => probeCliSocket(),
+ sleep: ms => new Promise(r => setTimeout(r, ms)), now: () => Date.now(),
+ }, { timeoutMs: plan.steps.length ? VERIFY_TIMEOUT_MS : 0, pollMs: VERIFY_POLL_MS });
+ const doc = { status: verified.ok ? 'ok' : 'unverified', ...planDoc, results, verified: { processes: verified.processes, warm_socket: verified.warm_socket, problems: verified.problems, unverified: verified.unverified } };
+ if (!verified.ok) {
+ const failed = results.find(r => !r.ok);
+ setCliExitVerdict(writeCliError(opError('restart_unverified',
+ `After the restart this host still runs more than one gbrain build, or a process did not come back: ${verified.problems.join(' ')}`,
+ `${failed ? `${failed.detail}. ` : ''}Restart what is listed with the command the plan printed, then run \`gbrain upgrade --restart-only\` again.`,
+ { docs: DOCS, fix: { argv: DRY_RUN_VERIFY, consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS, why: 'Read-only: lists every gbrain process on this host with its build and the restart each one needs.', verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } }),
+ 'upgrade', { json: opts.json, extra: opts.json ? { restart: doc } : undefined }));
+ return;
+ }
+ if (opts.json) { console.log(JSON.stringify(doc, null, 2)); return; }
+ const running = verified.processes.map(p => `${p.role} pid ${p.pid}`).join(', ');
+ console.log(`Verified: every gbrain process on this host runs v${VERSION}${running ? ` (${running})` : ' (none is running)'}; warm CLI socket: ${verified.warm_socket.state === 'refused' ? `refused for this shell (${verified.warm_socket.reason}${verified.warm_socket.mismatch ? `: ${verified.warm_socket.mismatch}` : ''})` : verified.warm_socket.state}.`);
+ for (const line of verified.unverified) console.log(`Note: ${line}`);
+ const stopped = plan.steps.filter(step => step.kind === 'stop');
+ if (stopped.length) console.log(`Reconnect gbrain in the harness of each stopped MCP server (${stopped.map(s => `pid ${s.pid}`).join(', ')}): Claude Code /mcp, then reconnect; other harnesses: start a new session.`);
+ } finally {
+ await close();
+ }
+}
+
+function printPlan(plan: RestartPlan, warm: WarmSocketState, notes: string[]): void {
+ for (const note of notes) console.log(note);
+ if (!plan.stale.length) console.log(`Every gbrain process on this host already runs v${plan.expected}${plan.current.length ? ` (${plan.current.map(describe).join(', ')})` : ' (none is running)'}.`);
+ else {
+ console.log(`Restarting onto v${plan.expected}:`);
+ for (const line of describeSteps(plan)) console.log(` ${line}`);
+ for (const m of plan.manual) console.log(` manual: ${m.instruction}`);
+ if (plan.current.length) console.log(`Already on v${plan.expected}: ${plan.current.map(describe).join(', ')}.`);
+ }
+ console.log(`Warm CLI socket: ${warm.state}${warm.state === 'refused' ? ` (${warm.reason}${warm.mismatch ? `: ${warm.mismatch}` : ''})` : ''}.`);
+}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 80a5cd3eba..87a41721c1 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -3,7 +3,7 @@ import { execSync, execFileSync, spawnSync } from '../core/spawn.ts';
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, realpathSync } from 'fs';
import { basename, join, dirname, resolve } from 'path';
import { isNewerVersion, parseSemver, semverGt } from '../core/semver.ts';
-import { jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
+import { cliChildStdio, jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
import { opError, type OperationError } from '../core/ops/contract.ts';
import { writeCliError } from '../cli/cli-error.ts';
import { VERSION } from '../version.ts';
@@ -12,7 +12,8 @@ import { forwardProgressPast, migrationLedgerSummary, wedgedLedgerHint } from '.
import { loadCompletedMigrations } from '../core/preferences.ts';
import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';
import { loadConfig } from '../core/config.ts';
-import { clearSnooze, clearUpdateCache, writeJustUpgraded, writeSwapReceipt } from '../core/self-upgrade.ts';
+import { clearSnooze, clearUpdateCache, normalizeChannel, resolveReleaseChannel, writeJustUpgraded, writeSwapReceipt, type ReleaseChannel } from '../core/self-upgrade.ts';
+import { preflightHostRestart, runHostRestart } from './upgrade-restart.ts';
import { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';
import {
BUN_FLOOR_EXIT_CODE,
@@ -46,7 +47,7 @@ export function assessUpgradeOutcome(
export async function runUpgrade(args: string[], opts: { targetVersion?: string } = {}) {
if (args.includes('--help') || args.includes('-h')) {
- console.log('Usage: gbrain upgrade [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n\nSelf-update the CLI.\n\nDetects install method (bun, binary, clawhub) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--no-autopilot-install Skip autopilot installation and service rewrites, including package postinstall.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--no-bun-floor-check Upgrade even when the target release\'s Bun floor cannot be read or is above\n this host\'s Bun (manual upgrades only). Docs: docs/guides/upgrades-auto-update.md#bun-floor.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');
+ console.log('Usage: gbrain upgrade [--channel latest|stable] [--stop-mcp] [--no-restart] [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]\n\nSelf-update the CLI, then restart every gbrain process on this host onto the new build.\n\nDetects install method (bun, binary, clawhub) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--channel <name> latest (every published release) or stable (the newest release promoted after the\n production-shaped soak passed on its exact tree). Default: self_upgrade.channel, else latest.\n Set it per brain with: gbrain config set self_upgrade.channel stable\n--stop-mcp Stop MCP stdio servers agent harnesses started, instead of refusing; reconnect gbrain\n in each harness afterwards.\n--no-restart Install without restarting anything (doctor reports runtime_build_skew until\n \'gbrain upgrade --restart-only\' runs).\n--restart-only Restart serve, autopilot, the jobs supervisor and its worker (and, with --stop-mcp, MCP\n servers) onto the installed build, then verify every process reports it and the warm\n CLI socket accepts it. A process it cannot restart refuses with the exact step (exit 3).\n--dry-run With --restart-only: print the plan and change nothing.\n--no-autopilot-install Skip autopilot installation and service rewrites, including package postinstall.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--no-bun-floor-check Upgrade even when the target release\'s Bun floor cannot be read or is above\n this host\'s Bun (manual upgrades only). Docs: docs/guides/upgrades-auto-update.md#bun-floor.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');
return;
}
@@ -58,15 +59,34 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
// #5693: post-upgrade owns migrations, so package postinstall skips them.
const upgradeEnv = { ...process.env, GBRAIN_UPGRADE_OWNS_MIGRATIONS: '1', ...(noAutopilotInstall ? { GBRAIN_NO_AUTOPILOT_INSTALL: '1' } : {}) };
+ const json = jsonRequested(args);
+ const stopMcp = args.includes('--stop-mcp');
+ const restartOpts = { stopMcp, json, rerunArgv: ['gbrain', 'upgrade', ...args.filter(a => a !== '--json' && a !== '--dry-run')] };
+ if (args.includes('--restart-only')) {
+ await runHostRestart({ ...restartOpts, rerunArgv: ['gbrain', 'upgrade', '--restart-only', ...(stopMcp ? ['--stop-mcp'] : [])], dryRun: args.includes('--dry-run') });
+ return;
+ }
+ const noRestart = args.includes('--no-restart');
+
// Capture old version BEFORE upgrading (Codex finding: old binary runs this code)
const oldVersion = VERSION;
const method = detectInstallMethod();
console.log(`Detected install method: ${method}`);
+ const stableTarget = channelTarget(args, oldVersion, json);
+ if (stableTarget === 'stop') return;
+ if (stableTarget) opts = { ...opts, targetVersion: stableTarget.version };
+
+ if (!swapOnly && !noRestart && !await preflightHostRestart(restartOpts)) return;
+
let upgraded = false;
const recovery: SmokeRecovery = { method, oldVersion };
- switch (method) {
+ if (stableTarget) {
+ const outcome = await installStableRelease(method, stableTarget, { oldVersion, upgradeEnv, checkBunFloor, recovery });
+ if (outcome === 'refused') return;
+ upgraded = outcome === 'installed';
+ } else switch (method) {
case 'bun-link': {
const linkInfo = detectBunLink();
if (!linkInfo) {
@@ -148,7 +168,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
fromVersion: oldVersion,
toVersion: opts.targetVersion ?? result.targetVersion ?? 'unknown',
error: result.reason,
- hint: 'Integrity check failed; existing binary retained. Retry or download manually.',
+ recover: 'Integrity check failed; existing binary retained. Retry or download manually.',
});
} else {
console.error(`Binary self-update failed (${result.reason}${result.error ? `: ${result.error}` : ''}).`);
@@ -159,7 +179,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
fromVersion: oldVersion,
toVersion: opts.targetVersion ?? result.targetVersion ?? 'unknown',
error: `${result.reason}${result.error ? `: ${result.error}` : ''}`,
- hint: 'Download from https://github.com/garrytan/gbrain/releases',
+ recover: 'Download from https://github.com/garrytan/gbrain/releases',
});
}
break;
@@ -222,7 +242,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
fromVersion: oldVersion,
toVersion: target,
error: `still running ${newVersion} after upgrade`,
- hint: pinnedReinstallHint(plan),
+ recover: pinnedReinstallHint(plan),
});
setCliExitVerdict(1);
return;
@@ -244,7 +264,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
fromVersion: oldVersion,
toVersion: plan.version ?? 'latest',
error: `pinned to ${pin}; still running ${newVersion} after upgrade`,
- hint: pinnedReinstallHint(plan),
+ recover: pinnedReinstallHint(plan),
});
setCliExitVerdict(1);
return;
@@ -306,7 +326,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
fromVersion: oldVersion,
toVersion: newVersion,
error: e instanceof Error ? e.message : String(e),
- hint: 'Run: gbrain apply-migrations --yes',
+ recover: 'Run: gbrain apply-migrations --yes',
});
}
// Run features scan to show what's new and what to fix
@@ -315,18 +335,173 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
} catch {
// features scan is best-effort
}
+ // GBRA-175: the new build restarts every process onto itself and verifies one build runs (this process is the old build).
+ const restartLine = unchanged ? 'Restart: nothing to restart (no newer version was installed)'
+ : noRestart ? 'Restart: skipped (--no-restart). Run `gbrain upgrade --restart-only`; doctor reports runtime_build_skew until then'
+ : restartOntoNewBuild(stopMcp, newVersion);
console.log(unchanged ? `Binary: no newer version installed (still ${newVersion})` : `Binary: installed ${newVersion || 'a new version (could not verify)'}`);
console.log(migrationsLine);
- // #6317 (I2): upgrade owns no relaunch, so the supervisor proves data movement after it restarts serve and the workers.
+ console.log(restartLine);
+ // #6317 (I2): the supervisor proves data movement once serve and the workers run the new build.
console.log(`Next: ${MOVEMENT_SUPERVISOR_STEP}`);
}
+/** GBRA-175: `--channel <name>` / `--channel=<name>`; null when absent, 'invalid' for anything but latest or stable. */
+export function parseChannelArg(args: readonly string[]): ReleaseChannel | 'invalid' | null {
+ const at = args.findIndex(a => a === '--channel' || a.startsWith('--channel='));
+ if (at === -1) return null;
+ const raw = args[at]!.includes('=') ? args[at]!.slice('--channel='.length) : args[at + 1];
+ return normalizeChannel(raw) ?? 'invalid';
+}
+
+/** GBRA-175: the new build restarts every process onto itself and verifies one build runs; returns the summary line. */
+function restartOntoNewBuild(stopMcp: boolean, newVersion: string): string {
+ const restart = spawnSync('gbrain', ['upgrade', '--restart-only', ...(stopMcp ? ['--stop-mcp'] : [])], { stdio: cliChildStdio(), env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' }, timeout: 900_000 });
+ if (restart.status === 0) return `Restart: every gbrain process on this host runs ${newVersion || 'the new build'}`;
+ setCliExitVerdict(restart.status ?? 1);
+ return `Restart: incomplete (exit ${restart.status ?? restart.signal ?? 'unknown'}). Follow the steps above, then run \`gbrain upgrade --restart-only\``;
+}
+
+/**
+ * GBRA-175: the release `--channel` (default self_upgrade.channel) selects: null on latest, the stable release when it
+ * is newer than this build, or 'stop' after reporting an invalid channel, an unresolved stable tag or nothing newer.
+ */
+function channelTarget(args: readonly string[], oldVersion: string, json: boolean): { version: string; commit: string } | null | 'stop' {
+ const channel = parseChannelArg(args) ?? resolveReleaseChannel(loadConfig());
+ if (channel === 'invalid') {
+ setCliExitVerdict(writeCliError(opError('invalid_params', '--channel takes latest or stable.', 'Run gbrain upgrade --channel stable (or latest).'), 'upgrade', { json }));
+ return 'stop';
+ }
+ if (channel === 'latest') return null;
+ const stable = resolveStableRelease();
+ if ('error' in stable) {
+ setCliExitVerdict(writeCliError(opError('stable_channel_unresolved', stableUnresolvedMessage(stable.error), 'Nothing was changed. Retry later, or run: gbrain upgrade --channel latest', { reason: stable.error }), 'upgrade', { json }));
+ return 'stop';
+ }
+ if (!isNewerVersion(oldVersion, stable.version)) {
+ console.log(oldVersion === stable.version
+ ? `Already on the stable channel's release: gbrain ${oldVersion}.`
+ : `gbrain ${oldVersion} is newer than the stable channel's release (${stable.version}); the stable channel never downgrades. Nothing was changed.`);
+ return 'stop';
+ }
+ console.log(`Stable channel: installing gbrain ${stable.version} (promoted after the production-shaped soak).`);
+ return stable;
+}
+
+function stableUnresolvedMessage(error: 'unreadable' | 'no_stable' | 'no_release_tag'): string {
+ if (error === 'unreadable') return `The stable channel could not be read: \`git ls-remote --tags ${GBRAIN_GIT_URL}\` failed (offline, or no git).`;
+ if (error === 'no_stable') return 'No release has been promoted to the stable channel yet (the repository has no `stable` tag).';
+ return 'The `stable` tag does not point at a published release commit (no `v<version>` tag shares its commit).';
+}
+
+/**
+ * GBRA-175: the release the stable channel names: the `v<version>` tag on the commit `refs/tags/stable` peels to
+ * (the newest when several share it). promote-stable.yml moves `stable` only to a published release whose exact
+ * tree passed the soak.
+ */
+export function resolveStableRelease(git: GitRunner = runGit): { version: string; commit: string } | { error: 'unreadable' | 'no_stable' | 'no_release_tag' } {
+ const { status, stdout } = git(['ls-remote', '--tags', GBRAIN_GIT_URL]);
+ if (status !== 0) return { error: 'unreadable' };
+ const refs = new Map<string, string>();
+ for (const line of stdout.split('\n')) {
+ const [sha, ref] = line.trim().split('\t');
+ if (sha && ref) refs.set(ref, sha);
+ }
+ const peel = (tag: string) => refs.get(`refs/tags/${tag}^{}`) ?? refs.get(`refs/tags/${tag}`);
+ const commit = peel('stable');
+ if (!commit) return { error: 'no_stable' };
+ let best: string | null = null;
+ for (const ref of refs.keys()) {
+ const v = /^refs\/tags\/v(\d+\.\d+\.\d+(?:\.\d+)?)$/.exec(ref)?.[1];
+ if (v && peel(`v${v}`) === commit && (!best || isNewerVersion(best, v))) best = v;
+ }
+ return best ? { version: best, commit } : { error: 'no_release_tag' };
+}
+
+interface StableInstallContext { oldVersion: string; upgradeEnv: NodeJS.ProcessEnv; checkBunFloor: boolean; recovery: SmokeRecovery }
+
+/**
+ * GBRA-175: install exactly the stable release. bun: reinstall pinned to its tag (an in-place tag swap corrupts a
+ * global install, #5034), restoring the previous release when the add fails. bun-link: fast-forward the clone to the
+ * release commit, never backward or across a fork. binary: the release's own asset. clawhub follows its own line.
+ */
+async function installStableRelease(method: string, target: { version: string; commit: string }, ctx: StableInstallContext): Promise<'installed' | 'failed' | 'refused'> {
+ const spec = `github:${GBRAIN_GITHUB_REPO}#v${target.version}`;
+ if (method === 'clawhub' || method === 'unknown') {
+ console.error(`The stable channel installs through bun, a bun-link clone or the release binary; this install (${method}) follows its own release line. Nothing was changed.`);
+ console.error(`Reinstall on the stable release with: ${bunReinstallCommand(`#v${target.version}`)}`);
+ setCliExitVerdict(1);
+ return 'refused';
+ }
+ if (ctx.checkBunFloor && method !== 'binary' && refuseForBunFloor(await readPackageTarget(spec), target.version)) return 'refused';
+ if (method === 'binary') {
+ const { runBinarySelfUpdate, fetchReleaseByTag } = await import('../core/binary-self-update.ts');
+ const result = await runBinarySelfUpdate(process.execPath, { fetchRelease: () => fetchReleaseByTag(`v${target.version}`) });
+ if (result.ok) return 'installed';
+ console.error(`Binary self-update to the stable release ${target.version} failed (${result.reason}${result.error ? `: ${result.error}` : ''}). Your existing binary is unchanged.`);
+ recordUpgradeError({ phase: 'binary-self-update', fromVersion: ctx.oldVersion, toVersion: target.version, error: `${result.reason}`, recover: 'Retry gbrain upgrade --channel stable, or download the release asset manually.' });
+ setCliExitVerdict(1);
+ return 'failed';
+ }
+ if (method === 'bun-link') {
+ const link = detectBunLink();
+ if (!link) { console.error('bun-link detected but could not resolve repo root.'); return 'failed'; }
+ const git = (gitArgs: string[]) => spawnSync('git', ['-C', link.repoRoot, ...gitArgs], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 120_000 });
+ try { ctx.recovery.previousSha = execFileSync('git', ['-C', link.repoRoot, 'rev-parse', 'HEAD'], { encoding: 'utf-8', timeout: 10_000 }).trim(); } catch { /* recovery text falls back */ }
+ ctx.recovery.repoRoot = link.repoRoot;
+ if (git(['fetch', '--quiet', 'origin', `+refs/tags/v${target.version}:refs/tags/v${target.version}`]).status !== 0) {
+ console.error(`Could not fetch v${target.version} into ${link.repoRoot}. Nothing was changed.`);
+ setCliExitVerdict(1);
+ return 'failed';
+ }
+ if (git(['merge-base', '--is-ancestor', 'HEAD', target.commit]).status !== 0) {
+ console.error(`The clone at ${link.repoRoot} has commits that v${target.version} does not, and the stable channel never moves a clone backward or across a fork. Nothing was changed.`);
+ console.error(`To run the stable release from this clone, check it out yourself: git -C ${link.repoRoot} checkout v${target.version} && bun install`);
+ setCliExitVerdict(1);
+ return 'refused';
+ }
+ try {
+ execFileSync('git', ['-C', link.repoRoot, 'merge', '--ff-only', target.commit], { stdio: cliChildStdio(), timeout: 120_000 });
+ execFileSync('bun', ['install'], { cwd: link.repoRoot, env: ctx.upgradeEnv, stdio: cliChildStdio(), timeout: 120_000 });
+ return 'installed';
+ } catch {
+ if (installedDespiteFailure(ctx.oldVersion)) return 'installed';
+ console.error(`Upgrade to v${target.version} failed. Try manually: cd ${link.repoRoot} && git merge --ff-only ${target.commit} && bun install`);
+ return 'failed';
+ }
+ }
+ if (probeReleaseTag(target.version) === 'not_published') {
+ console.error(`v${target.version} has no release tag on GitHub. Nothing was removed.`);
+ setCliExitVerdict(1);
+ return 'refused';
+ }
+ const bun = (bunArgs: string[]) => execFileSync('bun', bunArgs, { env: ctx.upgradeEnv, stdio: cliChildStdio(), timeout: 300_000 });
+ try {
+ bun(['remove', '-g', 'gbrain']);
+ bun(['add', '-g', spec]);
+ return 'installed';
+ } catch {
+ if (installedDespiteFailure(ctx.oldVersion)) return 'installed';
+ console.error(`Installing ${spec} failed. Restoring gbrain ${ctx.oldVersion}...`);
+ try { bun(['add', '-g', `github:${GBRAIN_GITHUB_REPO}#v${ctx.oldVersion}`]); console.error(`Restored gbrain ${ctx.oldVersion}.`); }
+ catch { console.error(`Restore failed. Reinstall by hand: ${bunReinstallCommand(`#v${target.version}`)}`); }
+ recordUpgradeError({ phase: 'stable-reinstall', fromVersion: ctx.oldVersion, toVersion: target.version, error: `bun add -g ${spec} failed`, recover: bunReinstallCommand(`#v${target.version}`) });
+ setCliExitVerdict(1);
+ return 'failed';
+ }
+}
+
/**
* #5855: the Bun floor of the release `gbrain upgrade` would install for this
* install method (the autopilot channel's pre-swap check). The swap re-reads
- * it, so a floor raised in between still refuses there.
+ * it, so a floor raised in between still refuses there. GBRA-175: on the stable
+ * channel (self_upgrade.channel) it is the stable release's floor.
*/
-export async function readInstallTargetFloor(method: string): Promise<TargetFloor> {
+export async function readInstallTargetFloor(method: string, channel: ReleaseChannel = resolveReleaseChannel(loadConfig())): Promise<TargetFloor> {
+ if (channel === 'stable') {
+ const stable = resolveStableRelease();
+ return 'error' in stable ? { ok: false, failedRead: `the stable channel's release (${stable.error})` } : readPackageTarget(`github:${GBRAIN_GITHUB_REPO}#v${stable.version}`);
+ }
if (method === 'bun-link') {
const link = detectBunLink();
return link ? readBunLinkTarget(link.repoRoot).target : { ok: false, failedRead: 'the bun-link source clone could not be found' };
@@ -379,7 +554,7 @@ function postSwapSmoke(newVersion: string, r: SmokeRecovery): boolean {
fromVersion: r.oldVersion,
toVersion: newVersion || 'unknown',
error: `gbrain --help failed after the swap (${why})${detail ? `: ${detail}` : ''}`,
- hint: back ? `bun upgrade && gbrain post-upgrade, or return to ${r.oldVersion}: ${back}` : 'bun upgrade && gbrain post-upgrade',
+ recover: back ? `bun upgrade && gbrain post-upgrade, or return to ${r.oldVersion}: ${back}` : 'bun upgrade && gbrain post-upgrade',
});
setCliExitVerdict(1);
return false;
@@ -600,7 +775,8 @@ export function recordUpgradeError(record: {
fromVersion: string;
toVersion: string;
error: string;
- hint: string;
+ /** The paste-ready recovery step doctor shows (the record's `hint` field). */
+ recover: string;
}): void {
try {
const dir = join(process.env.HOME || '', '.gbrain');
@@ -612,7 +788,7 @@ export function recordUpgradeError(record: {
from_version: record.fromVersion,
to_version: record.toVersion,
error: record.error,
- hint: record.hint,
+ hint: record.recover,
}) + '\n';
appendFileSync(path, line);
} catch {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 39ac344787..b865b0dca6 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1097,6 +1097,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.359.0', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },
// #7190 (GBRA-150): per-source applied-through watermark. `since` is stamped at the merge slot.
{ since: '0.60.361.0', id: 'applied_watermark_7190', text: '`get_write_request` with `applied: true` (`gbrain write-request <id> --applied`) now returns `applied`, read live: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`), the request `sequence` and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`), and a pending write\'s hint names that read; a write\'s own reply is otherwise unchanged. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },
+ // GBRA-175 (stable channel, upgrade restarts every process). `since` is stamped at the merge slot.
+ { since: '0.60.362.0', id: 'upgrade_restarts_7245', text: '`gbrain upgrade` now restarts every gbrain process this brain runs on the host onto the new build (serve and autopilot through their installed services, the jobs supervisor and its worker with `gbrain jobs supervisor stop` then `start --detach`) and verifies that they all report one build and that the warm CLI socket accepts it. Before installing anything it refuses with `restart_refused` (exit 3) when a process cannot be restarted automatically: a serve or worker started by hand, an autopilot without its service, a running sync, or an MCP server an agent harness started (rerun with `--stop-mcp` to stop those; reconnect gbrain in each harness afterwards). `--no-restart` installs without restarting; `gbrain upgrade --restart-only` restarts onto the installed build (`--dry-run` previews). The autopilot `--swap-only` channel is unchanged.' },
+ { since: '0.60.362.0', id: 'runtime_build_skew_fails_7245', text: 'doctor `runtime_build_skew` now fails (was a warning) when two or more gbrain builds run on this host, and its fix asks the user before running `gbrain upgrade --restart-only`; one process older than its install alone still warns. New release channel: `gbrain upgrade --channel stable` or `gbrain config set self_upgrade.channel stable` installs only releases a maintainer promoted after the production-shaped soak passed on their exact tree, and the update checks then offer only that release; the default channel (`latest`) is unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/binary-self-update.ts b/src/core/binary-self-update.ts
index 4e1cd6e4eb..14deb26a27 100644
--- a/src/core/binary-self-update.ts
+++ b/src/core/binary-self-update.ts
@@ -156,8 +156,17 @@ export interface BinarySelfUpdateDeps {
}
async function defaultFetchRelease(): Promise<{ tag: string; assets: ReleaseAsset[] } | null> {
+ return fetchReleaseJson('https://api.github.com/repos/garrytan/gbrain/releases/latest');
+}
+
+/** GBRA-175: one named release (the stable channel's), in the same shape as the latest release. */
+export function fetchReleaseByTag(tag: string): Promise<{ tag: string; assets: ReleaseAsset[] } | null> {
+ return fetchReleaseJson(`https://api.github.com/repos/garrytan/gbrain/releases/tags/${encodeURIComponent(tag)}`);
+}
+
+async function fetchReleaseJson(url: string): Promise<{ tag: string; assets: ReleaseAsset[] } | null> {
try {
- const res = await fetch('https://api.github.com/repos/garrytan/gbrain/releases/latest', {
+ const res = await fetch(url, {
headers: { 'User-Agent': 'gbrain-self-upgrade' },
signal: AbortSignal.timeout(5_000),
});
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e9a6543319..72a11ece88 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -20,7 +20,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],
'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--origin', '--parked-pushes', '--pat-file', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--wait', '--warn-only', '--yes'],
- 'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
+ 'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],
'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],
@@ -34,7 +34,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
- 'check-update': ['--brain', '--exit-code', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
+ 'check-update': ['--brain', '--channel', '--exit-code', '--ff-only', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'claw-test': ['--agent', '--apply', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--statement-timeout', '--version', '--yes'],
'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--channel', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -75,14 +75,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--push-only', '--query', '--question', '--queue', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--push-only', '--query', '--question', '--queue', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
@@ -93,7 +93,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],
- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
@@ -118,7 +118,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--request-id', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
- 'self-upgrade': ['--apply', '--brain', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--refs', '--remediation-plan', '--source', '--swap-only', '--tags', '--version', '--yes'],
+ 'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
@@ -130,12 +130,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],
'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
diff --git a/src/core/cli-socket/probe.ts b/src/core/cli-socket/probe.ts
new file mode 100644
index 0000000000..8e3a9da009
--- /dev/null
+++ b/src/core/cli-socket/probe.ts
@@ -0,0 +1,56 @@
+/**
+ * GBRA-175: the warm CLI socket's probe, which the upgrade restart uses to check that the running serve accepts the
+ * installed build. Kept apart from src/cli/cli-socket-client.ts, whose op rendering reaches the whole CLI.
+ */
+import net from 'node:net';
+import { loadConfig, configDir, configPath, isThinClient } from '../config.ts';
+import { getCliOptions } from '../cli-options.ts';
+import { resolveBrainId } from '../brain-resolver.ts';
+import { VERSION } from '../../version.ts';
+import { cliSocketDir, cliSocketPath, connectProblem } from './fs-guard.ts';
+import { cliSocketIdentity } from './identity.ts';
+import { peerCredSupport, peerUid, type PeerCredSupport } from './peer-cred.ts';
+import { CONNECT_TIMEOUT_MS, FrameReader, HANDSHAKE_TIMEOUT_MS, isHandshakeFrame, MAX_RESPONSE_BYTES, type CliSocketProbe } from './protocol.ts';
+import type { WarmSocketState } from '../upgrade-restart.ts';
+
+/**
+ * GBRA-175: whether the running serve's warm socket accepts this build and this shell's brain identity. Handshake only:
+ * the serve runs nothing. `absent` when this brain has no socket (not Postgres, a thin client, or serve runs without
+ * --cli-socket); a socket file nobody answers is `refused` (`connect_failed`), so a serve that did not come back shows.
+ */
+export function probeCliSocket(peerCred: PeerCredSupport = peerCredSupport()): Promise<WarmSocketState> {
+ const config = loadConfig();
+ if (!config || config.engine !== 'postgres' || !config.database_url || isThinClient(config)) return Promise.resolve({ state: 'absent' });
+ const home = configDir();
+ const path = cliSocketPath(home);
+ const problem = connectProblem(path, cliSocketDir(home));
+ if (problem === 'missing') return Promise.resolve({ state: 'absent' });
+ if (problem) return Promise.resolve({ state: 'refused', reason: problem });
+ if (!peerCred.ok) return Promise.resolve({ state: 'refused', reason: `peer_credentials_unsupported (${peerCred.reason})` });
+ const support = peerCred;
+ let brainId: string;
+ try { brainId = resolveBrainId(getCliOptions().brain); } catch (error) { return Promise.resolve({ state: 'refused', reason: `brain_unresolved (${(error as Error).message})` }); }
+ const probe: CliSocketProbe = { v: 1, kind: 'probe', identity: cliSocketIdentity({ config, brainId, configDir: home, configFile: configPath(), version: VERSION, env: process.env }) };
+ return new Promise(resolve => {
+ const socket = net.createConnection(path);
+ const reader = new FrameReader(MAX_RESPONSE_BYTES);
+ const finish = (state: WarmSocketState) => { clearTimeout(timer); socket.destroy(); resolve(state); };
+ const timer = setTimeout(() => finish({ state: 'refused', reason: 'handshake_timeout' }), CONNECT_TIMEOUT_MS + HANDSHAKE_TIMEOUT_MS);
+ socket.once('error', error => finish({ state: 'refused', reason: `connect_failed (${(error as NodeJS.ErrnoException).code ?? error.message})` }));
+ socket.once('close', () => finish({ state: 'refused', reason: 'serve_closed' }));
+ socket.once('connect', () => {
+ if (peerUid(socket, support.read) !== process.getuid?.()) { finish({ state: 'refused', reason: 'serve_uid_mismatch' }); return; }
+ socket.write(JSON.stringify(probe) + '\n');
+ });
+ socket.on('data', data => {
+ const frames = reader.push(typeof data === 'string' ? Buffer.from(data) : data);
+ if (frames === 'overflow') { finish({ state: 'refused', reason: 'response_too_large' }); return; }
+ if (!frames.length) return;
+ let value: unknown;
+ try { value = JSON.parse(frames[0]!); } catch { value = null; }
+ if (!isHandshakeFrame(value)) finish({ state: 'refused', reason: 'malformed_response' });
+ else if (value.accepted) finish({ state: 'accepted' });
+ else finish({ state: 'refused', reason: value.reason, ...(value.mismatch ? { mismatch: value.mismatch } : {}) });
+ });
+ });
+}
diff --git a/src/core/cli-socket/protocol.ts b/src/core/cli-socket/protocol.ts
index 099cc10df8..4966e73dd8 100644
--- a/src/core/cli-socket/protocol.ts
+++ b/src/core/cli-socket/protocol.ts
@@ -40,6 +40,16 @@ export type CliSocketRequest = {
cli: { quiet: boolean; timeout_ms: number | null };
} & ({ kind: 'op'; op: CliSocketOp; params: Record<string, unknown> } | { kind: 'recall'; args: string[] });
+/**
+ * GBRA-175: a handshake-only probe. The serve checks the identity exactly as for a request and answers the handshake
+ * line alone, running nothing, so `gbrain upgrade` can prove after a restart that the serve accepts this build.
+ */
+export interface CliSocketProbe { v: 1; kind: 'probe'; identity: CliSocketIdentity }
+
+export function isCliSocketProbe(value: unknown): value is CliSocketProbe {
+ return record(value) && value.v === CLI_SOCKET_PROTOCOL && value.kind === 'probe' && isCliSocketIdentity(value.identity);
+}
+
/** A refusal for `identity_mismatch` names the identity part that differed in `mismatch` (cliSocketIdentityMismatch), never its value. */
export type HandshakeFrame = { v: 1; accepted: true } | { v: 1; accepted: false; reason: string; mismatch?: string };
diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.ts
index ca19b9d04b..64e0902fa2 100644
--- a/src/core/cli-socket/server.ts
+++ b/src/core/cli-socket/server.ts
@@ -18,7 +18,7 @@ import { CliSocketUnsafeError, cliSocketDir, cliSocketPath, ensurePrivateDir, pr
import { cliSocketIdentity, cliSocketIdentityMismatch, type CliSocketIdentity } from './identity.ts';
import { installOutputCapture } from './output-capture.ts';
import { peerCredSupport, peerUid, type PeerCredSupport } from './peer-cred.ts';
-import { FrameReader, isCliSocketRequest, MAX_REQUEST_BYTES, MAX_RESPONSE_BYTES, MAX_ROUND_TRIP_MS, REQUEST_READ_TIMEOUT_MS,
+import { FrameReader, isCliSocketProbe, isCliSocketRequest, MAX_REQUEST_BYTES, MAX_RESPONSE_BYTES, MAX_ROUND_TRIP_MS, REQUEST_READ_TIMEOUT_MS,
type CliSocketRequest, type HandshakeFrame, type ResultFrame } from './protocol.ts';
const MAX_CONNECTIONS = 32;
@@ -158,6 +158,11 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promis
void (async () => {
let request: unknown;
try { request = JSON.parse(frames[0]!); } catch { request = null; }
+ if (isCliSocketProbe(request)) {
+ const mismatch = cliSocketIdentityMismatch(identity, request.identity);
+ socket.end(frame(mismatch ? { v: 1, accepted: false, reason: 'identity_mismatch', mismatch } : { v: 1, accepted: true }));
+ return;
+ }
if (!isCliSocketRequest(request)) { socket.end(frame({ v: 1, accepted: false, reason: 'malformed_request' })); return; }
const mismatch = cliSocketIdentityMismatch(identity, request.identity);
if (mismatch) {
diff --git a/src/core/config.ts b/src/core/config.ts
index 66067124f0..16d4288c96 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -284,6 +284,7 @@ export interface GBrainConfig {
*/
self_upgrade?: {
mode?: 'auto' | 'notify' | 'off';
+ channel?: 'latest' | 'stable';
/** Set true once the upgrade-time consent prompt has been shown. */
mode_prompted?: boolean;
/** Quiet-hours window for the autopilot silent channel. */
@@ -1658,6 +1659,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'skillpack.nag_disabled',
// Self-upgrade (v0.42; file plane, read on the hot path)
'self_upgrade.mode',
+ 'self_upgrade.channel',
'self_upgrade.mode_prompted',
'self_upgrade.quiet_hours',
'self_upgrade.failed_versions',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5daa31a51a..aeb8355c37 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -585,6 +585,8 @@ export const CODES = {
request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },
requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },
requires_local_engine: { class: 'host_only', summary: "This command needs the brain's local database, and this install is a thin client of a remote brain." },
+ restart_refused: { class: 'consent', exit: 3, actor: 'user', summary: "`gbrain upgrade` (or `--restart-only`) found a gbrain process on this host it cannot restart onto the new build (a serve or worker started by hand, an autopilot without its service, a running sync, or an MCP server an agent harness started), so it restarted nothing and, before a swap, installed nothing.", why: "A process keeps the build it started with, so restarting only some of them leaves serve, workers and MCP servers on different builds; the upgrade refuses instead of leaving that skew. Each process is named with the exact step that restarts it.", docs: 'docs/guides/upgrades-auto-update.md#restart', suggestion: 'Handle each listed process as the message says (MCP servers only: rerun with --stop-mcp after the user agrees), then run the same command again; `gbrain upgrade --no-restart` installs without restarting.', fix: { argv: ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every gbrain process on this host with its build and how each one restarts.', requires_exclusive: false } },
+ restart_unverified: { class: 'host_only', summary: "After `gbrain upgrade` restarted this host's gbrain processes, one of them still runs another build, did not come back, or the warm CLI socket refused the new build.", why: "The restart is done only when every gbrain process on the host reports the installed build and serve's warm CLI socket accepts it; anything less is the version skew the restart exists to remove.", docs: 'docs/guides/upgrades-auto-update.md#restart', suggestion: 'Restart each process the message lists with the command the plan printed, then run `gbrain upgrade --restart-only` again.', fix: { argv: ['gbrain', 'upgrade', '--restart-only', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists every gbrain process on this host with its build and how each one restarts.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json'] } } },
reset_upstream_refused: { class: 'caller', summary: "gbrain sources reset-upstream changed nothing: the checkout moved since the reset was proposed, has no upstream, has uncommitted tracked edits, or has local commits that were never on the upstream (named, with the backup ref a reset would create).", why: "The reset is bound to the HEAD and upstream the user agreed to and drops only commits the upstream once had; anything else needs the user's decision first.", reasons: ['expect_mismatch', 'no_upstream', 'dirty_tree', 'local_commits'], reason_overrides: { dirty_tree: { class: 'consent' }, local_commits: { class: 'consent' } }, docs: 'docs/guides/troubleshooting.md#upstream-rewritten' },
response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },
resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },
@@ -648,6 +650,7 @@ export const CODES = {
source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },
split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },
split_unparseable: { class: 'caller', summary: "Split unparseable." },
+ stable_channel_unresolved: { class: 'unavailable', reasons: ['unreadable', 'no_stable', 'no_release_tag'], summary: "`gbrain upgrade --channel stable` (or `self_upgrade.channel stable`) could not name the stable release: the repository's tags could not be read, no release has been promoted to stable yet, or the `stable` tag does not share a commit with a `v<version>` release tag. Nothing was changed.", why: "The stable channel installs only a release a maintainer promoted after the production-shaped soak passed on its exact tree; without that answer it installs nothing rather than guess.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel', suggestion: 'Retry later, or upgrade on the latest channel with `gbrain upgrade --channel latest`.' },
stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
storage_error: { class: 'server', summary: "Reading or writing durable storage failed.",
diff --git a/src/core/self-upgrade.ts b/src/core/self-upgrade.ts
index 43e921cc10..ff84d59afb 100644
--- a/src/core/self-upgrade.ts
+++ b/src/core/self-upgrade.ts
@@ -57,6 +57,24 @@ export const SNOOZE_DURATIONS_MS = [
export type SelfUpgradeMode = 'auto' | 'notify' | 'off';
+/**
+ * The release line an install follows. `latest` is every published release (the `latest-stable` tag release.yml
+ * advances); `stable` is the newest release a maintainer promoted after the production-shaped soak passed on its
+ * exact tree (the `stable` tag .github/workflows/promote-stable.yml advances). Set per brain home with
+ * `gbrain config set self_upgrade.channel stable`; `gbrain upgrade --channel <name>` overrides it for one run.
+ */
+export type ReleaseChannel = 'latest' | 'stable';
+export const RELEASE_CHANNELS: readonly ReleaseChannel[] = ['latest', 'stable'];
+
+export function normalizeChannel(raw: unknown): ReleaseChannel | null {
+ return raw === 'latest' || raw === 'stable' ? raw : null;
+}
+
+/** The configured channel (file plane), else `latest`. */
+export function resolveReleaseChannel(cfg: { self_upgrade?: { channel?: string } } | null | undefined): ReleaseChannel {
+ return normalizeChannel(cfg?.self_upgrade?.channel) ?? 'latest';
+}
+
export type SelfUpgradeChannel = 'invocation' | 'autopilot';
/**
@@ -517,6 +535,7 @@ export function readSwapReceipt(path: string): SwapReceipt | null {
/** The mutable slice of `config.self_upgrade` the autopilot channel manages. */
export interface SelfUpgradeState {
mode?: SelfUpgradeMode;
+ channel?: ReleaseChannel;
mode_prompted?: boolean;
quiet_hours?: { start?: number; end?: number; tz?: string };
failed_versions?: string[];
@@ -636,6 +655,7 @@ export function resolveQuietHoursWindow(
* would be accepted and never read (#5489). */
export const SELF_UPGRADE_CONFIG_LEAVES = [
'mode',
+ 'channel',
'mode_prompted',
'quiet_hours',
'failed_versions',
@@ -737,6 +757,10 @@ export function parseSelfUpgradeConfigValue(leaf: SelfUpgradeConfigLeaf, raw: st
const mode = normalizeMode(raw.trim());
return mode ? { ok: true, value: mode } : { ok: false, error: `must be auto, notify or off (got '${raw}')` };
}
+ case 'channel': {
+ const channel = normalizeChannel(raw.trim());
+ return channel ? { ok: true, value: channel } : { ok: false, error: `must be latest or stable (got '${raw}')` };
+ }
case 'mode_prompted': {
if (isConfigTruthy(raw)) return { ok: true, value: true };
if (['false', '0', 'no', 'off'].includes(raw.trim().toLowerCase())) return { ok: true, value: false };
diff --git a/src/core/serve-service.ts b/src/core/serve-service.ts
index 6498dd95ea..f92acca230 100644
--- a/src/core/serve-service.ts
+++ b/src/core/serve-service.ts
@@ -50,6 +50,13 @@ export function serveErrPath(dir: string = serveDir()): string { return join(dir
export function launchdPlistPath(home: string): string { return join(home, 'Library', 'LaunchAgents', `${SERVE_LAUNCHD_LABEL}.plist`); }
export function systemdUnitPath(home: string): string { return join(home, '.config', 'systemd', 'user', SERVE_SYSTEMD_UNIT); }
+/** The installed serve service's restart command on this platform; null when no serve service is installed. */
+export function serveServiceRestartArgv(service: { platform: string; home: string; uid: number }): string[] | null {
+ if (service.platform === 'darwin' && existsSync(launchdPlistPath(service.home))) return ['launchctl', 'kickstart', '-k', `gui/${service.uid}/${SERVE_LAUNCHD_LABEL}`];
+ if (service.platform === 'linux' && existsSync(systemdUnitPath(service.home))) return ['systemctl', '--user', 'restart', SERVE_SYSTEMD_UNIT];
+ return null;
+}
+
// ---------------------------------------------------------------------------
// Target detection (pure — probe results are passed in)
// ---------------------------------------------------------------------------
diff --git a/src/core/upgrade-restart.ts b/src/core/upgrade-restart.ts
new file mode 100644
index 0000000000..8c5e38fda3
--- /dev/null
+++ b/src/core/upgrade-restart.ts
@@ -0,0 +1,348 @@
+/**
+ * GBRA-175: one upgrade restarts every gbrain process the brain runs on this
+ * host, or refuses with the exact step for each process it cannot restart, and
+ * then proves that every process reports one build and that the warm CLI
+ * socket accepts it. A long-running process keeps the code it loaded at start
+ * (#7245), so an upgrade that restarts nothing leaves serve, the jobs
+ * supervisor and its worker, autopilot and every MCP server on the old build
+ * while one-shot commands and job children run the new one.
+ *
+ * Three steps, each with its side effects behind an interface so tests drive
+ * them with fakes:
+ *
+ * - `collectHostProcesses`: the processes this brain runs on this host. The
+ * process table is the authority on what runs (role by command line, every
+ * ancestor pid, start time, the version the process's install holds; on
+ * Linux only processes whose GBRAIN_HOME is this brain's); the consumer
+ * heartbeat rows (Postgres), the supervisor PID file and the worker registry
+ * add the build each pid loaded, and a record whose pid the table does not
+ * list as a gbrain process is stale and dropped. Read-only.
+ * - `planRestart`: which processes are not on the installed build and how each
+ * restarts: serve and autopilot through their installed service, only when
+ * the service's own process runs them; the supervisor with `jobs supervisor
+ * stop` and `start --detach` with the options it was launched with (its
+ * worker restarts with it); an MCP stdio server by stopping it when
+ * `--stop-mcp` says so (its harness starts the new build on reconnect).
+ * Anything else is a manual step, and any manual step refuses the whole
+ * restart before anything changes.
+ * - `runRestartSteps` then `verifyRestart`: run the steps in that order, then
+ * poll until no restarted pid is alive, every process reports the installed
+ * build (or, reporting none, started after the restart from an install that
+ * holds it), each restarted role and supervised worker came back, and the
+ * warm CLI socket, when serve had one, accepts this build.
+ */
+import { basename, resolve } from 'node:path';
+
+export type ProcessRole = 'serve' | 'autopilot' | 'supervisor' | 'worker' | 'mcp' | 'sync';
+
+export interface HostProcess {
+ pid: number;
+ /** The nearest gbrain process above it in the process table; null when none is. */
+ ppid: number | null;
+ role: ProcessRole;
+ /** The build the process runs (in memory); null when it records none. */
+ version: string | null;
+ /** Epoch ms the process started; null when unknown. */
+ started_ms: number | null;
+ /** Every pid above it in the process table, nearest first (which service runs it). */
+ ancestors?: number[];
+ /** Its arguments after the gbrain entry point, from the process table; absent when the table did not list it. */
+ args?: string[];
+ /** The version the install it was started from holds now; null when unknown (a compiled binary). */
+ install_version?: string | null;
+}
+
+export interface ProcessTableRow { pid: number; ppid: number; command: string; started_ms: number | null; gbrain_home: string | null | undefined }
+
+export interface ProcessSources {
+ /** Live consumer heartbeat rows on this host (Postgres only; PGLite keeps none). */
+ heartbeats: () => Promise<Array<{ pid: number; kind: string; version: string | null }>>;
+ supervisor: () => { pid: number; version: string | null } | null;
+ workers: () => Array<{ pid: number; version: string | null }>;
+ /** This user's processes, null when ps cannot run; `gbrain_home` is the GBRAIN_HOME (else HOME) from the process's environment, undefined when unreadable. */
+ processTable: () => ProcessTableRow[] | null;
+ /** The version the install a command line starts from holds now; null when unknown. */
+ installVersion?: (command: string) => string | null;
+ /** This brain's GBRAIN_HOME (else HOME), resolved. */
+ home: string;
+ /** Pids never listed: this process and its parents (the upgrade that spawned it). */
+ exclude: readonly number[];
+}
+
+const SERVE_SUBCOMMANDS_TRANSIENT = new Set(['status', 'install', 'uninstall', 'stop', 'logs', 'help']);
+/** `gbrain autopilot` forms that report or change the service and exit; anything else is the daemon (`--repo <path>`, `start`). */
+const AUTOPILOT_TRANSIENT = new Set(['status', 'install', 'uninstall', 'pause', 'resume', 'help']);
+const INTERPRETERS = new Set(['bun', 'node']);
+
+/**
+ * The gbrain entry point of a command line and the arguments after it, or null when the command is not gbrain
+ * itself: a wrapper that starts gbrain as its child (tini, a shell, `timeout`) is not the gbrain process.
+ */
+export function gbrainEntry(command: string): { entry: string; args: string[] } | null {
+ const tokens = command.trim().split(/\s+/);
+ const at = tokens.findIndex(token => /(^|\/)gbrain$/.test(token) || /gbrain[^\s]*\/src\/cli\.ts$/.test(token));
+ if (at === -1 || (at > 0 && !INTERPRETERS.has(basename(tokens[0]!)))) return null;
+ return { entry: tokens[at]!, args: tokens.slice(at + 1) };
+}
+
+/** The role of a gbrain command line, or null when it is not a long-running gbrain process. */
+export function classifyGbrainCommand(command: string): ProcessRole | null {
+ const args = gbrainEntry(command)?.args;
+ if (!args) return null;
+ const [sub, second] = args.filter(arg => !arg.startsWith('-'));
+ if (sub === 'serve') {
+ if (second && SERVE_SUBCOMMANDS_TRANSIENT.has(second)) return null;
+ return args.includes('--http') ? 'serve' : 'mcp';
+ }
+ if (sub === 'jobs' && second === 'work') return 'worker';
+ if (sub === 'jobs' && second === 'supervisor') return args.some(arg => arg === 'stop' || arg === 'status') ? null : 'supervisor';
+ if (sub === 'autopilot') return args.some(arg => AUTOPILOT_TRANSIENT.has(arg.replace(/^--/, ''))) ? null : 'autopilot';
+ if (sub === 'sync') return 'sync';
+ return null;
+}
+
+const HEARTBEAT_ROLES: Record<string, ProcessRole> = { serve: 'serve', jobs: 'worker', autopilot: 'autopilot', mcp: 'mcp', sync: 'sync' };
+
+/** Every gbrain process this brain runs on this host, one per pid. */
+export async function collectHostProcesses(sources: ProcessSources): Promise<HostProcess[]> {
+ const byPid = new Map<number, HostProcess>();
+ const excluded = new Set(sources.exclude);
+ const table = sources.processTable();
+ const rows = new Map((table ?? []).map(row => [row.pid, row]));
+ const ancestry = (ppid: number) => {
+ const chain: number[] = [];
+ for (let pid = ppid; pid > 1 && chain.length < 64 && !chain.includes(pid); pid = rows.get(pid)?.ppid ?? 0) chain.push(pid);
+ return chain;
+ };
+ for (const row of table ?? []) {
+ if (excluded.has(row.pid)) continue;
+ if (row.gbrain_home !== undefined && row.gbrain_home !== null && resolve(row.gbrain_home) !== resolve(sources.home)) continue;
+ const role = classifyGbrainCommand(row.command);
+ if (!role) continue;
+ byPid.set(row.pid, { pid: row.pid, ppid: null, role, version: null, started_ms: row.started_ms, ancestors: ancestry(row.ppid),
+ args: gbrainEntry(row.command)!.args, install_version: sources.installVersion?.(row.command) ?? null });
+ }
+ const merge = (pid: number, role: ProcessRole | null, version: string | null) => {
+ if (excluded.has(pid)) return;
+ const known = byPid.get(pid);
+ if (known) {
+ if (role === 'supervisor' || role === 'worker') known.role = role;
+ known.version = version ?? known.version;
+ } else if (role && table === null) {
+ byPid.set(pid, { pid, ppid: null, role, version, started_ms: null });
+ }
+ };
+ for (const row of await sources.heartbeats()) merge(row.pid, HEARTBEAT_ROLES[row.kind] ?? null, row.version || null);
+ for (const worker of sources.workers()) merge(worker.pid, 'worker', worker.version);
+ const supervisor = sources.supervisor();
+ if (supervisor) merge(supervisor.pid, 'supervisor', supervisor.version);
+ for (const p of byPid.values()) p.ppid = p.ancestors?.find(pid => byPid.has(pid)) ?? null;
+ return [...byPid.values()].sort((a, b) => a.pid - b.pid);
+}
+
+/** An installed service: its restart command and the pid its manager runs now (null when it is not running). */
+export interface ServiceHandle { argv: string[]; pid: number | null }
+
+export interface RestartContext {
+ /** The installed build every process must run. */
+ expected: string;
+ /** The installed serve service; null when none is installed. */
+ serveService: ServiceHandle | null;
+ /** The installed autopilot service; null when none is installed. */
+ autopilotService: ServiceHandle | null;
+ /** Stop MCP stdio servers (their harness starts the new build on reconnect) instead of refusing. */
+ stopMcp: boolean;
+}
+
+export type RestartStep =
+ | { kind: 'service'; role: 'serve' | 'autopilot'; argv: string[]; pids: number[] }
+ | { kind: 'supervisor'; pid: number; workers: number[]; stop: string[]; start: string[]; pid_file: string | null }
+ | { kind: 'stop'; role: 'mcp'; pid: number; started_ms: number | null };
+
+export interface ManualStep { role: ProcessRole; pid: number; version: string | null; argv: string[]; instruction: string }
+
+export interface RestartPlan {
+ expected: string;
+ /** Processes already on the installed build; left running. */
+ current: HostProcess[];
+ /** Processes on another build, or reporting none. */
+ stale: HostProcess[];
+ steps: RestartStep[];
+ manual: ManualStep[];
+}
+
+const label = (p: Pick<HostProcess, 'role' | 'pid' | 'version'>) => `${p.role} pid ${p.pid} (${p.version ? `v${p.version}` : 'build not recorded'})`;
+
+/** The supervisor's stop and start commands from the arguments it runs with, so the restart keeps its queue, concurrency and PID file. */
+export function supervisorRestartArgv(args: readonly string[]): { stop: string[]; start: string[]; pid_file: string | null } {
+ const rest = args.slice(args.indexOf('supervisor') + 1).filter(arg => arg !== 'start' && arg !== '--detach' && arg !== '--json');
+ const at = rest.findIndex(arg => arg === '--pid-file' || arg.startsWith('--pid-file='));
+ const pidFile = at === -1 ? null : rest[at]!.includes('=') ? rest[at]!.slice('--pid-file='.length) : rest[at + 1] ?? null;
+ return {
+ stop: ['gbrain', 'jobs', 'supervisor', 'stop', ...(pidFile ? ['--pid-file', pidFile] : []), '--json'],
+ start: ['gbrain', 'jobs', 'supervisor', 'start', '--detach', ...rest, '--json'],
+ pid_file: pidFile,
+ };
+}
+
+export function planRestart(processes: readonly HostProcess[], ctx: RestartContext): RestartPlan {
+ const stale = processes.filter(p => p.version !== ctx.expected);
+ const current = processes.filter(p => p.version === ctx.expected);
+ const manual: ManualStep[] = [];
+ const services = new Map<'serve' | 'autopilot', number[]>();
+ const supervisors = new Map<number, number[]>();
+ const stops: RestartStep[] = [];
+ const byPid = new Map(processes.map(p => [p.pid, p]));
+ const addService = (role: 'serve' | 'autopilot', pid: number) => services.set(role, [...(services.get(role) ?? []), pid]);
+ const runsUnder = (p: HostProcess, service: ServiceHandle | null) => !!service && service.pid !== null && (p.pid === service.pid || !!p.ancestors?.includes(service.pid));
+ const kill = (p: HostProcess, instruction: string) => manual.push({ role: p.role, pid: p.pid, version: p.version, argv: ['kill', String(p.pid)], instruction });
+
+ for (const p of stale) {
+ const parent = p.ppid === null ? undefined : byPid.get(p.ppid);
+ switch (p.role) {
+ case 'serve':
+ if (runsUnder(p, ctx.serveService)) addService('serve', p.pid);
+ else kill(p, `${label(p)} was not started by the installed serve service${ctx.serveService ? (ctx.serveService.pid === null ? ' (the service is not running)' : ` (the service runs pid ${ctx.serveService.pid})`) : ''}: stop it (\`kill ${p.pid}\`, SIGTERM drains it) and start it again the way it was launched.`);
+ break;
+ case 'autopilot':
+ if (runsUnder(p, ctx.autopilotService)) addService('autopilot', p.pid);
+ else kill(p, `${label(p)} does not run under an installed autopilot service: stop it (\`kill ${p.pid}\`) and start it again the way it was launched (\`gbrain autopilot --install\` installs the service).`);
+ break;
+ case 'supervisor':
+ if (p.args) supervisors.set(p.pid, supervisors.get(p.pid) ?? []);
+ else kill(p, `${label(p)}: its launch options could not be read from the process table, so it is not restarted with defaults: stop it (\`gbrain jobs supervisor stop\`) and start it again the way it was launched.`);
+ break;
+ case 'worker':
+ if (parent?.role === 'supervisor' && parent.args) supervisors.set(parent.pid, [...(supervisors.get(parent.pid) ?? []), p.pid]);
+ else if (parent?.role === 'autopilot' && runsUnder(parent, ctx.autopilotService)) addService('autopilot', parent.pid);
+ else kill(p, `${label(p)} is not run by a jobs supervisor this restart can relaunch${parent?.role === 'autopilot' ? ' (its autopilot runs under no installed service)' : ''}: stop it (\`kill ${p.pid}\`, SIGTERM drains its jobs) and start \`gbrain jobs work\` again the way it was launched, or run workers under \`gbrain jobs supervisor start --detach\`.`);
+ break;
+ case 'mcp':
+ if (ctx.stopMcp && p.args) stops.push({ kind: 'stop', role: 'mcp', pid: p.pid, started_ms: p.started_ms });
+ else if (ctx.stopMcp) kill(p, `${label(p)} is known only from its heartbeat row (the process table could not be read), so it is not signalled: stop it yourself if it is a gbrain MCP server, and reconnect gbrain in its harness afterwards.`);
+ else kill(p, `${label(p)} is an MCP server an agent harness started: rerun with --stop-mcp to stop it during the restart and reconnect gbrain in that harness afterwards (Claude Code: /mcp, then reconnect; other harnesses: start a new session).`);
+ break;
+ case 'sync':
+ manual.push({ role: p.role, pid: p.pid, version: p.version, argv: ['gbrain', 'sync', 'status', '--json'],
+ instruction: `${label(p)} is a running gbrain sync: let it finish (\`gbrain sync status --json\` shows its progress), then run the restart again.` });
+ break;
+ }
+ }
+ const steps: RestartStep[] = [];
+ const serve = services.get('serve');
+ if (serve && ctx.serveService) steps.push({ kind: 'service', role: 'serve', argv: ctx.serveService.argv, pids: [...new Set(serve)] });
+ const autopilot = services.get('autopilot');
+ if (autopilot && ctx.autopilotService) steps.push({ kind: 'service', role: 'autopilot', argv: ctx.autopilotService.argv, pids: [...new Set(autopilot)] });
+ for (const [pid, workers] of supervisors) steps.push({ kind: 'supervisor', pid, workers, ...supervisorRestartArgv(byPid.get(pid)!.args!) });
+ steps.push(...stops);
+ return { expected: ctx.expected, current, stale, steps, manual };
+}
+
+export interface RestartExecutor {
+ run: (argv: string[]) => { status: number | null; output: string };
+ /** SIGTERM the MCP server at pid only if it is still the process the plan saw: 'changed' when the pid now names another process. */
+ terminate: (pid: number, startedMs: number | null) => 'stopped' | 'gone' | 'changed';
+ /** The live supervisor's pid now (read from its PID file, the default one when null), or null. */
+ supervisorPid: (pidFile: string | null) => number | null;
+ sleep: (ms: number) => Promise<void>;
+}
+
+export interface StepResult { step: RestartStep; ok: boolean; detail: string }
+
+const SUPERVISOR_RESPAWN_GRACE_MS = 3_000;
+const failed = (argv: string[], r: { status: number | null; output: string }) => `\`${argv.join(' ')}\` exited ${r.status ?? 'without a status'}: ${r.output.trim().split('\n')[0] ?? ''}`;
+
+export async function runRestartSteps(plan: RestartPlan, exec: RestartExecutor): Promise<StepResult[]> {
+ const results: StepResult[] = [];
+ for (const step of plan.steps) {
+ if (step.kind === 'service') {
+ const r = exec.run(step.argv);
+ results.push({ step, ok: r.status === 0, detail: r.status === 0 ? `ran \`${step.argv.join(' ')}\`` : failed(step.argv, r) });
+ } else if (step.kind === 'supervisor') {
+ const stop = exec.run(step.stop);
+ if (stop.status !== 0) { results.push({ step, ok: false, detail: failed(step.stop, stop) }); continue; }
+ await exec.sleep(SUPERVISOR_RESPAWN_GRACE_MS);
+ const respawned = exec.supervisorPid(step.pid_file);
+ if (respawned !== null && respawned !== step.pid) {
+ results.push({ step, ok: true, detail: `stopped supervisor pid ${step.pid}; its service manager started pid ${respawned}` });
+ continue;
+ }
+ const start = exec.run(step.start);
+ results.push({ step, ok: start.status === 0, detail: start.status === 0 ? `stopped supervisor pid ${step.pid} and started it again with \`${step.start.join(' ')}\`` : failed(step.start, start) });
+ } else {
+ const outcome = exec.terminate(step.pid, step.started_ms);
+ results.push({ step, ok: outcome !== 'changed', detail: outcome === 'changed'
+ ? `pid ${step.pid} is no longer the MCP server the plan saw, so it was not signalled`
+ : `stopped mcp pid ${step.pid}; reconnect gbrain in its harness` });
+ }
+ }
+ return results;
+}
+
+/** `mismatch` names the identity part an `identity_mismatch` refusal differed on (`version`, `env GBRAIN_MODEL`, ...). */
+export type WarmSocketState = { state: 'absent' } | { state: 'accepted' } | { state: 'refused'; reason: string; mismatch?: string };
+
+/** A refusal for anything but a non-version identity part means serve does not accept this build; an env or config difference is this shell's, not the upgrade's. */
+function refusesThisBuild(warm: WarmSocketState): boolean {
+ return warm.state === 'refused' && !(warm.reason === 'identity_mismatch' && warm.mismatch && warm.mismatch !== 'version');
+}
+
+const restartedPids = (plan: RestartPlan) => new Set(plan.steps.flatMap(step => step.kind === 'service' ? step.pids : step.kind === 'supervisor' ? [step.pid, ...step.workers] : [step.pid]));
+
+/** What still stands between the host and one build after a restart; empty when it is done. */
+export function restartProblems(plan: RestartPlan, processes: readonly HostProcess[], restartStartedMs: number,
+ warm: { before: WarmSocketState; after: WarmSocketState }): string[] {
+ const problems: string[] = [];
+ const live = new Map(processes.map(p => [p.pid, p]));
+ const restarted = restartedPids(plan);
+ for (const pid of restarted) {
+ const p = live.get(pid);
+ if (p) problems.push(`${label(p)} is still running after the restart.`);
+ }
+ const fresh = processes.filter(p => !restarted.has(p.pid));
+ for (const p of fresh) {
+ if (p.version && p.version !== plan.expected) problems.push(`${label(p)} runs a build other than v${plan.expected}.`);
+ else if (!p.version && p.install_version && p.install_version !== plan.expected) problems.push(`${label(p)} reports no build and was started from an install that holds v${p.install_version}.`);
+ else if (!p.version && (p.started_ms === null || p.started_ms < restartStartedMs)) problems.push(`${label(p)} reports no build and started before the restart.`);
+ }
+ for (const step of plan.steps) {
+ if (step.kind === 'stop') continue;
+ const role = step.kind === 'service' ? step.role : 'supervisor';
+ if (!fresh.some(p => p.role === role)) {
+ problems.push(`${role} did not come back after ${step.kind === 'service' ? `\`${step.argv.join(' ')}\`` : 'the supervisor restart'}.`);
+ } else if (step.kind === 'supervisor' && step.workers.length && !fresh.some(p => p.role === 'worker' && live.get(p.ppid ?? -1)?.role === 'supervisor' && !restarted.has(p.ppid!))) {
+ problems.push(`the jobs worker did not come back under the restarted supervisor (\`${step.start.join(' ')}\`).`);
+ }
+ }
+ if (warm.after.state === 'refused' && refusesThisBuild(warm.after)) problems.push(`The warm CLI socket refused this build (${warm.after.reason}${warm.after.mismatch ? `: ${warm.after.mismatch}` : ''}).`);
+ else if (warm.before.state !== 'absent' && warm.after.state === 'absent') problems.push('The warm CLI socket serve had before the restart is gone.');
+ return problems;
+}
+
+/** Processes that pass verification only by their start time: they record no build and their install's version is unknown (a compiled binary). */
+export function unverifiedBuilds(plan: RestartPlan, processes: readonly HostProcess[]): string[] {
+ const restarted = restartedPids(plan);
+ return processes.filter(p => !restarted.has(p.pid) && !p.version && !p.install_version)
+ .map(p => `${label(p)} started after the restart but records no build, so its build is inferred from its start time.`);
+}
+
+export interface VerifyDeps {
+ collect: () => Promise<HostProcess[]>;
+ probeWarmSocket: () => Promise<WarmSocketState>;
+ sleep: (ms: number) => Promise<void>;
+ now: () => number;
+}
+
+export interface VerifyResult { ok: boolean; processes: HostProcess[]; warm_socket: WarmSocketState; problems: string[]; unverified: string[] }
+
+export async function verifyRestart(plan: RestartPlan, restartStartedMs: number, warmBefore: WarmSocketState, deps: VerifyDeps,
+ opts: { timeoutMs: number; pollMs: number }): Promise<VerifyResult> {
+ const deadline = deps.now() + opts.timeoutMs;
+ for (;;) {
+ const processes = await deps.collect();
+ const warm = await deps.probeWarmSocket();
+ const problems = restartProblems(plan, processes, restartStartedMs, { before: warmBefore, after: warm });
+ if (!problems.length || deps.now() >= deadline) return { ok: !problems.length, processes, warm_socket: warm, problems, unverified: unverifiedBuilds(plan, processes) };
+ await deps.sleep(opts.pollMs);
+ }
+}
diff --git a/test/check-update-refresh.serial.test.ts b/test/check-update-refresh.serial.test.ts
index 9a26cd255a..9dcfd22445 100644
--- a/test/check-update-refresh.serial.test.ts
+++ b/test/check-update-refresh.serial.test.ts
@@ -10,7 +10,7 @@
* `fetch` (cross-file-unsafe under the parallel runner).
*/
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { VERSION } from '../src/version.ts';
@@ -77,6 +77,24 @@ describe('fetchLatestRelease — resolves from the VERSION file, discriminates f
stubVersionFetch('<html>rate limited</html>');
expect(await fetchLatestRelease()).toEqual({ ok: false, reason: 'no_releases' });
});
+
+ test('GBRA-175: the stable channel reads VERSION at the stable tag, from the argument or self_upgrade.channel', async () => {
+ const urls: string[] = [];
+ globalThis.fetch = (async (url: any) => {
+ urls.push(String(url));
+ return new Response(String(url).includes('/gbrain/stable/VERSION') ? '0.99.0.0\n' : '0.99.9.0\n', { status: 200 });
+ }) as typeof fetch;
+ expect(await fetchLatestRelease('stable')).toMatchObject({ ok: true, tag: '0.99.0.0' });
+ expect(await fetchLatestRelease()).toMatchObject({ ok: true, tag: '0.99.9.0' });
+ mkdirSync(join(homeDir, '.gbrain'), { recursive: true });
+ writeFileSync(join(homeDir, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(homeDir, 'brain.pglite'), self_upgrade: { channel: 'stable' } }));
+ expect(await fetchLatestRelease()).toMatchObject({ ok: true, tag: '0.99.0.0' });
+ expect(urls).toEqual([
+ 'https://raw.githubusercontent.com/garrytan/gbrain/stable/VERSION',
+ 'https://raw.githubusercontent.com/garrytan/gbrain/latest-stable/VERSION',
+ 'https://raw.githubusercontent.com/garrytan/gbrain/stable/VERSION',
+ ]);
+ });
});
describe('parseVersionFileBody — shape gate over the raw fetch body', () => {
diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.ts
index 39d0fbc76d..0831e1ee03 100644
--- a/test/cli-socket.test.ts
+++ b/test/cli-socket.test.ts
@@ -336,6 +336,22 @@ describe('serve listener', () => {
expect(started.lines.filter(line => line.includes('identity_mismatch')).length).toBe(2);
});
+ test('GBRA-175: a probe gets the handshake alone, runs nothing, and names a version mismatch', async () => {
+ let executed = 0;
+ const { path } = await start({ execute: async () => { executed++; return { frame: okFrame, settled: Promise.resolve() }; } });
+ const probe = (identity: CliSocketIdentity) => new Promise<unknown[]>((resolveFrames, reject) => {
+ const socket = net.createConnection(path);
+ let text = '';
+ socket.on('data', data => { text += data.toString(); });
+ socket.once('error', reject);
+ socket.once('close', () => resolveFrames(text.trim().split('\n').filter(Boolean).map(line => JSON.parse(line))));
+ socket.once('connect', () => socket.write(JSON.stringify({ v: 1, kind: 'probe', identity }) + '\n'));
+ });
+ expect(await probe(serveIdentity())).toEqual([{ v: 1, accepted: true }]);
+ expect(await probe({ ...serveIdentity(), version: '1.0.1' })).toEqual([{ v: 1, accepted: false, reason: 'identity_mismatch', mismatch: 'version' }]);
+ expect(executed).toBe(0);
+ });
+
test('rejects a peer whose kernel uid differs, and one whose uid cannot be read', async () => {
let calls = 0;
// The first read is the start-up self-test on this process's own connection.
diff --git a/test/doctor-runtime-build-skew.test.ts b/test/doctor-runtime-build-skew.test.ts
index 2e0075f5ab..9ee31f34ef 100644
--- a/test/doctor-runtime-build-skew.test.ts
+++ b/test/doctor-runtime-build-skew.test.ts
@@ -58,15 +58,18 @@ describe('doctor runtime_build_skew', () => {
workers: [{ pid: 5151, version: OLD, install_root: INSTALL }],
supervisor: { pid: 6161, version: OLD, install_root: INSTALL },
}), service);
- expect(check.status).toBe('warn');
+ expect(check.status).toBe('fail');
expect(check.message).toStartWith(`runtime_build_skew: 3 gbrain builds are running on this host (newest v${VERSION})`);
expect(check.message).toContain(`serve pid 4242 v${OLDER}`);
expect(check.message).toContain(`supervisor pid 6161 v${OLD} (its install now holds v${VERSION})`);
expect(check.message).toContain(`worker pid 5151 v${OLD} (its install now holds v${VERSION})`);
expect(check.message).toContain(`job children of worker pid 5151 ran v${VERSION} (jobs #11, #12)`);
- const fix = check.fix as { argv: string[]; actor: string; verify: { argv: string[] } };
- expect(fix.argv).toEqual(['kill', '4242']);
- expect(fix.actor).toBe('user');
+ const fix = check.fix as { argv: string[]; actor: string; ask_user?: boolean; user_message: string; verify: { argv: string[] } };
+ expect(fix.argv).toEqual(['gbrain', 'upgrade', '--restart-only']);
+ expect(fix.actor).toBe('agent');
+ expect(fix.ask_user).toBe(true);
+ expect(fix.user_message).toContain(`serve pid 4242 v${OLDER}`);
+ expect(check.message).toContain('By hand: restart with `kill 4242`');
expect(fix.verify.argv).toEqual(['gbrain', 'doctor', '--only', 'runtime_build_skew', '--json']);
expect(check.details).toMatchObject({ count: 3, newest: VERSION, earlier_job_children: 0 });
expect(JSON.stringify(check)).not.toContain(INSTALL);
@@ -86,14 +89,15 @@ describe('doctor runtime_build_skew', () => {
const check = await runtimeBuildSkewCheck(stub([]).engine, HOST, sources({ workers: [{ pid: 5151, version: OLD, install_root: INSTALL }] }), service);
expect(check.status).toBe('warn');
expect(check.message).toStartWith(`runtime_build_skew: a gbrain process runs an older build than its install (newest v${OLD})`);
- expect((check.fix as { argv: string[] }).argv).toEqual(['kill', '5151']);
+ expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'upgrade', '--restart-only']);
+ expect(check.message).toContain('By hand: restart with `kill 5151`');
});
test('a stale supervisor is restarted before its worker', async () => {
const check = await runtimeBuildSkewCheck(stub([heartbeat()]).engine, HOST, sources({
workers: [{ pid: 5151, version: OLD, install_root: INSTALL }], supervisor: { pid: 6161, version: OLD, install_root: INSTALL } }), service);
- expect(check.status).toBe('warn');
- expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'jobs', 'supervisor', 'stop']);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain('By hand: restart with `gbrain jobs supervisor stop`');
expect(check.message).toContain('gbrain jobs supervisor start --detach');
});
@@ -125,7 +129,7 @@ describe('doctor runtime_build_skew on PGLite', () => {
const job = await queue.add('sync', {});
await engine.executeRaw(`UPDATE minion_jobs SET stacktrace = jsonb_build_array('earlier failure', $1::text) WHERE id = $2`, [childLine(process.pid, OLD), job.id]);
const check = await runtimeBuildSkewCheck(engine as unknown as BrainEngine, HOST, sources({ workers: [{ pid: process.pid, version: OLD, install_root: INSTALL }] }), service);
- expect(check.status).toBe('warn');
+ expect(check.status).toBe('fail');
expect(check.details).toMatchObject({ job_children: [{ job_id: job.id, child_version: VERSION, worker_pid: process.pid, worker_version: OLD, refused: false }] });
expect(check.message).toContain(`job children of worker pid ${process.pid} ran v${VERSION} (jobs #${job.id})`);
});
diff --git a/test/scripts/promote-stable.test.ts b/test/scripts/promote-stable.test.ts
new file mode 100644
index 0000000000..6d7f28cf84
--- /dev/null
+++ b/test/scripts/promote-stable.test.ts
@@ -0,0 +1,458 @@
+/**
+ * .github/workflows/promote-stable.yml + scripts/promote-stable.ts — the
+ * stable channel.
+ *
+ * Protects: `stable` moves only for an admin or maintainer, only to an
+ * existing, published v<VERSION> release whose exact git tree passed a
+ * completed, successful run of the configured soak workflow, only forward
+ * unless a rollback names its reason, with the immutable stable-v<VERSION>
+ * record created once and pushed atomically with the leased `stable` move. Regressions it
+ * catches: accepting a soak of a different tree or workflow, a run from
+ * another repository, a no-op or silent downgrade, re-creating a record tag,
+ * a changed tag message contract, and the workflow interpolating inputs
+ * into shell or growing a trigger other than workflow_dispatch.
+ */
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { load } from 'js-yaml';
+import {
+ checkOrder, checkSoakRun, compareVersions, normaliseWorkflowPath, parseRunUrl, processDeps, promote, Refusal, renderSummary, renderTagMessage,
+ type GitResult, type PromoteDeps, type PromoteInputs, type SoakRun, type TagFields,
+} from '../../scripts/promote-stable.ts';
+
+const ROOT = join(import.meta.dir, '..', '..');
+const REPO = 'garrytan/gbrain';
+const RUN_URL = `https://github.com/${REPO}/actions/runs/123456`;
+const SOAK = '.github/workflows/soak.yml';
+const sha = (c: string) => c.repeat(40);
+const NOW = new Date('2026-10-21T17:00:00.123Z');
+
+const refused = (fn: () => unknown, pattern: RegExp) => {
+ let error: unknown;
+ try { fn(); } catch (e) { error = e; }
+ expect(error).toBeInstanceOf(Refusal);
+ expect((error as Error).message).toMatch(pattern);
+};
+const refusedAsync = async (p: Promise<unknown>, pattern: RegExp) => {
+ const error = await p.then(() => null, e => e);
+ expect(error).toBeInstanceOf(Refusal);
+ expect((error as Error).message).toMatch(pattern);
+};
+
+interface FakeRepo {
+ commits: Record<string, string>;
+ tags: Record<string, { commit: string; object?: string; message?: string }>;
+ remote?: Record<string, string>;
+ /** What `git show v<version>:VERSION` prints; default: the tag's own version. */
+ versionFile?: string;
+ failPush?: boolean;
+}
+
+const ok = (stdout = ''): GitResult => ({ code: 0, stdout: `${stdout}\n`, stderr: '' });
+const fail: GitResult = { code: 1, stdout: '', stderr: 'fatal: bad revision' };
+
+function fakeGit(repo: FakeRepo, calls: string[]) {
+ let objects = 0;
+ const resolve = (spec: string): { commit: string; object: string } | null => {
+ const ref = spec.replace(/^refs\/tags\//, '');
+ const tag = repo.tags[ref];
+ if (tag) return { commit: tag.commit, object: tag.object ?? tag.commit };
+ return repo.commits[spec] ? { commit: spec, object: spec } : null;
+ };
+ return async (args: string[]): Promise<GitResult> => {
+ calls.push(args.join(' '));
+ const [cmd, ...rest] = args;
+ if (cmd === 'rev-parse') {
+ const spec = rest.at(-1)!;
+ const m = /^(.*?)(\^\{(commit|tree)\})?$/.exec(spec)!;
+ const hit = resolve(m[1]!);
+ if (!hit) return fail;
+ if (m[3] === 'tree') return ok(repo.commits[hit.commit]!);
+ return ok(m[3] === 'commit' ? hit.commit : hit.object);
+ }
+ if (cmd === 'tag' && rest[0] === '--points-at') {
+ return ok(Object.entries(repo.tags).filter(([n, t]) => t.commit === rest[1] && n.startsWith('v')).map(([n]) => n).join('\n'));
+ }
+ if (cmd === 'tag' && rest[0] === '-a') {
+ const message = rest[rest.indexOf('-m') + 1]!;
+ const [name, commit] = rest.slice(-2) as [string, string];
+ if (repo.tags[name] && !rest.includes('-f')) return fail;
+ repo.tags[name] = { commit, object: `tagobj-${name}-${++objects}`, message };
+ return ok();
+ }
+ if (cmd === 'push') {
+ const names = rest.filter(a => a.includes(':') && !a.startsWith('--')).map(r => r.split(':')[0]!.replace(/^refs\/tags\//, ''));
+ const lease = rest.find(a => a.startsWith('--force-with-lease='));
+ repo.remote ??= {};
+ if (repo.failPush) return { code: 1, stdout: '', stderr: 'fatal: the remote end hung up unexpectedly' };
+ if (lease && lease.split(':').at(-1) !== (repo.remote.stable ?? '')) return { code: 1, stdout: '', stderr: '! [rejected] stable -> stable (stale info)' };
+ for (const name of names) repo.remote[name] = repo.tags[name]!.object!;
+ return ok();
+ }
+ if (cmd === 'show') {
+ const ref = rest[0]!.replace(/:VERSION$/, '').replace(/^refs\/tags\//, '');
+ return repo.tags[ref] ? ok(repo.versionFile ?? ref.replace(/^v/, '')) : fail;
+ }
+ if (cmd === 'fetch') return ok();
+ return fail;
+ };
+}
+
+interface Setup {
+ role?: { permission: string; role_name?: string };
+ run?: SoakRun;
+ /** The GitHub release for the tag; null: there is none (404). */
+ release?: { draft: boolean } | null;
+ soakWorkflow?: string;
+ repo?: FakeRepo;
+}
+
+function harness(setup: Setup = {}) {
+ const calls: string[] = [];
+ const api: string[] = [];
+ const logs: string[] = [];
+ const summaries: string[] = [];
+ const repo: FakeRepo = setup.repo ?? {
+ commits: { [sha('a')]: sha('1'), [sha('b')]: sha('2'), [sha('c')]: sha('3') },
+ tags: { 'v0.60.360.0': { commit: sha('a') }, 'v0.60.361.0': { commit: sha('b') }, stable: { commit: sha('a'), object: 'tagobj-stable-old' }, 'stable-v0.60.360.0': { commit: sha('a'), object: 'tagobj-record-360' } },
+ remote: { stable: 'tagobj-stable-old', 'stable-v0.60.360.0': 'tagobj-record-360' },
+ };
+ const run: SoakRun = setup.run ?? { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('b') };
+ const deps: PromoteDeps = {
+ repo: REPO,
+ actor: 'alice-example',
+ soakWorkflow: setup.soakWorkflow ?? 'soak.yml',
+ async ghApi(path) {
+ api.push(path);
+ if (path.endsWith('/permission')) return setup.role ?? { permission: 'write', role_name: 'maintain' };
+ if (path.includes('/releases/tags/')) {
+ if (setup.release === null) throw new Error(`gh api ${path} failed: HTTP 404: Not Found`);
+ return setup.release ?? { draft: false };
+ }
+ return run;
+ },
+ git: fakeGit(repo, calls),
+ now: () => NOW,
+ log: line => logs.push(line),
+ summary: md => summaries.push(md),
+ };
+ return { deps, calls, api, logs, summaries, repo };
+}
+
+const inputs = (over: Partial<PromoteInputs> = {}): PromoteInputs => ({ version: '0.60.361.0', soakRunUrl: RUN_URL, scoreboardUrl: '', rollback: false, reason: '', ...over });
+
+describe('soak run URL parsing', () => {
+ test('accepts a run, a run attempt and a trailing slash in this repository', () => {
+ expect(parseRunUrl(RUN_URL, REPO)).toEqual({ runId: '123456', attempt: null });
+ expect(parseRunUrl(`${RUN_URL}/attempts/2`, REPO)).toEqual({ runId: '123456', attempt: '2' });
+ expect(parseRunUrl(`${RUN_URL}/`, REPO)).toEqual({ runId: '123456', attempt: null });
+ expect(parseRunUrl(`${RUN_URL}/attempts/3/`, REPO)).toEqual({ runId: '123456', attempt: '3' });
+ });
+
+ test('refuses a run of another repository and anything that is not a run URL', () => {
+ refused(() => parseRunUrl('https://github.com/acme-example/gbrain/actions/runs/123456', REPO), /run of acme-example\/gbrain, not garrytan\/gbrain/);
+ for (const junk of ['', 'not a url', 'http://github.com/garrytan/gbrain/actions/runs/1', `${RUN_URL}/job/9`, 'https://github.com/garrytan/gbrain/actions/runs/abc', `${RUN_URL}?x=1`, 'https://example.com/garrytan/gbrain/actions/runs/1']) {
+ refused(() => parseRunUrl(junk, REPO), /is not a GitHub Actions run URL/);
+ }
+ });
+});
+
+describe('soak run validation', () => {
+ const good: SoakRun = { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('b') };
+
+ test('accepts a completed successful run of the configured workflow, named bare or by path', () => {
+ for (const name of ['soak.yml', '.github/workflows/soak.yml', './.github/workflows/soak.yml', ' soak.yml ']) {
+ expect(() => checkSoakRun(good, name, RUN_URL)).not.toThrow();
+ }
+ expect(normaliseWorkflowPath('soak.yml')).toBe(SOAK);
+ expect(normaliseWorkflowPath('.github/workflows/soak.yml@refs/heads/master')).toBe(SOAK);
+ });
+
+ test('refuses a run that has not completed or did not succeed', () => {
+ refused(() => checkSoakRun({ ...good, status: 'in_progress', conclusion: null }, 'soak.yml', RUN_URL), /is in_progress, not completed; wait for it to finish/);
+ refused(() => checkSoakRun({ ...good, conclusion: 'failure' }, 'soak.yml', RUN_URL), /concluded failure, not success/);
+ refused(() => checkSoakRun({ ...good, conclusion: 'cancelled' }, 'soak.yml', RUN_URL), /concluded cancelled, not success/);
+ });
+
+ test('refuses a run of another workflow', () => {
+ refused(() => checkSoakRun({ ...good, path: '.github/workflows/test.yml' }, 'soak.yml', RUN_URL), /ran \.github\/workflows\/test\.yml, not the soak workflow \.github\/workflows\/soak\.yml/);
+ });
+
+ test('refuses when the STABLE_SOAK_WORKFLOW variable is unset, naming where to set it', () => {
+ refused(() => checkSoakRun(good, '', RUN_URL), /set the repository variable STABLE_SOAK_WORKFLOW to the soak workflow's file \(Settings → Secrets and variables → Actions → Variables\)/);
+ });
+});
+
+describe('version ordering', () => {
+ test('compares 3- and 4-part versions numerically', () => {
+ expect(compareVersions('0.60.361.0', '0.60.360.0')).toBe(1);
+ expect(compareVersions('0.60.99.0', '0.60.100.0')).toBe(-1);
+ expect(compareVersions('0.61.0', '0.60.999.9')).toBe(1);
+ expect(compareVersions('0.60.1', '0.60.1.0')).toBe(0);
+ });
+
+ test('newer promotes; same is a no-op; older needs rollback and a reason', () => {
+ expect(() => checkOrder('0.60.361.0', '0.60.360.0', false, '')).not.toThrow();
+ expect(() => checkOrder('0.60.361.0', null, false, '')).not.toThrow();
+ refused(() => checkOrder('0.60.361.0', '0.60.361.0', false, ''), /already the stable release, so there is nothing to promote/);
+ refused(() => checkOrder('0.60.361.0', '0.60.361.0', true, 'retry'), /already the stable release/);
+ refused(() => checkOrder('0.60.359.0', '0.60.360.0', false, ''), /older than the current stable v0\.60\.360\.0; to move stable back, re-run with rollback=true and a reason/);
+ refused(() => checkOrder('0.60.359.0', '0.60.360.0', true, ' '), /A rollback needs a reason/);
+ expect(() => checkOrder('0.60.359.0', '0.60.360.0', true, 'sync regression in 0.60.360.0')).not.toThrow();
+ });
+});
+
+describe('tag message and summary', () => {
+ const fields: TagFields = {
+ version: '0.60.361.0', commit: sha('b'), tree: sha('2'), soakRun: RUN_URL, scoreboard: 'https://example.com/scoreboard',
+ promotedBy: 'alice-example', promotedAt: '2026-10-21T17:00:00Z', previous: '0.60.360.0', rollback: false, reason: '',
+ };
+
+ test('renders the exact key: value body', () => {
+ expect(renderTagMessage(fields)).toBe([
+ 'gbrain stable channel: v0.60.361.0',
+ '',
+ 'version: 0.60.361.0',
+ `commit: ${sha('b')}`,
+ `tree: ${sha('2')}`,
+ `soak_run: ${RUN_URL}`,
+ 'scoreboard: https://example.com/scoreboard',
+ 'promoted_by: alice-example',
+ 'promoted_at: 2026-10-21T17:00:00Z',
+ 'previous: 0.60.360.0',
+ 'rollback: false',
+ 'reason: -',
+ '',
+ ].join('\n'));
+ const first = renderTagMessage({ ...fields, previous: null, rollback: true, reason: 'bad\nrelease' });
+ expect(first).toContain('previous: none\n');
+ expect(first).toContain('rollback: true\nreason: bad release\n');
+ });
+
+ test('the step summary names version, commit, tree, soak run, scoreboard, previous and rollback', () => {
+ const md = renderSummary({ ...fields, rollback: true, reason: 'a | b', recordCreated: false });
+ for (const part of ['## Stable channel: v0.60.361.0', sha('b'), sha('2'), RUN_URL, 'https://example.com/scoreboard', 'v0.60.360.0', 'yes: a \\| b', 'already existed']) expect(md).toContain(part);
+ });
+});
+
+describe('promote', () => {
+ test('a maintainer promotes a newer release: the record tag and the leased stable move in one atomic push', async () => {
+ const h = harness();
+ const p = await promote(h.deps, inputs());
+ expect(p).toMatchObject({ version: '0.60.361.0', commit: sha('b'), tree: sha('2'), previous: '0.60.360.0', scoreboard: RUN_URL, recordCreated: true, promotedAt: '2026-10-21T17:00:00Z' });
+ expect(h.api).toEqual([`repos/${REPO}/collaborators/alice-example/permission`, `repos/${REPO}/releases/tags/v0.60.361.0`, `repos/${REPO}/actions/runs/123456`]);
+ const pushes = h.calls.filter(c => c.startsWith('push'));
+ expect(pushes).toEqual([
+ 'push --atomic --force-with-lease=refs/tags/stable:tagobj-stable-old origin refs/tags/stable-v0.60.361.0:refs/tags/stable-v0.60.361.0 refs/tags/stable:refs/tags/stable',
+ ]);
+ expect(h.repo.tags['stable-v0.60.361.0']!.commit).toBe(sha('b'));
+ expect(h.repo.tags.stable!.commit).toBe(sha('b'));
+ expect(h.repo.tags.stable!.message).toBe(renderTagMessage(p));
+ expect(h.repo.tags['stable-v0.60.361.0']!.message).toBe(renderTagMessage(p));
+ expect(h.summaries).toHaveLength(1);
+ expect(h.logs.length).toBeGreaterThanOrEqual(6);
+ expect(h.calls).not.toContain(`fetch --no-tags origin ${sha('b')}`);
+ });
+
+ test('a named attempt is read from the attempts endpoint and the first promotion records previous: none', async () => {
+ const h = harness({ repo: { commits: { [sha('b')]: sha('2') }, tags: { 'v0.60.361.0': { commit: sha('b') } } } });
+ const p = await promote(h.deps, inputs({ soakRunUrl: `${RUN_URL}/attempts/2`, scoreboardUrl: 'https://example.com/board' }));
+ expect(h.api[2]).toBe(`repos/${REPO}/actions/runs/123456/attempts/2`);
+ expect(p.previous).toBeNull();
+ expect(p.scoreboard).toBe('https://example.com/board');
+ expect(h.calls.at(-1)).toBe('push --atomic --force-with-lease=refs/tags/stable: origin refs/tags/stable-v0.60.361.0:refs/tags/stable-v0.60.361.0 refs/tags/stable:refs/tags/stable');
+ });
+
+ test('admins pass; write, triage and read collaborators are refused before anything else is read', async () => {
+ await promote(harness({ role: { permission: 'admin', role_name: 'admin' } }).deps, inputs());
+ for (const role of [{ permission: 'write', role_name: 'write' }, { permission: 'read', role_name: 'triage' }, { permission: 'none' }]) {
+ const h = harness({ role });
+ await refusedAsync(promote(h.deps, inputs()), /only admins and maintainers promote to stable/);
+ expect(h.calls).toEqual([]);
+ expect(h.api).toHaveLength(1);
+ }
+ });
+
+ test('refuses a malformed version and a version with no release tag', async () => {
+ await refusedAsync(promote(harness().deps, inputs({ version: '0.60.361.0; rm -rf /' })), /is not a release version/);
+ await refusedAsync(promote(harness().deps, inputs({ version: '0.60.362.0' })), /There is no release tag v0\.60\.362\.0/);
+ });
+
+ test('refuses a tag whose VERSION file names another version, a tag with no GitHub release and a draft release, before anything moves', async () => {
+ const mismatched = harness();
+ mismatched.repo.versionFile = '0.60.999.0';
+ await refusedAsync(promote(mismatched.deps, inputs()), /v0\.60\.361\.0's VERSION file says "0\.60\.999\.0"/);
+ const missing = harness({ release: null });
+ await refusedAsync(promote(missing.deps, inputs()), /v0\.60\.361\.0 has no published GitHub release \(.*404.*\); wait for release\.yml to publish it/);
+ const draft = harness({ release: { draft: true } });
+ await refusedAsync(promote(draft.deps, inputs()), /is still a draft/);
+ for (const h of [mismatched, missing, draft]) expect(h.calls.filter(c => c.startsWith('tag -a') || c.startsWith('push'))).toEqual([]);
+ });
+
+ test('refuses when STABLE_SOAK_WORKFLOW is unset without reading the run', async () => {
+ const h = harness({ soakWorkflow: '' });
+ await refusedAsync(promote(h.deps, inputs()), /set the repository variable STABLE_SOAK_WORKFLOW/);
+ expect(h.api.filter(p => p.includes('/actions/runs/'))).toEqual([]);
+ });
+
+ test('refuses a soak of a different tree, naming both trees and the run head', async () => {
+ const h = harness({ run: { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('c') } });
+ await refusedAsync(promote(h.deps, inputs()), new RegExp(`soak ran tree ${sha('3')} \\(run head ${sha('c')}\\) but v0\\.60\\.361\\.0 is tree ${sha('2')}`));
+ expect(h.calls.filter(c => c.startsWith('tag -a') || c.startsWith('push'))).toEqual([]);
+ });
+
+ test('a soak head missing locally is fetched; a different commit with the same tree passes', async () => {
+ const repo: FakeRepo = { commits: { [sha('b')]: sha('2') }, tags: { 'v0.60.361.0': { commit: sha('b') } } };
+ const h = harness({ repo, run: { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('d') } });
+ const git = h.deps.git;
+ h.deps.git = async args => { if (args[0] === 'fetch') repo.commits[sha('d')] = sha('2'); return git(args); };
+ await promote(h.deps, inputs());
+ expect(h.calls).toContain(`fetch --no-tags origin ${sha('d')}`);
+ });
+
+ test('ordering through promote: same refuses, older refuses without rollback, rollback without a reason refuses, rollback with a reason moves stable back', async () => {
+ const same = harness();
+ same.repo.tags.stable = { commit: sha('b'), object: 'tagobj-stable-old' };
+ await refusedAsync(promote(same.deps, inputs()), /already the stable release/);
+ const older = () => { const h = harness({ run: { status: 'completed', conclusion: 'success', path: SOAK, head_sha: sha('a') } }); h.repo.tags.stable = { commit: sha('b'), object: 'tagobj-stable-old' }; return h; };
+ await refusedAsync(promote(older().deps, inputs({ version: '0.60.360.0' })), /older than the current stable v0\.60\.361\.0/);
+ await refusedAsync(promote(older().deps, inputs({ version: '0.60.360.0', rollback: true })), /A rollback needs a reason/);
+ const back = older();
+ const p = await promote(back.deps, inputs({ version: '0.60.360.0', rollback: true, reason: 'sync regression' }));
+ expect(p).toMatchObject({ previous: '0.60.361.0', rollback: true, recordCreated: false });
+ expect(back.repo.tags.stable!.commit).toBe(sha('a'));
+ expect(back.repo.tags.stable!.message).toContain('rollback: true\nreason: sync regression\n');
+ expect(back.calls.filter(c => c.startsWith('push'))).toEqual(['push --atomic --force-with-lease=refs/tags/stable:tagobj-stable-old origin refs/tags/stable:refs/tags/stable']);
+ expect(back.repo.tags['stable-v0.60.360.0']!.object).toBe('tagobj-record-360');
+ });
+
+ test('an existing record tag refuses without rollback and is never re-created', async () => {
+ const h = harness();
+ h.repo.tags['stable-v0.60.361.0'] = { commit: sha('b'), object: 'tagobj-record-361' };
+ await refusedAsync(promote(h.deps, inputs()), /stable-v0\.60\.361\.0 already exists, so v0\.60\.361\.0 was promoted before/);
+ expect(h.calls.filter(c => c.startsWith('tag -a') || c.startsWith('push'))).toEqual([]);
+ const moved = harness();
+ moved.repo.tags['stable-v0.60.361.0'] = { commit: sha('c'), object: 'tagobj-record-361' };
+ await refusedAsync(promote(moved.deps, inputs({ rollback: true, reason: 'restore' })), /points at c+, not the release commit b+/);
+ });
+
+ test('stable on a commit with no release tag refuses', async () => {
+ const h = harness();
+ h.repo.tags.stable = { commit: sha('c'), object: 'tagobj-stable-old' };
+ await refusedAsync(promote(h.deps, inputs()), /carries no v<VERSION> release tag/);
+ });
+
+ test('a stable tag moved by someone else after it was read loses the lease', async () => {
+ const h = harness();
+ h.repo.remote!.stable = 'tagobj-someone-else';
+ await refusedAsync(promote(h.deps, inputs()), /Moving the stable tag failed.*stale info/);
+ });
+
+ test('a failed push leaves the remote unchanged, so the re-run it asks for promotes cleanly', async () => {
+ const h = harness();
+ h.repo.failPush = true;
+ await refusedAsync(promote(h.deps, inputs()), /nothing changed on the remote.*re-run this workflow/);
+ expect(h.repo.remote).toEqual({ stable: 'tagobj-stable-old', 'stable-v0.60.360.0': 'tagobj-record-360' });
+ const retry = harness();
+ expect((await promote(retry.deps, inputs())).recordCreated).toBe(true);
+ });
+});
+
+describe('promote against real git', () => {
+ const git = (cwd: string, ...args: string[]) => {
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } });
+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);
+ return r.stdout.trim();
+ };
+
+ test('creates the annotated tags, pushes them and peels stable to the release commit', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'promote-stable-'));
+ try {
+ const origin = join(dir, 'origin.git');
+ const work = join(dir, 'work');
+ git(dir, 'init', '-q', '--bare', origin);
+ git(dir, 'init', '-q', work);
+ git(work, 'config', 'user.name', 'test-bot');
+ git(work, 'config', 'user.email', '[email protected]');
+ git(work, 'config', 'commit.gpgsign', 'false');
+ git(work, 'config', 'tag.gpgsign', 'false');
+ git(work, 'remote', 'add', 'origin', origin);
+ for (const version of ['1.0.0', '1.0.1']) {
+ writeFileSync(join(work, 'VERSION'), `${version}\n`);
+ git(work, 'add', 'VERSION');
+ git(work, 'commit', '-q', '-m', `release ${version}`);
+ git(work, 'tag', `v${version}`);
+ }
+ git(work, 'push', '-q', 'origin', 'HEAD:refs/heads/master', '--tags');
+ const head = git(work, 'rev-parse', 'HEAD');
+ const env = { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' };
+ const run: SoakRun = { status: 'completed', conclusion: 'success', path: SOAK, head_sha: head };
+ const deps = (version: string): PromoteDeps => ({
+ ...processDeps(env, work), repo: REPO, actor: 'alice-example', soakWorkflow: 'soak.yml', now: () => NOW, log: () => {}, summary: () => {},
+ ghApi: async path => (path.endsWith('/permission') ? { permission: 'admin', role_name: 'admin' }
+ : path.includes('/releases/tags/') ? { draft: false }
+ : { ...run, head_sha: git(work, 'rev-parse', `v${version}^{commit}`) }),
+ });
+
+ await promote(deps('1.0.0'), inputs({ version: '1.0.0' }));
+ await promote(deps('1.0.1'), inputs({ version: '1.0.1' }));
+ expect(git(work, 'ls-remote', origin, 'refs/tags/stable^{}').split('\t')[0]).toBe(head);
+ expect(git(work, 'cat-file', '-t', 'refs/tags/stable')).toBe('tag');
+ expect(git(work, 'cat-file', '-t', 'refs/tags/stable-v1.0.1')).toBe('tag');
+ const body = git(work, 'for-each-ref', '--format=%(contents)', 'refs/tags/stable');
+ expect(body).toContain('gbrain stable channel: v1.0.1\n\nversion: 1.0.1\n');
+ expect(body).toContain('previous: 1.0.0\nrollback: false\nreason: -');
+ const remote = git(work, 'ls-remote', '--tags', origin);
+ expect(remote).toContain('refs/tags/stable-v1.0.0');
+ expect(remote).toContain('refs/tags/stable-v1.0.1');
+
+ const record = git(work, 'rev-parse', 'refs/tags/stable-v1.0.0');
+ await promote(deps('1.0.0'), inputs({ version: '1.0.0', rollback: true, reason: 'regression' }));
+ expect(git(work, 'ls-remote', origin, 'refs/tags/stable^{}').split('\t')[0]).toBe(git(work, 'rev-parse', 'v1.0.0^{commit}'));
+ expect(git(work, 'ls-remote', origin, 'refs/tags/stable-v1.0.0').split('\t')[0]).toBe(record);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('promote-stable.yml', () => {
+ const workflowYml = readFileSync(join(ROOT, '.github/workflows/promote-stable.yml'), 'utf8');
+ const wf = load(workflowYml) as {
+ on: Record<string, { inputs: Record<string, { required?: boolean; type: string; default?: unknown }> }>;
+ concurrency: { group: string; 'cancel-in-progress': boolean };
+ permissions: Record<string, string>;
+ jobs: { promote: { steps: Array<{ uses?: string; with?: Record<string, unknown>; env?: Record<string, string>; run?: string }> } };
+ };
+
+ test('dispatch only, with the decided inputs, one serial group and scoped permissions', () => {
+ expect(Object.keys(wf.on)).toEqual(['workflow_dispatch']);
+ const i = wf.on.workflow_dispatch!.inputs;
+ expect(Object.keys(i)).toEqual(['version', 'soak_run_url', 'scoreboard_url', 'rollback', 'reason']);
+ expect([i.version!.required, i.soak_run_url!.required, i.scoreboard_url!.required]).toEqual([true, true, false]);
+ expect(i.rollback).toMatchObject({ type: 'boolean', default: false });
+ expect(wf.concurrency).toEqual({ group: 'promote-stable', 'cancel-in-progress': false });
+ expect(wf.permissions).toEqual({ contents: 'write', actions: 'read' });
+ });
+
+ test('inputs reach the script through env only; actions are pinned like release.yml; full history', () => {
+ const steps = wf.jobs.promote.steps;
+ const run = steps.find(s => s.run?.includes('scripts/promote-stable.ts'))!;
+ expect(run.env).toMatchObject({
+ GH_TOKEN: '${{ github.token }}', STABLE_SOAK_WORKFLOW: '${{ vars.STABLE_SOAK_WORKFLOW }}',
+ PROMOTE_VERSION: '${{ inputs.version }}', PROMOTE_SOAK_RUN_URL: '${{ inputs.soak_run_url }}', PROMOTE_SCOREBOARD_URL: '${{ inputs.scoreboard_url }}',
+ PROMOTE_ROLLBACK: '${{ inputs.rollback }}', PROMOTE_REASON: '${{ inputs.reason }}',
+ });
+ for (const s of steps) expect(s.run ?? '').not.toContain('${{');
+ const releaseYml = readFileSync(join(ROOT, '.github/workflows/release.yml'), 'utf8');
+ for (const s of steps.filter(x => x.uses)) {
+ expect(s.uses).toMatch(/@[0-9a-f]{40}$/);
+ expect(releaseYml).toContain(`uses: ${s.uses}`);
+ }
+ expect(steps[0]!.with).toMatchObject({ 'fetch-depth': 0 });
+ expect(workflowYml).not.toMatch(/bun install|ci-bun-install/);
+ });
+});
diff --git a/test/upgrade-bun-link-arc.serial.test.ts b/test/upgrade-bun-link-arc.serial.test.ts
index 89f6faba52..e3d0a5c49d 100644
--- a/test/upgrade-bun-link-arc.serial.test.ts
+++ b/test/upgrade-bun-link-arc.serial.test.ts
@@ -347,13 +347,14 @@ describe('runUpgrade — bun-link arc (real git vs local bare origin; bun/gbrain
expect(git(['rev-parse', 'HEAD'], fx.clone).trim()).toBe(fx.originHead);
// Recorder sequence: the bun shim saw the POST-pull HEAD (pull ran first),
- // then verify → post-upgrade → features, in order, and nothing else.
+ // then verify → post-upgrade → features → the new build's restart (GBRA-175), in order, and nothing else.
expect(argvLines(fx)).toEqual([
`bun install ::head=${fx.originHead}`,
'gbrain --version',
'gbrain --help',
'gbrain post-upgrade',
'gbrain features',
+ 'gbrain upgrade --restart-only',
]);
// saveUpgradeState checkpoint: $HOME/.gbrain/upgrade-state.json.
diff --git a/test/upgrade-restart.test.ts b/test/upgrade-restart.test.ts
new file mode 100644
index 0000000000..f48a2c77b8
--- /dev/null
+++ b/test/upgrade-restart.test.ts
@@ -0,0 +1,305 @@
+/**
+ * GBRA-175: `gbrain upgrade` restarts every gbrain process on the host onto
+ * the installed build, or refuses with the exact step for each process it
+ * cannot restart, then verifies one build runs and the warm CLI socket
+ * accepts it. Fakes stand in for ps, the PID file, the worker registry, the
+ * heartbeat rows, the service managers and the socket.
+ */
+import { describe, expect, test } from 'bun:test';
+import {
+ classifyGbrainCommand, collectHostProcesses, planRestart, restartProblems, runRestartSteps, supervisorRestartArgv, unverifiedBuilds, verifyRestart,
+ type HostProcess, type ProcessSources, type RestartContext, type RestartExecutor, type WarmSocketState,
+} from '../src/core/upgrade-restart.ts';
+import { restartRefusal } from '../src/commands/upgrade-restart.ts';
+import { exitCodeForCode } from '../src/core/error-catalogue.ts';
+
+const NEW = '0.60.400.0';
+const OLD = '0.60.390.0';
+const HOME = '/home/alice-example';
+const SERVE_SERVICE = ['systemctl', '--user', 'restart', 'gbrain-serve.service'];
+const AUTOPILOT_SERVICE = ['systemctl', '--user', 'restart', 'gbrain-autopilot.service'];
+const SERVE_PID = 9;
+const AUTOPILOT_PID = 29;
+const ctx = (over: Partial<RestartContext> = {}): RestartContext => ({
+ expected: NEW, serveService: { argv: SERVE_SERVICE, pid: SERVE_PID }, autopilotService: { argv: AUTOPILOT_SERVICE, pid: AUTOPILOT_PID }, stopMcp: false, ...over,
+});
+const SUP_ARGS = ['jobs', 'supervisor', 'start'];
+const DEFAULT_SUP = supervisorRestartArgv(SUP_ARGS);
+const proc = (pid: number, role: HostProcess['role'], version: string | null = OLD, over: Partial<HostProcess> = {}): HostProcess => ({
+ pid, ppid: null, role, version, started_ms: 1_000,
+ ancestors: role === 'serve' ? [SERVE_PID] : role === 'autopilot' ? [AUTOPILOT_PID] : [],
+ args: role === 'supervisor' ? SUP_ARGS : [role], ...over,
+});
+
+describe('classifyGbrainCommand', () => {
+ test('long-running gbrain processes get a role; one-shot, transient and wrapper commands do not', () => {
+ expect(classifyGbrainCommand('/usr/bin/bun /home/alice-example/.bun/bin/gbrain serve --http --port 3131')).toBe('serve');
+ expect(classifyGbrainCommand('bun /srv/gbrain/src/cli.ts serve')).toBe('mcp');
+ expect(classifyGbrainCommand('gbrain jobs work --queue default')).toBe('worker');
+ expect(classifyGbrainCommand('gbrain jobs supervisor start --detach')).toBe('supervisor');
+ expect(classifyGbrainCommand('gbrain jobs supervisor')).toBe('supervisor');
+ expect(classifyGbrainCommand('gbrain jobs supervisor stop')).toBeNull();
+ expect(classifyGbrainCommand('gbrain autopilot --repo /srv/brain-example')).toBe('autopilot');
+ expect(classifyGbrainCommand('gbrain autopilot start')).toBe('autopilot');
+ expect(classifyGbrainCommand('gbrain autopilot --install')).toBeNull();
+ expect(classifyGbrainCommand('gbrain autopilot status')).toBeNull();
+ expect(classifyGbrainCommand('gbrain jobs supervisor --max-rss 512')).toBe('supervisor');
+ expect(classifyGbrainCommand('gbrain sync --source source-a')).toBe('sync');
+ expect(classifyGbrainCommand('gbrain search alice')).toBeNull();
+ expect(classifyGbrainCommand('gbrain upgrade --restart-only')).toBeNull();
+ expect(classifyGbrainCommand('gbrain serve status')).toBeNull();
+ expect(classifyGbrainCommand('vim notes/gbrain-serve.md')).toBeNull();
+ expect(classifyGbrainCommand('/usr/bin/tini -s -- /home/alice-example/.bun/bin/gbrain jobs work --queue default')).toBeNull();
+ });
+});
+
+describe('supervisorRestartArgv', () => {
+ test('keeps the queue, concurrency and PID file the supervisor was launched with', () => {
+ expect(supervisorRestartArgv(['jobs', 'supervisor', 'start', '--queue', 'ingest', '--concurrency', '4', '--pid-file', '/tmp/sup-example.pid'])).toEqual({
+ stop: ['gbrain', 'jobs', 'supervisor', 'stop', '--pid-file', '/tmp/sup-example.pid', '--json'],
+ start: ['gbrain', 'jobs', 'supervisor', 'start', '--detach', '--queue', 'ingest', '--concurrency', '4', '--pid-file', '/tmp/sup-example.pid', '--json'],
+ pid_file: '/tmp/sup-example.pid',
+ });
+ expect(DEFAULT_SUP).toEqual({ stop: ['gbrain', 'jobs', 'supervisor', 'stop', '--json'], start: ['gbrain', 'jobs', 'supervisor', 'start', '--detach', '--json'], pid_file: null });
+ });
+});
+
+describe('collectHostProcesses', () => {
+ const sources = (over: Partial<ProcessSources> = {}): ProcessSources => ({
+ heartbeats: async () => [], supervisor: () => null, workers: () => [], processTable: () => [], home: HOME, exclude: [], ...over,
+ });
+
+ test('merges ps, heartbeats, the PID file and the worker registry by pid; the parent is the nearest gbrain process (through tini)', async () => {
+ const processes = await collectHostProcesses(sources({
+ processTable: () => [
+ { pid: 10, ppid: SERVE_PID, command: 'gbrain serve --http', started_ms: 500, gbrain_home: HOME },
+ { pid: SERVE_PID, ppid: 1, command: '/bin/sh /home/alice-example/.gbrain/serve/gbrain-serve.sh', started_ms: 400, gbrain_home: HOME },
+ { pid: 20, ppid: 1, command: 'gbrain jobs supervisor start --queue ingest', started_ms: 600, gbrain_home: HOME },
+ { pid: 22, ppid: 20, command: '/usr/bin/tini -s -- /usr/local/bin/gbrain jobs work --queue ingest', started_ms: 650, gbrain_home: HOME },
+ { pid: 21, ppid: 22, command: '/usr/local/bin/gbrain jobs work --queue ingest', started_ms: 700, gbrain_home: HOME },
+ { pid: 30, ppid: 99, command: 'gbrain serve', started_ms: 800, gbrain_home: undefined },
+ ],
+ heartbeats: async () => [{ pid: 10, kind: 'serve', version: OLD }, { pid: 40, kind: 'autopilot', version: NEW }, { pid: 50, kind: 'cli', version: NEW }],
+ supervisor: () => ({ pid: 20, version: OLD }),
+ workers: () => [{ pid: 21, version: OLD }],
+ installVersion: command => command.startsWith('/usr/local/bin/gbrain') ? NEW : null,
+ }));
+ expect(processes).toEqual([
+ { pid: 10, ppid: null, role: 'serve', version: OLD, started_ms: 500, ancestors: [SERVE_PID], args: ['serve', '--http'], install_version: null },
+ { pid: 20, ppid: null, role: 'supervisor', version: OLD, started_ms: 600, ancestors: [], args: ['jobs', 'supervisor', 'start', '--queue', 'ingest'], install_version: null },
+ { pid: 21, ppid: 20, role: 'worker', version: OLD, started_ms: 700, ancestors: [22, 20], args: ['jobs', 'work', '--queue', 'ingest'], install_version: NEW },
+ { pid: 30, ppid: null, role: 'mcp', version: null, started_ms: 800, ancestors: [99], args: ['serve'], install_version: null },
+ ]);
+ });
+
+ test('a record whose pid the process table does not list as gbrain is stale and dropped (a dead or reused pid is never signalled)', async () => {
+ const processes = await collectHostProcesses(sources({
+ processTable: () => [{ pid: 77, ppid: 1, command: 'sleep 600', started_ms: 500, gbrain_home: HOME }],
+ heartbeats: async () => [{ pid: 77, kind: 'mcp', version: OLD }, { pid: 78, kind: 'serve', version: OLD }],
+ workers: () => [{ pid: 79, version: OLD }],
+ }));
+ expect(processes).toEqual([]);
+ });
+
+ test('without a process table, records are kept but an MCP server is never stopped', async () => {
+ const processes = await collectHostProcesses(sources({ processTable: () => null, heartbeats: async () => [{ pid: 77, kind: 'mcp', version: OLD }] }));
+ expect(processes).toEqual([{ pid: 77, ppid: null, role: 'mcp', version: OLD, started_ms: null }]);
+ const plan = planRestart(processes, ctx({ stopMcp: true }));
+ expect(plan.steps).toEqual([]);
+ expect(plan.manual[0]!.instruction).toContain('not signalled');
+ });
+
+ test('skips another brain home and the upgrade process itself', async () => {
+ const processes = await collectHostProcesses(sources({
+ processTable: () => [
+ { pid: 10, ppid: 1, command: 'gbrain serve --http', started_ms: 500, gbrain_home: '/home/bob-example' },
+ { pid: 11, ppid: 1, command: 'gbrain serve --http', started_ms: 500, gbrain_home: `${HOME}/` },
+ { pid: 12, ppid: 1, command: 'gbrain jobs work', started_ms: 500, gbrain_home: HOME },
+ ],
+ exclude: [12],
+ }));
+ expect(processes.map(p => p.pid)).toEqual([11]);
+ });
+});
+
+describe('planRestart', () => {
+ test('serve and autopilot restart through their services, the supervisor takes its worker along, current processes stay', () => {
+ const plan = planRestart([
+ proc(10, 'serve'), proc(11, 'serve', NEW), proc(20, 'supervisor'), proc(21, 'worker', OLD, { ppid: 20 }),
+ proc(30, 'autopilot'), proc(31, 'worker', OLD, { ppid: 30 }),
+ ], ctx());
+ expect(plan.manual).toEqual([]);
+ expect(plan.current.map(p => p.pid)).toEqual([11]);
+ expect(plan.steps).toEqual([
+ { kind: 'service', role: 'serve', argv: SERVE_SERVICE, pids: [10] },
+ { kind: 'service', role: 'autopilot', argv: AUTOPILOT_SERVICE, pids: [30] },
+ { kind: 'supervisor', pid: 20, workers: [21], ...DEFAULT_SUP },
+ ]);
+ });
+
+ test('the supervisor restarts with the options it was launched with', () => {
+ const args = ['jobs', 'supervisor', 'start', '--queue', 'ingest', '--concurrency', '4'];
+ const plan = planRestart([proc(20, 'supervisor', OLD, { args }), proc(21, 'worker', OLD, { ppid: 20 })], ctx());
+ expect(plan.steps).toEqual([{ kind: 'supervisor', pid: 20, workers: [21], ...supervisorRestartArgv(args) }]);
+ });
+
+ test('a stale worker under a current supervisor restarts the supervisor', () => {
+ const plan = planRestart([proc(20, 'supervisor', NEW), proc(21, 'worker', OLD, { ppid: 20 })], ctx());
+ expect(plan.steps).toEqual([{ kind: 'supervisor', pid: 20, workers: [21], ...DEFAULT_SUP }]);
+ });
+
+ test('a process that reports no build counts as stale', () => {
+ expect(planRestart([proc(10, 'serve', null)], ctx()).steps).toEqual([{ kind: 'service', role: 'serve', argv: SERVE_SERVICE, pids: [10] }]);
+ });
+
+ test('an installed service restarts only the processes its manager runs; a hand-started serve beside it is manual', () => {
+ const plan = planRestart([proc(10, 'serve'), proc(12, 'serve', OLD, { ancestors: [500] })], ctx());
+ expect(plan.steps).toEqual([{ kind: 'service', role: 'serve', argv: SERVE_SERVICE, pids: [10] }]);
+ expect(plan.manual.map(m => [m.pid, m.argv])).toEqual([[12, ['kill', '12']]]);
+ expect(plan.manual[0]!.instruction).toContain(`(the service runs pid ${SERVE_PID})`);
+ const stopped = planRestart([proc(10, 'serve')], ctx({ serveService: { argv: SERVE_SERVICE, pid: null } }));
+ expect(stopped.steps).toEqual([]);
+ expect(stopped.manual[0]!.instruction).toContain('the service is not running');
+ });
+
+ test('hand-started serve, standalone worker, service-less autopilot, a supervisor without readable options and a running sync are manual steps', () => {
+ const plan = planRestart([proc(10, 'serve'), proc(21, 'worker', OLD), proc(30, 'autopilot'), proc(40, 'sync'), proc(20, 'supervisor', OLD, { args: undefined })],
+ ctx({ serveService: null, autopilotService: null }));
+ expect(plan.steps).toEqual([]);
+ expect(plan.manual.map(m => [m.role, m.argv])).toEqual([
+ ['serve', ['kill', '10']], ['worker', ['kill', '21']], ['autopilot', ['kill', '30']], ['sync', ['gbrain', 'sync', 'status', '--json']], ['supervisor', ['kill', '20']],
+ ]);
+ expect(plan.manual[0]!.instruction).toContain('was not started by the installed serve service');
+ expect(plan.manual[1]!.instruction).toContain('gbrain jobs supervisor start --detach');
+ expect(plan.manual[3]!.instruction).toContain('let it finish');
+ expect(plan.manual[4]!.instruction).toContain('not restarted with defaults');
+ });
+
+ test('an MCP server refuses without --stop-mcp and is stopped with it', () => {
+ expect(planRestart([proc(50, 'mcp')], ctx()).manual.map(m => m.role)).toEqual(['mcp']);
+ const plan = planRestart([proc(50, 'mcp'), proc(10, 'serve')], ctx({ stopMcp: true }));
+ expect(plan.manual).toEqual([]);
+ expect(plan.steps.at(-1)).toEqual({ kind: 'stop', role: 'mcp', pid: 50, started_ms: 1_000 });
+ expect(plan.steps[0]).toMatchObject({ kind: 'service', role: 'serve' });
+ });
+});
+
+describe('restartRefusal', () => {
+ test('MCP-only refusals ask the user to rerun with --stop-mcp; others tell the user the first manual step; exit 3', () => {
+ const mcp = restartRefusal(planRestart([proc(50, 'mcp')], ctx()), ['gbrain', 'upgrade', '--channel', 'stable'], false)!;
+ expect(mcp.code).toBe('restart_refused');
+ expect(exitCodeForCode(mcp.code)).toBe(3);
+ expect(mcp.message).toContain('nothing was installed');
+ expect(mcp.fix).toMatchObject({ ask_user: true, actor: 'agent', argv: ['gbrain', 'upgrade', '--channel', 'stable', '--stop-mcp'] });
+ expect(mcp.fix?.user_message).toContain('pid 50');
+ const serve = restartRefusal(planRestart([proc(50, 'mcp'), proc(10, 'serve')], ctx({ serveService: null })), ['gbrain', 'upgrade', '--restart-only'], true)!;
+ expect(serve.message).not.toContain('nothing was installed');
+ expect(serve.fix).toMatchObject({ actor: 'user', argv: ['kill', '10'] });
+ expect(restartRefusal(planRestart([proc(10, 'serve')], ctx()), ['gbrain', 'upgrade'], false)).toBeNull();
+ });
+});
+
+describe('runRestartSteps', () => {
+ const executor = (over: { status?: (argv: string[]) => number; supervisorPid?: (file: string | null) => number | null; terminate?: RestartExecutor['terminate'] } = {}) => {
+ const calls: string[] = [];
+ const exec: RestartExecutor = {
+ run: argv => { calls.push(argv.join(' ')); return { status: over.status?.(argv) ?? 0, output: 'boom\nmore' }; },
+ terminate: over.terminate ?? (pid => { calls.push(`SIGTERM ${pid}`); return 'stopped'; }),
+ supervisorPid: over.supervisorPid ?? (() => null),
+ sleep: async () => {},
+ };
+ return { calls, exec };
+ };
+ const plan = planRestart([proc(10, 'serve'), proc(20, 'supervisor'), proc(21, 'worker', OLD, { ppid: 20 }), proc(50, 'mcp')], ctx({ stopMcp: true }));
+
+ test('runs serve first, then the supervisor stop and start, then stops MCP servers', async () => {
+ const { calls, exec } = executor();
+ const results = await runRestartSteps(plan, exec);
+ expect(calls).toEqual([SERVE_SERVICE.join(' '), DEFAULT_SUP.stop.join(' '), DEFAULT_SUP.start.join(' '), 'SIGTERM 50']);
+ expect(results.every(r => r.ok)).toBe(true);
+ });
+
+ test('a supervisor its service manager respawned is not started twice; the respawn is read from its own PID file', async () => {
+ const files: Array<string | null> = [];
+ const { calls, exec } = executor({ supervisorPid: file => { files.push(file); return 77; } });
+ const custom = planRestart([proc(20, 'supervisor', OLD, { args: ['jobs', 'supervisor', '--pid-file', '/tmp/sup-example.pid'] })], ctx());
+ const results = await runRestartSteps(custom, exec);
+ expect(calls).toEqual(['gbrain jobs supervisor stop --pid-file /tmp/sup-example.pid --json']);
+ expect(files).toEqual(['/tmp/sup-example.pid']);
+ expect(results[0]!.detail).toContain('started pid 77');
+ });
+
+ test('an MCP pid that now names another process is not signalled and fails the step', async () => {
+ const { exec } = executor({ terminate: () => 'changed' });
+ const results = await runRestartSteps(plan, exec);
+ expect(results.at(-1)).toMatchObject({ ok: false });
+ expect(results.at(-1)!.detail).toContain('was not signalled');
+ });
+
+ test('a failed command is reported with its first output line', async () => {
+ const { exec } = executor({ status: argv => argv[0] === 'systemctl' ? 5 : 0 });
+ const results = await runRestartSteps(plan, exec);
+ expect(results[0]).toMatchObject({ ok: false });
+ expect(results[0]!.detail).toContain('exited 5: boom');
+ });
+});
+
+describe('restartProblems and verifyRestart', () => {
+ const plan = planRestart([proc(10, 'serve'), proc(20, 'supervisor'), proc(21, 'worker', OLD, { ppid: 20 })], ctx());
+ const absent: WarmSocketState = { state: 'absent' };
+ const accepted: WarmSocketState = { state: 'accepted' };
+ const after = [proc(110, 'serve', NEW, { started_ms: 5_000 }), proc(120, 'supervisor', NEW, { started_ms: 5_000 }), proc(121, 'worker', NEW, { ppid: 120, started_ms: 5_000 })];
+
+ test('done when the old pids are gone, every process reports the build and the roles came back', () => {
+ expect(restartProblems(plan, after, 4_000, { before: accepted, after: accepted })).toEqual([]);
+ });
+
+ test('names a surviving old pid, another build, an unrecorded build from before the restart, and a role that did not return', () => {
+ const problems = restartProblems(plan, [proc(10, 'serve'), proc(130, 'mcp', OLD), proc(140, 'autopilot', null, { started_ms: 3_000 })], 4_000, { before: absent, after: absent });
+ expect(problems).toEqual([
+ `serve pid 10 (v${OLD}) is still running after the restart.`,
+ `mcp pid 130 (v${OLD}) runs a build other than v${NEW}.`,
+ 'autopilot pid 140 (build not recorded) reports no build and started before the restart.',
+ 'serve did not come back after `systemctl --user restart gbrain-serve.service`.',
+ 'supervisor did not come back after the supervisor restart.',
+ ]);
+ });
+
+ test('a restarted supervisor whose worker has not come back is not done', () => {
+ expect(restartProblems(plan, after.slice(0, 2), 4_000, { before: absent, after: absent }))
+ .toEqual(['the jobs worker did not come back under the restarted supervisor (`' + DEFAULT_SUP.start.join(' ') + '`).']);
+ });
+
+ test('a process with no recorded build must have started after the restart from an install that holds the build', () => {
+ expect(restartProblems(plan, [...after, proc(150, 'mcp', null, { started_ms: 6_000, install_version: NEW })], 4_000, { before: absent, after: absent })).toEqual([]);
+ expect(restartProblems(plan, [...after, proc(151, 'mcp', null, { started_ms: 6_000, install_version: OLD })], 4_000, { before: absent, after: absent }))
+ .toEqual([`mcp pid 151 (build not recorded) reports no build and was started from an install that holds v${OLD}.`]);
+ const binary = [...after, proc(152, 'serve', null, { started_ms: 6_000, install_version: null })];
+ expect(restartProblems(plan, binary, 4_000, { before: absent, after: absent })).toEqual([]);
+ expect(unverifiedBuilds(plan, binary)).toEqual(['serve pid 152 (build not recorded) started after the restart but records no build, so its build is inferred from its start time.']);
+ });
+
+ test('the warm socket must accept the build; an env difference is this shell, not the upgrade', () => {
+ const warm = (state: WarmSocketState) => restartProblems(plan, after, 4_000, { before: accepted, after: state });
+ expect(warm({ state: 'refused', reason: 'identity_mismatch', mismatch: 'version' })).toEqual(['The warm CLI socket refused this build (identity_mismatch: version).']);
+ expect(warm({ state: 'refused', reason: 'malformed_request' })).toEqual(['The warm CLI socket refused this build (malformed_request).']);
+ expect(warm({ state: 'refused', reason: 'identity_mismatch', mismatch: 'env GBRAIN_MODEL' })).toEqual([]);
+ expect(warm(absent)).toEqual(['The warm CLI socket serve had before the restart is gone.']);
+ expect(restartProblems(plan, after, 4_000, { before: absent, after: absent })).toEqual([]);
+ });
+
+ test('verifyRestart polls until the restart settles, and gives up at the deadline with the problems', async () => {
+ let clock = 0;
+ const rounds = [[proc(10, 'serve'), ...after.slice(1)], after];
+ let round = 0;
+ const deps = { collect: async () => rounds[Math.min(round++, rounds.length - 1)]!, probeWarmSocket: async () => accepted, sleep: async (ms: number) => { clock += ms; }, now: () => clock };
+ const ok = await verifyRestart(plan, 4_000, accepted, deps, { timeoutMs: 10_000, pollMs: 2_000 });
+ expect(ok).toMatchObject({ ok: true, problems: [], unverified: [] });
+ expect(clock).toBe(2_000);
+ clock = 0;
+ const stuck = await verifyRestart(plan, 4_000, accepted, { ...deps, collect: async () => [proc(10, 'serve'), ...after.slice(1)] }, { timeoutMs: 6_000, pollMs: 2_000 });
+ expect(stuck.ok).toBe(false);
+ expect(stuck.problems[0]).toContain('serve pid 10');
+ expect(clock).toBe(6_000);
+ });
+});
diff --git a/test/upgrade-stable-channel.test.ts b/test/upgrade-stable-channel.test.ts
new file mode 100644
index 0000000000..c0ef499371
--- /dev/null
+++ b/test/upgrade-stable-channel.test.ts
@@ -0,0 +1,164 @@
+/**
+ * GBRA-175: the stable release channel. `gbrain upgrade --channel stable` (or
+ * `self_upgrade.channel stable`) installs the release the `stable` tag names,
+ * pinned to its `v<version>` tag, never downgrades, and then restarts every
+ * process onto it through the new build's `gbrain upgrade --restart-only`.
+ *
+ * Subprocess: detectInstallMethod keys on argv[1] living under node_modules,
+ * and git, bun and gbrain must hit PATH shims, which Bun snapshots at start.
+ */
+import { describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+import { parseChannelArg, resolveStableRelease } from '../src/commands/upgrade.ts';
+import { normalizeChannel, parseSelfUpgradeConfigValue, resolveReleaseChannel } from '../src/core/self-upgrade.ts';
+import { parseSemver } from '../src/core/semver.ts';
+import { VERSION } from '../src/version.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+const v = parseSemver(VERSION)!;
+const NEWER = `${v[0]}.${v[1]}.${v[2] + 5}.0`;
+const NEWEST = `${v[0]}.${v[1]}.${v[2] + 9}.0`;
+const OLDER = `${v[0]}.${v[1]}.${Math.max(0, v[2] - 5)}.0`;
+
+const tags = (stableCommit: string | null, annotated = true) => [
+ `1111\trefs/tags/v${OLDER}`, `2222\trefs/tags/v${NEWER}`, `3333\trefs/tags/v${NEWEST}`, '3333\trefs/tags/latest-stable',
+ ...(stableCommit ? (annotated ? ['9999\trefs/tags/stable', `${stableCommit}\trefs/tags/stable^{}`] : [`${stableCommit}\trefs/tags/stable`]) : []),
+].join('\n');
+
+describe('resolveStableRelease', () => {
+ const git = (stdout: string, status = 0) => () => ({ status, stdout });
+ test('peels the annotated stable tag to the release commit and names its version', () => {
+ expect(resolveStableRelease(git(tags('2222')))).toEqual({ version: NEWER, commit: '2222' });
+ expect(resolveStableRelease(git(tags('2222', false)))).toEqual({ version: NEWER, commit: '2222' });
+ });
+ test('the newest v tag wins when several share the stable commit', () => {
+ expect(resolveStableRelease(git(`${tags('2222')}\n2222\trefs/tags/v${NEWER.replace(/\.0$/, '.1')}`))).toEqual({ version: NEWER.replace(/\.0$/, '.1'), commit: '2222' });
+ });
+ test('no stable tag, a stable tag on no release, and an unreadable remote are distinct errors', () => {
+ expect(resolveStableRelease(git(tags(null)))).toEqual({ error: 'no_stable' });
+ expect(resolveStableRelease(git(tags('abcd')))).toEqual({ error: 'no_release_tag' });
+ expect(resolveStableRelease(git('', 128))).toEqual({ error: 'unreadable' });
+ });
+});
+
+describe('channel selection', () => {
+ test('--channel takes latest or stable, in either spelling', () => {
+ expect(parseChannelArg(['--channel', 'stable'])).toBe('stable');
+ expect(parseChannelArg(['--channel=latest'])).toBe('latest');
+ expect(parseChannelArg(['--channel', 'beta'])).toBe('invalid');
+ expect(parseChannelArg(['--channel'])).toBe('invalid');
+ expect(parseChannelArg(['--swap-only'])).toBeNull();
+ });
+ test('self_upgrade.channel is validated and defaults to latest', () => {
+ expect(parseSelfUpgradeConfigValue('channel', 'stable')).toEqual({ ok: true, value: 'stable' });
+ expect(parseSelfUpgradeConfigValue('channel', 'nightly')).toMatchObject({ ok: false });
+ expect(resolveReleaseChannel({ self_upgrade: { channel: 'stable' } })).toBe('stable');
+ expect(resolveReleaseChannel({ self_upgrade: { channel: 'bogus' } })).toBe('latest');
+ expect(resolveReleaseChannel(null)).toBe('latest');
+ expect(normalizeChannel('latest')).toBe('latest');
+ });
+});
+
+interface Run { home: string; exitCode: number; stdout: string; stderr: string; bunCalls: string[]; gbrainCalls: string[] }
+
+async function runStableUpgrade(args: string[], opts: { stableCommit?: string | null; config?: Record<string, unknown>; failAdd?: string } = {}): Promise<Run> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-stable-'));
+ const bin = join(home, 'bin');
+ mkdirSync(bin);
+ const state = join(home, 'installed-version');
+ writeFileSync(state, VERSION);
+ writeFileSync(join(bin, 'git'), `#!/bin/sh\ncase "$1" in ls-remote) cat '${join(home, 'tags.txt')}'; exit 0;; esac\nexit 1\n`);
+ writeFileSync(join(home, 'tags.txt'), tags(opts.stableCommit === undefined ? '2222' : opts.stableCommit));
+ // `bun add -g github:garrytan/gbrain#v<x>` installs <x>; `gbrain --version` reports what is installed.
+ writeFileSync(join(bin, 'bun'), `#!/bin/sh\necho "$*" >> '${join(home, 'bun-calls.log')}'\n${opts.failAdd ? `case "$*" in "add -g github:garrytan/gbrain#v${opts.failAdd}") exit 1;; esac\n` : ''}case "$*" in "add -g github:garrytan/gbrain#v"*) echo "$3" | sed 's/.*#v//' > '${state}';; esac\nexit 0\n`);
+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nif [ "$1" = "--version" ]; then echo "gbrain $(cat '${state}')"; exit 0; fi\necho "$*" >> '${join(home, 'gbrain-calls.log')}'\nexit 0\n`);
+ for (const f of ['git', 'bun', 'gbrain']) chmodSync(join(bin, f), 0o755);
+ if (opts.config) {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(opts.config));
+ }
+ const globalRoot = join(home, '.bun', 'install', 'global');
+ const pkgDir = join(globalRoot, 'node_modules', 'gbrain');
+ mkdirSync(pkgDir, { recursive: true });
+ writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: 'github:garrytan/gbrain#latest-stable' } }));
+ writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));
+ const driver = join(pkgDir, 'driver.ts');
+ writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(${JSON.stringify(['--no-bun-floor-check', '--no-autopilot-install', ...args])});\n`);
+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}` };
+ delete env.BUN_INSTALL;
+ delete env.DATABASE_URL;
+ delete env.GBRAIN_DATABASE_URL;
+ const proc = Bun.spawn([process.execPath, 'run', driver], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
+ const lines = (f: string) => existsSync(join(home, f)) ? readFileSync(join(home, f), 'utf8').trim().split('\n').filter(Boolean) : [];
+ return { home, exitCode: await proc.exited, stdout, stderr, bunCalls: lines('bun-calls.log'), gbrainCalls: lines('gbrain-calls.log') };
+}
+
+describe('gbrain upgrade --channel stable', () => {
+ test('installs exactly the stable release pinned to its tag (remove, then add), not the newest release', async () => {
+ const r = await runStableUpgrade(['--channel', 'stable', '--swap-only']);
+ try {
+ expect(r.stdout).toContain(`Stable channel: installing gbrain ${NEWER}`);
+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]);
+ expect(r.stdout).toContain(`Now running: gbrain ${NEWER}`);
+ expect(r.exitCode).toBe(0);
+ } finally { rmSync(r.home, { recursive: true, force: true }); }
+ });
+
+ test('then the new build restarts every process and the summary says so', async () => {
+ const r = await runStableUpgrade(['--channel', 'stable']);
+ try {
+ expect(r.gbrainCalls).toContain('upgrade --restart-only');
+ expect(r.stdout).toContain(`Restart: every gbrain process on this host runs ${NEWER}`);
+ expect(r.exitCode).toBe(0);
+ } finally { rmSync(r.home, { recursive: true, force: true }); }
+ });
+
+ test('--no-restart installs without restarting and says what to run', async () => {
+ const r = await runStableUpgrade(['--channel', 'stable', '--no-restart']);
+ try {
+ expect(r.gbrainCalls.some(c => c.includes('--restart-only'))).toBe(false);
+ expect(r.stdout).toContain('Restart: skipped (--no-restart)');
+ } finally { rmSync(r.home, { recursive: true, force: true }); }
+ });
+
+ test('self_upgrade.channel stable makes a bare upgrade follow the stable channel', async () => {
+ const r = await runStableUpgrade(['--swap-only'], { config: { engine: 'pglite', database_path: '/tmp/gbrain-stable-example.pglite', self_upgrade: { channel: 'stable' } } });
+ try {
+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`]);
+ } finally { rmSync(r.home, { recursive: true, force: true }); }
+ });
+
+ test('a build at or above the stable release changes nothing (the stable channel never downgrades)', async () => {
+ const same = await runStableUpgrade(['--channel', 'stable'], { stableCommit: '1111' });
+ try {
+ expect(same.stdout).toContain(`is newer than the stable channel's release (${OLDER})`);
+ expect(same.bunCalls).toEqual([]);
+ expect(same.exitCode).toBe(0);
+ } finally { rmSync(same.home, { recursive: true, force: true }); }
+ });
+
+ test('a failed add restores the release that was installed and records the recovery step', async () => {
+ const r = await runStableUpgrade(['--channel', 'stable', '--swap-only'], { failAdd: NEWER });
+ try {
+ expect(r.bunCalls).toEqual(['remove -g gbrain', `add -g github:garrytan/gbrain#v${NEWER}`, `add -g github:garrytan/gbrain#v${VERSION}`]);
+ expect(r.stderr).toContain(`Restored gbrain ${VERSION}.`);
+ const record = JSON.parse(readFileSync(join(r.home, '.gbrain', 'upgrade-errors.jsonl'), 'utf8').trim().split('\n').at(-1)!);
+ expect(record).toMatchObject({ phase: 'stable-reinstall', from_version: VERSION, to_version: NEWER });
+ expect(record.hint).toContain(`#v${NEWER}`);
+ expect(r.exitCode).not.toBe(0);
+ } finally { rmSync(r.home, { recursive: true, force: true }); }
+ });
+
+ test('no promoted release refuses with stable_channel_unresolved and changes nothing', async () => {
+ const r = await runStableUpgrade(['--channel', 'stable'], { stableCommit: null });
+ try {
+ expect(r.stderr).toContain('stable_channel_unresolved');
+ expect(r.stderr).toContain('No release has been promoted to the stable channel yet');
+ expect(r.bunCalls).toEqual([]);
+ expect(r.exitCode).not.toBe(0);
+ } finally { rmSync(r.home, { recursive: true, force: true }); }
+ });
+});