Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Run free upkeep inside gbrain serve while the agent is quiet, add gbrain maintain --schedule, and name upkeep in the first-run settings
garrytan3efba4cfb708
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cdefaf399f..e07116b95e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,14 @@ identifiers and attribution are available in the pre-removal Git revision- A new doctor check, `unattended_maintenance`, reports the same thing. It warns when upkeep hasn't run for 48 hours or a step keeps failing, and its fix is `gbrain maintain --unattended`. A brain where `maintenance.auto` is `false`, or where autopilot runs upkeep, reads as ok.- `gbrain maintain --purge` previews which soft-deleted pages are past their 72-hour window. `--yes --expect <hash>` purges exactly the previewed set, and refuses with `preview_changed` when the set moved since the preview. Upkeep never purges pages on its own.+### Upkeep runs while your agent is connected, and `--schedule` covers the rest++**An open `gbrain serve` now does the free upkeep for you, so a default install needs no service, cron job or second command.** When the agent connected to `gbrain serve` (stdio or HTTP) goes quiet, serve runs `gbrain maintain --unattended` in slices of about 3 seconds, at most one full round a day per brain, and stops a slice the moment a tool call arrives. It writes the same record that `gbrain maintain --status` and doctor read, with runner `serve`. It never deletes a page, and on a keyless brain it never spends anything. When two serves share one brain, only one runs it and the other skips. Turn it off with `gbrain config set maintenance.auto false` (or `GBRAIN_SWEEP=0`, which also stops the idle sweep).++- `gbrain maintain --schedule` is for a brain with no agent session open most days. It installs a job that runs `gbrain maintain --unattended` every 6 hours (launchd on macOS, a systemd user timer on Linux, cron otherwise). It asks before installing, `--dry-run` shows exactly what it would write, and `--unschedule` removes it. Nothing installs it by default. A scheduled run that finds a live `gbrain serve` on the brain exits 0 with `maintenance_owned_by_serve` and leaves the work to serve.+- `gbrain init` and `gbrain setup <harness>` now say how upkeep works in their first-run settings block, and how to turn it off.+- doctor's overdue upkeep warning and `gbrain maintain --status` now also offer `gbrain maintain --schedule` as the second fix.+### Smaller changes- The old bookkeeping cleanup inside the cycle's `purge` phase is now its own phase, `bookkeeping_gc`, with the same retentions. It never touches a page, so upkeep can run it while `purge` stays manual. `purge`'s summary now counts only pages, sources and orphaned clone folders.@@ -36,6 +44,12 @@ identifiers and attribution are available in the pre-removal Git revision- `src/core/cycle.ts`: `CycleOpts.stamp` (`full`, `source_only`, `none`) so a partial run can't claim a full cycle, and `deferFactEmbedding` so fact extraction stays free on a keyed brain.- `src/commands/autopilot-refusals.ts` (new) and `src/core/error-registry.ts`: new codes `autopilot_no_repo`, `autopilot_pglite_daemon`, `cycle_already_running`, `engine_degraded`, `maintenance_disabled` and `maintenance_owned_by_autopilot`.- Tests: `test/maintenance-unattended.test.ts` (PGLite and Postgres) and `test/e2e/maintain-unattended-keyless-pglite.test.ts`.+- `src/core/maintenance/idle.ts` (new): `runIdleUpkeep` (the stdio serve calls it from its idle tick, after the sweep) and `armIdleUpkeep` (the HTTP serve's new idle timer), with a 3-second budget per run. `src/core/foreground-activity.ts` gains `onForegroundRequest`, which aborts a run in flight, and `src/commands/serve-http.ts` marks each `/mcp` POST as foreground work.+- `src/core/maintenance/run.ts`: a PGLite brain runs `CHECKPOINT` after a finished round, recorded as the `checkpoint` step.+- `src/commands/extract.ts`, `src/core/cycle.ts` and `src/core/cycle/connector-extract.ts`: the cycle's stale link drain now stops between batches of 25 pages when the cycle is aborted. Before, a first upkeep run on a 10,000-page brain with no repository spent 64 seconds in this one step, past its 3-second budget, and tool calls made meanwhile took about twice as long.+- `src/core/cycle/extract-facts.ts`: the facts walk now gives the event loop a turn every 50 pages. On PGLite, queries finish without ever letting timers or stdin run, so on a 10,000-page brain the walk froze the serve for about 2 seconds and a tool call sent during it waited until the walk ended (p99 1.7 seconds). With the fix, the freeze is under 150 ms, a call stops the walk, and tool calls during upkeep stay at p99 241 ms against 139 ms with upkeep off.+- `src/commands/maintain-schedule.ts` (new): `--schedule`, `--unschedule` and the live-serve check, routed before the engine opens. New codes `maintenance_owned_by_serve`, `schedule_unsupported` (Windows and containers) and `schedule_install_failed`.+- Tests: `test/serve-idle-upkeep-gbra438.test.ts`, `test/maintenance-idle-gbra438.test.ts` (PGLite and Postgres, including two serves on one brain), `test/maintain-schedule-gbra438.test.ts` and `test/e2e/serve-idle-upkeep-keyless-pglite.test.ts`.## [0.60.699.0] - 2026-11-12diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex dbca3b46bf..482d86e49f 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -428,7 +428,8 @@ and HTTP MCP) saves references as text without inline graph extraction; apost-commit `links` effect then adds plain mention edges to existing pages thewriter can see (`gbrain config set mcp.remote_auto_links off` disables it). Stdio`gbrain serve` runs bounded startup/idle sweeps for typed edges; `gbrain serve --http` does not-self-sweep. For HTTP, arrange explicit host-side `gbrain sweep --once` or+self-sweep, and its daily idle upkeep (link extraction included) is the only+graph work it does on its own. For HTTP, arrange explicit host-side `gbrain sweep --once` orextraction; use authorized `add_link` calls for edges needed immediately.After this step:@@ -632,7 +633,9 @@ Optional: skip this entire step for memory-only installs. Ask before schedulingcapture, enrichment, maintenance or a service; do not infer consent from asuccessful install or from a health recommendation.-Set up using your platform's scheduler (OpenClaw cron, Railway cron, crontab), or skip the+An open `gbrain serve` already runs the free upkeep while its agent is idle+(`gbrain maintain --status` shows the last run). For the jobs below, set up+using your platform's scheduler (OpenClaw cron, Railway cron, crontab), or skip theplatform glue entirely with `gbrain autopilot --install` (built-in self-maintaining daemon).Every cron job, workspace script and hook calls gbrain through **one wrapper**diff --git a/README.md b/README.mdindex 76077dd666..acd7633baf 100644--- a/README.md+++ b/README.md@@ -273,7 +273,7 @@ Want to see a tutorial that isn't here yet? [Open an issue](https://github.com/gThe whole loop is described in [`docs/architecture/topologies.md`](docs/architecture/topologies.md) with diagrams.-**Say to your agent:** *"Set up autopilot"* (installs the cron that runs the loop) — *"Run dream"* — *"Did the dream cycle run?"*+**Say to your agent:** *"Did upkeep run?"* (your agent's open `gbrain serve` runs the free upkeep while it is idle; `gbrain maintain --schedule` adds a timer for a brain no agent opens) — *"Run dream"* — *"Did the dream cycle run?"*## Capabilitiesdiff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 651f8f17d9..9f45135175 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -36,3 +36,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-migration-cli.ts` — pure, positive migration control contract, shared by the pre-engine CLI boundary and the command parser (re-exported by `commands/migrate-embeddings.ts`). Validates original argv as well as command arguments, so consumed global timeout/progress flags cannot evade validation. Unknown controls, unsupported equals forms, duplicate flags, missing values, invalid numeric ranges and unknown pace modes refuse rather than falling back, truncating, clamping or widening work. Only implemented globals are accepted; no new fact-only or deadline behavior. The flag-registry generator includes this peeled surface; the registry's embed/import unions do not define migration legality.- `test/migrate-embeddings-recovery-cli.serial.test.ts` — real migration CLI subprocesses over isolated synthetic PGLite brains. Pins recovery envelopes and private-safe help/stderr, then exercises unsupported scope/work flags, consumed timeout, malformed numeric controls, supported pacing/globals/status/help, zero dispatch and unchanged DB/config snapshots on both routes. Direct parser cases use the same adversarial matrix. Help directs deferred work back through the migration with the existing total authorization, never standalone/background embedding. The static `EMBEDDING_MIGRATION_RECOVERY` is shared with the local-only admin operation; its unchanged discriminators and restrictions remain covered by `test/migrate-embeddings-op-contract.serial.test.ts`. Archived pending projections still block destructive transitions; no silent restore or source exclusion is introduced.- `src/core/maintenance/run.ts` + `src/core/maintenance/status.ts` — GBRA-438 free unattended upkeep. `unattendedPlan` is the `--safe` list plus `bookkeeping_gc`, split into one global item (brain-wide phases, once per window under `gbrain-cycle`) and one item per source; cycles run with `stamp: 'none'` and `deferFactEmbedding` on a keyed brain. `runUnattendedMaintenance` never throws: preflight skips (`maintenance_disabled`, `engine_degraded`, `migrations_pending`, `maintenance_owned_by_autopilot` when `autopilot.last_global_at` is under 48h old, `write_capacity_backpressure`, `cycle_already_running`) exit 0; a failed step records its code (exit 1 for `maintain`) and three same-code failures back the step off to once a week. The embedding step runs under `maintenance.embed_daily_usd` (default $1 per UTC day, 0 = off; spend in `maintenance.embed_spend`). The record is `maintenance.last_run` (database config, so repo-less brains have one). `readUpkeepStatus` is the one view behind `--status` and doctor. Tests: `test/maintenance-unattended.test.ts` (both engines).+- `src/core/maintenance/idle.ts` + `src/commands/maintain-schedule.ts` — GBRA-438 PR 2, the upkeep runners. `runIdleUpkeep` runs `runUnattendedMaintenance` as runner `serve` with `IDLE_UPKEEP_BUDGET_MS` (3 s) when upkeep is on and due (`upkeepDue`); the stdio serve calls it from its idle tick after the sweep, in the same in-flight slot, and stdin data, `onForegroundRequest` or shutdown aborts it. `armIdleUpkeep` is the HTTP serve's idle timer: `mcpForegroundMiddleware` (in `src/core/foreground-activity.ts`, mounted on `/mcp` by `serve-http.ts`) marks each `/mcp` POST foreground, the first tick only opens the window, one run at a time. A finished round on PGLite ends with a `CHECKPOINT` step. `maintain-schedule.ts` is routed engine-free from `src/cli/main.ts`: `--schedule` (consent `persistent_install`, `--dry-run` preview) writes a wrapper and a launchd plist, systemd user service and timer, or a `# gbrain-maintain` crontab line (pure renderers, every 6 hours); Windows and containers refuse `schedule_unsupported`; `--unschedule` removes it. A scheduled `--unattended --runner schedule` run exits 0 `maintenance_owned_by_serve` while a live serve holds the brain (PGLite lock holder, or the CLI socket on Postgres). Tests: `test/serve-idle-upkeep-gbra438.test.ts`, `test/maintenance-idle-gbra438.test.ts` (both engines, two serves on one brain), `test/maintain-schedule-gbra438.test.ts`, `test/e2e/serve-idle-upkeep-keyless-pglite.test.ts`. The cycle hands its signal to the repo-less stale link drain (`extractStaleFromDB` `signal`), so a slice stops between 25-page batches, and `runExtractFacts` yields a macrotask every 50 pages of its walk, so a timer or stdin can trip the abort mid-walk on PGLite. Bench: `scripts/bench/serve-upkeep-latency.ts` (tool-call latency during idle upkeep on a keyless repo-less PGLite brain, against a sweep-only baseline).diff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.mdindex 79a714c0f0..f70c195f7c 100644--- a/docs/guides/cron-schedule.md+++ b/docs/guides/cron-schedule.md@@ -36,8 +36,14 @@ scheduling surfaces — reach for these first:hand-rolling the dream cycle below.- **`gbrain jobs` / minions** — queue shell jobs or LLM subagents with retry,backoff, and an audit trail. See the `minion-orchestrator` skill.-- **`gbrain autopilot`** — the long-lived background daemon that runs cycles- on its own cadence.+- **`gbrain serve`** — while the agent connected to it is idle, it runs the+ free upkeep (`gbrain maintain --unattended`) once a day, with nothing to+ install. `gbrain maintain --status` shows the last run.+- **`gbrain maintain --schedule`** — for a brain no agent opens most days:+ installs a job that runs the same upkeep every 6 hours (launchd, a systemd+ user timer or cron). Opt-in; preview with `--dry-run`.+- **`gbrain autopilot`** — the long-lived background daemon that runs full+ cycles on its own cadence, for a Postgres brain with a repo.- **`cron-scheduler` skill** (`skills/cron-scheduler/`) — teaches an agent tomanage its harness's scheduler.- **Bootstrap session-triggered schedules** — `gbrain bootstrap` installsdiff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 6131357d69..f2c77cf06e 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2994,6 +2994,14 @@ More: [docs/guides/cron-schedule.md#dream-beside-autopilot](../../docs/guides/cr|---|---|---|---|---|---|---|| An autopilot keeps this brain maintained (its brain-wide pass stamped autopilot.last_global_at within 48 hours), so free upkeep did nothing. | One owner per brain: the autopilot already runs the free phases and more, on any host sharing the database. | Nothing to do; gbrain autopilot --status shows the daemon. | agent | `repeat the read that failed` | 0 | no |+### maintenance_owned_by_serve++<a id="maintenance_owned_by_serve"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A live gbrain serve owns this brain and runs free upkeep while idle, so the scheduled upkeep run did nothing (serve owns upkeep). | One runner at a time: the serve holds the brain (the PGLite lock, or the warm CLI socket on Postgres) and runs the same free upkeep on its idle tick. | Nothing to do; gbrain maintain --status shows the last run and its runner. | agent | `repeat the read that failed` | 0 | no |+### managed_failure_unsettled<a id="managed_failure_unsettled"></a>@@ -4454,6 +4462,24 @@ More: [docs/guides/windowed-reads.md#revision_changed](../../docs/guides/windoweMore: [docs/guides/troubleshooting.md#runtime-build-skew](../../docs/guides/troubleshooting.md#runtime-build-skew)+### schedule_install_failed++<a id="schedule_install_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain maintain --schedule wrote its files, but the operating-system scheduler (launchctl, systemctl --user or crontab) refused the job. | The scheduler belongs to the host: a missing user session bus, a locked crontab or a launchd error stops the job from loading. | Read the scheduler error in the message, fix it on the host, then run gbrain maintain --schedule --yes again (gbrain maintain --unschedule removes the files). | user | `gbrain doctor --json` | 1 | no |++### schedule_unsupported++<a id="schedule_unsupported"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain maintain --schedule installed nothing: on Windows and in containers it has no installer. | Windows gets the schtasks line to add by hand (minimal Windows support). In a container an operating-system schedule does not survive a redeploy, so the resident gbrain serve is the upkeep runner there. | On Windows, add the printed schtasks line yourself. In a container, keep gbrain serve running; it runs free upkeep while idle. | agent | `repeat the read that failed` | 1 | no |++Reasons: `windows`, `container`.+### schema_lock_blocked<a id="schema_lock_blocked"></a>diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex db41ab855a..a73fb24e43 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -271,7 +271,7 @@ stdout (`--json`):"code": "first_run_decisions","kind": "ask","why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",- "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.","decisions": [{"id": "search_mode",@@ -370,6 +370,29 @@ stdout (`--json`):],"default": "skip","default_reason": "No agent harness was detected."+ },+ {+ "id": "upkeep",+ "question": "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.",+ "options": [+ {+ "id": "on",+ "label": "Keep free upkeep on (in effect now)"+ },+ {+ "id": "off",+ "label": "Turn free upkeep off",+ "argv": [+ "gbrain",+ "config",+ "set",+ "maintenance.auto",+ "false"+ ]+ }+ ],+ "default": "on",+ "default_reason": "In effect now: the agent's gbrain serve runs the free upkeep tier while idle; nothing needs an answer."}],"contract_version": 1@@ -379,7 +402,7 @@ stdout (`--json`):}```-stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.+stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`), `upkeep` (default `on`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.### 5. A caller mistake over stdio MCP, recorded: `run` (journey)@@ -1279,8 +1302,10 @@ each with a `fix`.embeddings needs a provider key and costs money (`credentials`, `paid`):ask first, then use the exact command the readiness fix names. It keepspages and facts.-- **Maintenance.** Without a worker, queued jobs wait. `gbrain autopilot- --install` installs a background service (`persistent_install`): ask first.+- **Maintenance.** An open `gbrain serve` runs free upkeep while idle+ (`gbrain maintain --status`). Without a worker, queued jobs wait.+ `gbrain maintain --schedule` and `gbrain autopilot --install` install a+ background service (`persistent_install`): ask first.- **Backup.** Repo backups exclude database-only pages and facts. When the`backup_coverage` notice fires, tell the user what is unprotected.- **Surface.** `--surface verbs` (memory verbs), `starter` or `full` decidesdiff --git a/llms-full.txt b/llms-full.txtindex 17bc03954f..b8cf7b9a20 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2272,7 +2272,8 @@ and HTTP MCP) saves references as text without inline graph extraction; apost-commit `links` effect then adds plain mention edges to existing pages thewriter can see (`gbrain config set mcp.remote_auto_links off` disables it). Stdio`gbrain serve` runs bounded startup/idle sweeps for typed edges; `gbrain serve --http` does not-self-sweep. For HTTP, arrange explicit host-side `gbrain sweep --once` or+self-sweep, and its daily idle upkeep (link extraction included) is the only+graph work it does on its own. For HTTP, arrange explicit host-side `gbrain sweep --once` orextraction; use authorized `add_link` calls for edges needed immediately.After this step:@@ -2476,7 +2477,9 @@ Optional: skip this entire step for memory-only installs. Ask before schedulingcapture, enrichment, maintenance or a service; do not infer consent from asuccessful install or from a health recommendation.-Set up using your platform's scheduler (OpenClaw cron, Railway cron, crontab), or skip the+An open `gbrain serve` already runs the free upkeep while its agent is idle+(`gbrain maintain --status` shows the last run). For the jobs below, set up+using your platform's scheduler (OpenClaw cron, Railway cron, crontab), or skip theplatform glue entirely with `gbrain autopilot --install` (built-in self-maintaining daemon).Every cron job, workspace script and hook calls gbrain through **one wrapper**@@ -3025,7 +3028,7 @@ stdout (`--json`):"code": "first_run_decisions","kind": "ask","why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",- "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.","decisions": [{"id": "search_mode",@@ -3124,6 +3127,29 @@ stdout (`--json`):],"default": "skip","default_reason": "No agent harness was detected."+ },+ {+ "id": "upkeep",+ "question": "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.",+ "options": [+ {+ "id": "on",+ "label": "Keep free upkeep on (in effect now)"+ },+ {+ "id": "off",+ "label": "Turn free upkeep off",+ "argv": [+ "gbrain",+ "config",+ "set",+ "maintenance.auto",+ "false"+ ]+ }+ ],+ "default": "on",+ "default_reason": "In effect now: the agent's gbrain serve runs the free upkeep tier while idle; nothing needs an answer."}],"contract_version": 1@@ -3133,7 +3159,7 @@ stdout (`--json`):}```-stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.+stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`), `upkeep` (default `on`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.### 5. A caller mistake over stdio MCP, recorded: `run` (journey)@@ -4033,8 +4059,10 @@ each with a `fix`.embeddings needs a provider key and costs money (`credentials`, `paid`):ask first, then use the exact command the readiness fix names. It keepspages and facts.-- **Maintenance.** Without a worker, queued jobs wait. `gbrain autopilot- --install` installs a background service (`persistent_install`): ask first.+- **Maintenance.** An open `gbrain serve` runs free upkeep while idle+ (`gbrain maintain --status`). Without a worker, queued jobs wait.+ `gbrain maintain --schedule` and `gbrain autopilot --install` install a+ background service (`persistent_install`): ask first.- **Backup.** Repo backups exclude database-only pages and facts. When the`backup_coverage` notice fires, tell the user what is unprotected.- **Surface.** `--surface verbs` (memory verbs), `starter` or `full` decides@@ -4248,7 +4276,7 @@ off until the user opts in, and paid enrichment is a separate choice.| "Extract links", "build link graph", "populate timeline" | `skills/maintain/SKILL.md` (extraction sections) || "Run dream", "process today's session", "synthesize my conversations", "consolidate yesterday's conversations", "what patterns did you see", "did the dream cycle run", "retriage the backlog", "re-score the triage" | `skills/maintain/SKILL.md` (dream cycle section) || "Brain health", "what features am I missing", "brain score" | Run `gbrain features --json` |-| "Set up autopilot", "run brain maintenance", "keep brain updated" | Run `gbrain autopilot --install --repo ~/brain` |+| "Set up autopilot", "run brain maintenance", "keep brain updated" | Run `gbrain maintain --status`. An open `gbrain serve` runs free upkeep while idle. For a brain no agent opens most days, offer `gbrain maintain --schedule` (asks consent). A Postgres brain with a repo can use `gbrain autopilot --install --repo ~/brain` || "Upgrade gbrain", "update gbrain", "gbrain update available", `UPGRADE_AVAILABLE`, "is gbrain up to date" | `skills/gbrain-upgrade/SKILL.md` || Agent identity, "who am I", customize agent | `skills/soul-audit/SKILL.md` || "Populate links", "extract links", "backfill graph" | `skills/maintain/SKILL.md` (graph population phase) |@@ -4572,7 +4600,7 @@ Want to see a tutorial that isn't here yet? [Open an issue](https://github.com/gThe whole loop is described in [`docs/architecture/topologies.md`](docs/architecture/topologies.md) with diagrams.-**Say to your agent:** *"Set up autopilot"* (installs the cron that runs the loop) — *"Run dream"* — *"Did the dream cycle run?"*+**Say to your agent:** *"Did upkeep run?"* (your agent's open `gbrain serve` runs the free upkeep while it is idle; `gbrain maintain --schedule` adds a timer for a brain no agent opens) — *"Run dream"* — *"Did the dream cycle run?"*## Capabilities@@ -7064,8 +7092,14 @@ scheduling surfaces — reach for these first:hand-rolling the dream cycle below.- **`gbrain jobs` / minions** — queue shell jobs or LLM subagents with retry,backoff, and an audit trail. See the `minion-orchestrator` skill.-- **`gbrain autopilot`** — the long-lived background daemon that runs cycles- on its own cadence.+- **`gbrain serve`** — while the agent connected to it is idle, it runs the+ free upkeep (`gbrain maintain --unattended`) once a day, with nothing to+ install. `gbrain maintain --status` shows the last run.+- **`gbrain maintain --schedule`** — for a brain no agent opens most days:+ installs a job that runs the same upkeep every 6 hours (launchd, a systemd+ user timer or cron). Opt-in; preview with `--dry-run`.+- **`gbrain autopilot`** — the long-lived background daemon that runs full+ cycles on its own cadence, for a Postgres brain with a repo.- **`cron-scheduler` skill** (`skills/cron-scheduler/`) — teaches an agent tomanage its harness's scheduler.- **Bootstrap session-triggered schedules** — `gbrain bootstrap` installsdiff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.mdindex 380572da6e..ad77ec47f4 100644--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md@@ -273,7 +273,7 @@ stdout (`--json`):"code": "first_run_decisions","kind": "ask","why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",- "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.","decisions": [{"id": "search_mode",@@ -372,6 +372,29 @@ stdout (`--json`):],"default": "skip","default_reason": "No agent harness was detected."+ },+ {+ "id": "upkeep",+ "question": "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.",+ "options": [+ {+ "id": "on",+ "label": "Keep free upkeep on (in effect now)"+ },+ {+ "id": "off",+ "label": "Turn free upkeep off",+ "argv": [+ "gbrain",+ "config",+ "set",+ "maintenance.auto",+ "false"+ ]+ }+ ],+ "default": "on",+ "default_reason": "In effect now: the agent's gbrain serve runs the free upkeep tier while idle; nothing needs an answer."}],"contract_version": 1@@ -381,7 +404,7 @@ stdout (`--json`):}```-stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.+stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`), `upkeep` (default `on`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.### 5. A caller mistake over stdio MCP, recorded: `run` (journey)@@ -1281,8 +1304,10 @@ each with a `fix`.embeddings needs a provider key and costs money (`credentials`, `paid`):ask first, then use the exact command the readiness fix names. It keepspages and facts.-- **Maintenance.** Without a worker, queued jobs wait. `gbrain autopilot- --install` installs a background service (`persistent_install`): ask first.+- **Maintenance.** An open `gbrain serve` runs free upkeep while idle+ (`gbrain maintain --status`). Without a worker, queued jobs wait.+ `gbrain maintain --schedule` and `gbrain autopilot --install` install a+ background service (`persistent_install`): ask first.- **Backup.** Repo backups exclude database-only pages and facts. When the`backup_coverage` notice fires, tell the user what is unprotected.- **Surface.** `--surface verbs` (memory verbs), `starter` or `full` decidesdiff --git a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.mdindex e706eefeda..59bc1c0665 100644--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md@@ -303,8 +303,11 @@ a colon (`Source: Summary`) is prose, so the row keeps `source: markdown` and thwhole text as its summary.Note: extracted entries improve structured queries (`gbrain timeline`), not vector search.-### Autopilot check-Verify autopilot is running:+### Upkeep and autopilot check+`gbrain maintain --status` shows the last free-upkeep run, which an open+`gbrain serve` does while idle. For a brain no agent opens most days, offer+`gbrain maintain --schedule` (asks consent). On a Postgres brain with a repo,+verify autopilot:```bashgbrain autopilot --status```diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.mdindex 380572da6e..ad77ec47f4 100644--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md@@ -273,7 +273,7 @@ stdout (`--json`):"code": "first_run_decisions","kind": "ask","why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",- "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.","decisions": [{"id": "search_mode",@@ -372,6 +372,29 @@ stdout (`--json`):],"default": "skip","default_reason": "No agent harness was detected."+ },+ {+ "id": "upkeep",+ "question": "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.",+ "options": [+ {+ "id": "on",+ "label": "Keep free upkeep on (in effect now)"+ },+ {+ "id": "off",+ "label": "Turn free upkeep off",+ "argv": [+ "gbrain",+ "config",+ "set",+ "maintenance.auto",+ "false"+ ]+ }+ ],+ "default": "on",+ "default_reason": "In effect now: the agent's gbrain serve runs the free upkeep tier while idle; nothing needs an answer."}],"contract_version": 1@@ -381,7 +404,7 @@ stdout (`--json`):}```-stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.+stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`), `upkeep` (default `on`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.### 5. A caller mistake over stdio MCP, recorded: `run` (journey)@@ -1281,8 +1304,10 @@ each with a `fix`.embeddings needs a provider key and costs money (`credentials`, `paid`):ask first, then use the exact command the readiness fix names. It keepspages and facts.-- **Maintenance.** Without a worker, queued jobs wait. `gbrain autopilot- --install` installs a background service (`persistent_install`): ask first.+- **Maintenance.** An open `gbrain serve` runs free upkeep while idle+ (`gbrain maintain --status`). Without a worker, queued jobs wait.+ `gbrain maintain --schedule` and `gbrain autopilot --install` install a+ background service (`persistent_install`): ask first.- **Backup.** Repo backups exclude database-only pages and facts. When the`backup_coverage` notice fires, tell the user what is unprotected.- **Surface.** `--surface verbs` (memory verbs), `starter` or `full` decidesdiff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.mdindex 380572da6e..ad77ec47f4 100644--- a/plugin/skills/conventions/agent-operator-protocol.md+++ b/plugin/skills/conventions/agent-operator-protocol.md@@ -273,7 +273,7 @@ stdout (`--json`):"code": "first_run_decisions","kind": "ask","why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",- "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.","decisions": [{"id": "search_mode",@@ -372,6 +372,29 @@ stdout (`--json`):],"default": "skip","default_reason": "No agent harness was detected."+ },+ {+ "id": "upkeep",+ "question": "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.",+ "options": [+ {+ "id": "on",+ "label": "Keep free upkeep on (in effect now)"+ },+ {+ "id": "off",+ "label": "Turn free upkeep off",+ "argv": [+ "gbrain",+ "config",+ "set",+ "maintenance.auto",+ "false"+ ]+ }+ ],+ "default": "on",+ "default_reason": "In effect now: the agent's gbrain serve runs the free upkeep tier while idle; nothing needs an answer."}],"contract_version": 1@@ -381,7 +404,7 @@ stdout (`--json`):}```-stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.+stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`), `upkeep` (default `on`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.### 5. A caller mistake over stdio MCP, recorded: `run` (journey)@@ -1281,8 +1304,10 @@ each with a `fix`.embeddings needs a provider key and costs money (`credentials`, `paid`):ask first, then use the exact command the readiness fix names. It keepspages and facts.-- **Maintenance.** Without a worker, queued jobs wait. `gbrain autopilot- --install` installs a background service (`persistent_install`): ask first.+- **Maintenance.** An open `gbrain serve` runs free upkeep while idle+ (`gbrain maintain --status`). Without a worker, queued jobs wait.+ `gbrain maintain --schedule` and `gbrain autopilot --install` install a+ background service (`persistent_install`): ask first.- **Backup.** Repo backups exclude database-only pages and facts. When the`backup_coverage` notice fires, tell the user what is unprotected.- **Surface.** `--surface verbs` (memory verbs), `starter` or `full` decidesdiff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.mdindex e706eefeda..59bc1c0665 100644--- a/plugin/skills/maintain/SKILL.md+++ b/plugin/skills/maintain/SKILL.md@@ -303,8 +303,11 @@ a colon (`Source: Summary`) is prose, so the row keeps `source: markdown` and thwhole text as its summary.Note: extracted entries improve structured queries (`gbrain timeline`), not vector search.-### Autopilot check-Verify autopilot is running:+### Upkeep and autopilot check+`gbrain maintain --status` shows the last free-upkeep run, which an open+`gbrain serve` does while idle. For a brain no agent opens most days, offer+`gbrain maintain --schedule` (asks consent). On a Postgres brain with a repo,+verify autopilot:```bashgbrain autopilot --status```diff --git a/scripts/bench/serve-upkeep-latency.ts b/scripts/bench/serve-upkeep-latency.tsnew file mode 100644index 0000000000..f3c1b9edbc--- /dev/null+++ b/scripts/bench/serve-upkeep-latency.ts@@ -0,0 +1,154 @@+#!/usr/bin/env bun+/**+ * GBRA-438 PR 2: how much tool-call latency idle upkeep adds inside a stdio `gbrain serve` on a keyless, repo-less+ * PGLite brain (the default install).+ *+ * Builds a brain of --pages pages, each linking to --links others and carrying one timeline line, imported with+ * --no-embed so its links and timeline are stale. Then, per arm, it starts a stdio serve on a fresh copy of that brain+ * with a --interval-ms idle tick and sends MCP `search` calls after random quiet gaps (--gap-ms min-max). Arm `upkeep`+ * leaves upkeep on; arm `baseline` sets maintenance.auto false, so only the existing idle sweep runs. Each call is+ * tagged by what the serve was doing when it was sent (read from its stderr): `upkeep`, `sweep` or `idle`. A copy+ * whose upkeep round has finished is replaced by a fresh one until --calls calls landed during upkeep (or --max-copies).+ * Copies are restored into the same path (the brain's config and owner files record it), from a snapshot of .gbrain.+ *+ * bun scripts/bench/serve-upkeep-latency.ts --pages 1401 --out ~/upkeep-latency [--calls 150] [--links 3]+ * [--interval-ms 1000] [--gap-ms 1200-3200] [--baseline-calls 150] [--max-copies 8]+ *+ * Writes calls.jsonl and summary.json under --out and prints p50/p95/p99/max per arm and tag.+ */+import { appendFileSync, cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';++const argv = process.argv.slice(2);+const flag = (name: string, fallback: string) => { const i = argv.indexOf('--' + name); return i >= 0 ? argv[i + 1]! : fallback; };+const PAGES = Number(flag('pages', '1401')), LINKS = Number(flag('links', '3'));+const CALLS = Number(flag('calls', '150')), BASELINE_CALLS = Number(flag('baseline-calls', flag('calls', '150')));+const INTERVAL_MS = Number(flag('interval-ms', '1000')), MAX_COPIES = Number(flag('max-copies', '8'));+const [GAP_MIN, GAP_MAX] = flag('gap-ms', '1200-3200').split('-').map(Number) as [number, number];+const OUT = resolve(flag('out', join(process.cwd(), 'upkeep-latency')));+const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');+const WORDS = ['alpha', 'harbor', 'ledger', 'orbit', 'meadow', 'signal', 'copper', 'lantern', 'summit', 'river', 'quartz', 'falcon'];++function keylessEnv(home: string, extra: Record<string, string> = {}): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'JEV_TYPESAFE_API_KEY']) delete env[k];+ return { ...env, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', ...extra };+}++async function gbrain(home: string, args: string[]): Promise<void> {+ const p = Bun.spawn([process.execPath, '--no-env-file', CLI, ...args], { cwd: home, env: keylessEnv(home), stdout: 'pipe', stderr: 'pipe' });+ const [code, err] = await Promise.all([p.exited, new Response(p.stderr).text()]);+ if (code !== 0) throw new Error(`gbrain ${args.join(' ')} exited ${code}: ${err.slice(-2000)}`);+}++const quantile = (xs: number[], q: number) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.min(s.length - 1, Math.ceil(q * s.length) - 1)]! : NaN; };+const stats = (xs: number[]) => ({ n: xs.length, p50: quantile(xs, 0.5), p95: quantile(xs, 0.95), p99: quantile(xs, 0.99), max: xs.length ? Math.max(...xs) : NaN });+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++async function buildPristine(): Promise<string> {+ const home = join(OUT, 'brain');+ if (existsSync(join(OUT, 'snapshot', 'built'))) return home;+ rmSync(home, { recursive: true, force: true });+ mkdirSync(join(home, 'notes'), { recursive: true });+ const started = Date.now();+ await gbrain(home, ['init', '--pglite', '--no-embedding', '--non-interactive']);+ const name = (i: number) => `p${String(i).padStart(5, '0')}`;+ for (let i = 0; i < PAGES; i++) {+ const links = Array.from({ length: LINKS }, (_, k) => `[[${name((i * 7919 + k * 104729 + 1) % PAGES)}]]`).join(', ');+ const words = Array.from({ length: 6 }, (_, k) => WORDS[(i + k * 5) % WORDS.length]).join(' ');+ const day = String(1 + (i % 28)).padStart(2, '0'), month = String(1 + (i % 12)).padStart(2, '0');+ writeFileSync(join(home, 'notes', `${name(i)}.md`), `---\ntitle: Page ${i}\ntype: concept\n---\n# Page ${i}\n\nPage ${i} is about ${words}. It relates to ${links}.\n\n## Timeline\n\n- **2026-${month}-${day}** | Notes — Page ${i} was reviewed.\n`);+ }+ await gbrain(home, ['import', join(home, 'notes'), '--no-embed']);+ cpSync(join(home, '.gbrain'), join(OUT, 'snapshot', '.gbrain'), { recursive: true });+ writeFileSync(join(OUT, 'snapshot', 'built'), `${Date.now() - started}\n`);+ console.log(`built ${PAGES} pages in ${Math.round((Date.now() - started) / 1000)} s`);+ return home;+}++interface Call { arm: string; copy: number; tag: 'upkeep' | 'sweep' | 'idle'; ms: number; ok: boolean }++async function runCopy(arm: 'upkeep' | 'baseline', copy: number, home: string, want: () => boolean, record: (c: Call) => void): Promise<{ upkeepFinished: number[]; roundDone: boolean }> {+ rmSync(join(home, '.gbrain'), { recursive: true, force: true });+ cpSync(join(OUT, 'snapshot', '.gbrain'), join(home, '.gbrain'), { recursive: true });+ if (arm === 'baseline') await gbrain(home, ['config', 'set', 'maintenance.auto', 'false']);+ const serve = Bun.spawn([process.execPath, '--no-env-file', CLI, 'serve'], { cwd: home, env: keylessEnv(home, { GBRAIN_SWEEP_IDLE_INTERVAL_MS: String(INTERVAL_MS) }), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });+ let log = '';+ const pending = new Map<number, (ok: boolean) => void>();+ const errReader = (async () => { for await (const chunk of serve.stderr) { const text = new TextDecoder().decode(chunk); log += text; appendFileSync(join(OUT, `${arm}-${copy}.serve.log`), text); } })();+ const outReader = (async () => {+ let buf = '';+ for await (const chunk of serve.stdout) {+ buf += new TextDecoder().decode(chunk);+ let nl: number;+ while ((nl = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, nl); buf = buf.slice(nl + 1);+ try { const msg = JSON.parse(line); if (typeof msg.id === 'number') { pending.get(msg.id)?.(!msg.error && !msg.result?.isError); pending.delete(msg.id); } } catch { /* not a JSON-RPC line */ }+ }+ }+ })();+ let nextId = 1;+ const send = (method: string, params: unknown) => new Promise<boolean>((res) => {+ const id = nextId++;+ pending.set(id, res);+ serve.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');+ serve.stdin.flush();+ });+ const count = (re: RegExp) => (log.match(re) ?? []).length;+ const tagNow = (): Call['tag'] => count(/idle upkeep: started/g) > count(/idle upkeep: finished/g) ? 'upkeep' : count(/idle sweep: started/g) > count(/idle sweep: finished/g) ? 'sweep' : 'idle';+ let roundDone = false;+ try {+ await send('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'upkeep-latency', version: '1' } });+ serve.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');+ for (let w = 0; w < 5; w++) await send('tools/call', { name: 'search', arguments: { query: WORDS[w]! } });+ let quietSince = Date.now(), lastStarts = count(/idle upkeep: started/g), i = 0;+ while (want()) {+ await sleep(GAP_MIN + Math.random() * (GAP_MAX - GAP_MIN));+ const tag = tagNow();+ const t0 = performance.now();+ const ok = await send('tools/call', { name: 'search', arguments: { query: WORDS[i++ % WORDS.length]! } });+ record({ arm, copy, tag, ms: Math.round((performance.now() - t0) * 10) / 10, ok });+ const starts = count(/idle upkeep: started/g);+ if (starts !== lastStarts) { lastStarts = starts; quietSince = Date.now(); }+ if (arm === 'upkeep' && Date.now() - quietSince > Math.max(20_000, 8 * GAP_MAX)) { roundDone = true; break; }+ }+ } finally {+ serve.stdin.end();+ const killer = setTimeout(() => serve.kill(9), 20_000);+ await serve.exited;+ clearTimeout(killer);+ await Promise.allSettled([errReader, outReader]);+ }+ const upkeepFinished = [...log.matchAll(/idle upkeep: finished in (\d+) ms/g)].map((m) => Number(m[1]));+ return { upkeepFinished, roundDone };+}++mkdirSync(OUT, { recursive: true });+rmSync(join(OUT, 'calls.jsonl'), { force: true });+const home = await buildPristine();+const calls: Call[] = [];+const record = (c: Call) => { calls.push(c); appendFileSync(join(OUT, 'calls.jsonl'), JSON.stringify(c) + '\n'); };+const duringUpkeep = () => calls.filter((c) => c.arm === 'upkeep' && c.tag === 'upkeep').length;+const runs: Record<string, unknown>[] = [];++let baselineCalls = 0;+await runCopy('baseline', 0, home, () => baselineCalls++ < BASELINE_CALLS, record);+for (let copy = 0; copy < MAX_COPIES && duringUpkeep() < CALLS; copy++) {+ const r = await runCopy('upkeep', copy, home, () => duringUpkeep() < CALLS, record);+ runs.push({ copy, round_done: r.roundDone, upkeep_slices: r.upkeepFinished.length, slice_ms: stats(r.upkeepFinished) });+}++const pick = (arm: string, tag?: string) => calls.filter((c) => c.arm === arm && (!tag || c.tag === tag)).map((c) => c.ms);+const base = stats(pick('baseline'));+const during = stats(pick('upkeep', 'upkeep'));+const summary = {+ pages: PAGES, links: LINKS, interval_ms: INTERVAL_MS, gap_ms: [GAP_MIN, GAP_MAX],+ baseline_all: base, upkeep_arm_all: stats(pick('upkeep')),+ upkeep_arm_by_tag: { upkeep: during, sweep: stats(pick('upkeep', 'sweep')), idle: stats(pick('upkeep', 'idle')) },+ added_vs_baseline_ms: { p95: during.p95 - base.p95, p99: during.p99 - base.p99, max: during.max - base.max },+ failed_calls: calls.filter((c) => !c.ok).length,+ copies: runs,+};+writeFileSync(join(OUT, 'summary.json'), JSON.stringify(summary, null, 2) + '\n');+console.log(JSON.stringify(summary, null, 2));diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsvindex b61e808291..1bf448148d 100644--- a/scripts/core-world-reads-baseline.tsv+++ b/scripts/core-world-reads-baseline.tsv@@ -411,6 +411,7 @@ src/core/fence-scan.ts process_env 1 W6: settings plane out of the coresrc/core/file-resolver.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/filing-audit.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/fix-routing.ts module_collection 1 W6: per-engine state, or mark as a constant table+src/core/foreground-activity.ts module_collection 1 GBRA-438: the process-wide foreground-request listeners idle upkeep aborts on, alongside the module's process-wide in-flight counter; moves with per-engine serve state in W6src/core/forward-progress.ts module_collection 2 W6: per-engine state, or mark as a constant tablesrc/core/friction.ts fs_import 1 W7: filesystem boundary moves to the local appsrc/core/friction.ts process_env 1 W6: settings plane out of the corediff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 0384008d84..d8ac6835b5 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -21,7 +21,7 @@ src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomsrc/commands/import.ts runImport 978 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts); +1 Wave B lane 1d (TODO wave-b PR 1): reads the segmented-storage policy once per run for the streamed import of files over the single-string ceiling; +1 GBRA-218 A2: the import barrier installs the tree's folder rules before any page (logic in access/policy-transfer.ts); +4 GST-2462: the noticeRun option, the privacy_label_ignored notice call and its JSON and result fields (logic in core/search/ignored-privacy-labels.ts)src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/serve.ts installStdioLifecycle 323 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff)+src/commands/serve.ts installStdioLifecycle 326 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff); +3 GBRA-438 PR 2: the idle upkeep slot, its shutdown stop and the upkeep step after the idle sweep (logic in idleUpkeepSlot)src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 4 #5673: connector sources print that autopilot keeps them synced after the first syncsrc/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/brainstorm/orchestrator.ts _runBrainstormInner 413 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5890 close-set spreads INTERNAL_BREADTH_SEARCH_OPTS@@ -31,7 +31,7 @@ src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refasrc/core/context/retrieval-reflex.ts resolveEntitiesToPointers 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 fix wave 11 #6195: multi-word weak n-gram norms and the weak-title arm call (logic in weakTitleHits)src/core/cycle.ts runCycleUnscoped 1290 #6696 (A5): the body of runCycle, renamed when runCycle became its background-origin wrapper (9 lines shorter); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts); +6 #6188: fence_repair phase dispatch block (logic in cycle/fence-repair.ts); +2 fix wave 12 #6242: lease-set result and the maintenance-busy skip call (logic in skipBrainWidePhases and cycle/lock-set.ts); +7 C4: standing_questions phase dispatch block (logic in questions/phase.ts); +13 GBRA-438: bookkeeping_gc phase dispatch block (logic in cycle/bookkeeping-gc.ts) and the CycleOpts.stamp switch on the freshness stamp blocksrc/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallback-src/core/cycle/extract-facts.ts runExtractFacts 382 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count; +2 #6259 (landed alongside): a quarantined page projects no fence facts; +1 #5575 I2 (L1a-taint): the run result sums the write-gate tally each page reconcile returns; +1 merge v0.60.249.0: Wave B PR 1 segmented-page skip (+4, absorbed before) and master growth compose at 382+src/core/cycle/extract-facts.ts runExtractFacts 384 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); -129 wave 9 follow-ups (receipts): the page reconcile plan and writes moved into planFenceReconcile/reconcileWrites/writeFenceReconcile, shared with the managed preparer; +2 #6264 (landed alongside): ontology observations never gate the unfenced-rows count; +2 #6259 (landed alongside): a quarantined page projects no fence facts; +1 #5575 I2 (L1a-taint): the run result sums the write-gate tally each page reconcile returns; +1 merge v0.60.249.0: Wave B PR 1 segmented-page skip (+4, absorbed before) and master growth compose at 382; +2 GBRA-438 PR 2: the reconcile walk yields a macrotask every 50 pages so an abort from a timer or stdin lands mid-walk on PGLitesrc/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/propose-takes.ts ProposeTakesPhase.process 430 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout); +1 #5425 [UC4]: the one attribution-check call after the extractor returns (logic in propose-takes-attribution.ts)src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts); +8 #6643 PR B: drifted concepts skipped before spend (state and the live check in persistence/drift-conflicts.ts ConceptDriftSkips), with the warn status, summary clause and skipped_file_drift details; +10 #7269 (GBRA-161 PR 4): a T3 group hashes without the synthesis model, and a rewrite that would leave a deterministic-tier page at its current template body and visibility is skipped unchanged; -94 GBRA-60 G6: the publication steps (managed batches, provenance edges, world promotion) moved to cycle/concept-writes.tsdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 49992fe91b..2c8b6bd480 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli/main.ts 3002 ratchet +32 GST-2476 G2: enforced member gate call, static-help fallback, socket and delegate skips, read/write dispatch seams and receipt recording (logic in cli/enforced-member.ts); +3 GBRA-156: thin-client page-cap line on stderr in formatResult (import and two lines; +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured); re-summed at the 0.60.484.0 merge with #7598 (2959 measured); +3 GBRA-218 local --as: the access SELF_HELP_WITHOUT_ENGINE row, the --as refusal call and the preview open (logic in cli/as-preview.ts); re-summed at the GBRA-218 merge with #7593 (2962 measured); +3 #8426: serve captures the session directory the hook launcher records (import, comment, call; logic in core/session-cwd.ts); re-summed at the train R merge with v0.60.574.0: 2965 + 2; re-summed at the memory train #8481 merge with v0.60.576.0 (2970 measured); +4 GBRA-224: the startup hook resolves the release channel and prints the one-time channel notice (logic in core/release-channel-notice.ts, core/self-upgrade.ts; fits the master ceiling at the GBRA-346 merge: master 2956 + 4 = 2960)+src/cli/main.ts 3004 ratchet +32 GST-2476 G2: enforced member gate call, static-help fallback, socket and delegate skips, read/write dispatch seams and receipt recording (logic in cli/enforced-member.ts); +3 GBRA-156: thin-client page-cap line on stderr in formatResult (import and two lines; +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured); re-summed at the 0.60.484.0 merge with #7598 (2959 measured); +3 GBRA-218 local --as: the access SELF_HELP_WITHOUT_ENGINE row, the --as refusal call and the preview open (logic in cli/as-preview.ts); re-summed at the GBRA-218 merge with #7593 (2962 measured); +3 #8426: serve captures the session directory the hook launcher records (import, comment, call; logic in core/session-cwd.ts); re-summed at the train R merge with v0.60.574.0: 2965 + 2; re-summed at the memory train #8481 merge with v0.60.576.0 (2970 measured); +4 GBRA-224: the startup hook resolves the release channel and prints the one-time channel notice (logic in core/release-channel-notice.ts, core/self-upgrade.ts; fits the master ceiling at the GBRA-346 merge: master 2956 + 4 = 2960); +2 GBRA-438 PR 2: the engine-free maintain route (--schedule, --unschedule, a scheduled run beside a live serve) and its comment (logic in commands/maintain-schedule.ts)src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)src/commands/doctor.ts 700 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks)src/commands/embed.ts 2306 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +2 agent operator wave D2: --json failure envelope via writeCliError@@ -49,6 +49,6 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1767 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +6 GBRA-438 PR 1: the wave comment and five rows (unattended_maintenance_doctor, bookkeeping_gc_phase, autopilot_refusals_structured, cycle_skip_text, cycle_freshness_keyless_consent; since TBD until the merge slot; rows are data and cannot move)+src/core/behavior-change-notice.ts 1771 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +6 GBRA-438 PR 1: the wave comment and five rows (unattended_maintenance_doctor, bookkeeping_gc_phase, autopilot_refusals_structured, cycle_skip_text, cycle_freshness_keyless_consent; since TBD until the merge slot; rows are data and cannot move); +4 GBRA-438 PR 2: the wave comment and three rows (serve_idle_upkeep, serve_http_idle_timer, init_upkeep_line; since TBD until the merge slot; rows are data and cannot move)src/core/git/commit-push.ts 1658 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot movediff --git a/skills/RESOLVER.md b/skills/RESOLVER.mdindex 4a0bd45fc8..ea4393f4cd 100644--- a/skills/RESOLVER.md+++ b/skills/RESOLVER.md@@ -180,7 +180,7 @@ off until the user opts in, and paid enrichment is a separate choice.| "Extract links", "build link graph", "populate timeline" | `skills/maintain/SKILL.md` (extraction sections) || "Run dream", "process today's session", "synthesize my conversations", "consolidate yesterday's conversations", "what patterns did you see", "did the dream cycle run", "retriage the backlog", "re-score the triage" | `skills/maintain/SKILL.md` (dream cycle section) || "Brain health", "what features am I missing", "brain score" | Run `gbrain features --json` |-| "Set up autopilot", "run brain maintenance", "keep brain updated" | Run `gbrain autopilot --install --repo ~/brain` |+| "Set up autopilot", "run brain maintenance", "keep brain updated" | Run `gbrain maintain --status`. An open `gbrain serve` runs free upkeep while idle. For a brain no agent opens most days, offer `gbrain maintain --schedule` (asks consent). A Postgres brain with a repo can use `gbrain autopilot --install --repo ~/brain` || "Upgrade gbrain", "update gbrain", "gbrain update available", `UPGRADE_AVAILABLE`, "is gbrain up to date" | `skills/gbrain-upgrade/SKILL.md` || Agent identity, "who am I", customize agent | `skills/soul-audit/SKILL.md` || "Populate links", "extract links", "backfill graph" | `skills/maintain/SKILL.md` (graph population phase) |diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.mdindex 380572da6e..ad77ec47f4 100644--- a/skills/conventions/agent-operator-protocol.md+++ b/skills/conventions/agent-operator-protocol.md@@ -273,7 +273,7 @@ stdout (`--json`):"code": "first_run_decisions","kind": "ask","why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",- "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.","decisions": [{"id": "search_mode",@@ -372,6 +372,29 @@ stdout (`--json`):],"default": "skip","default_reason": "No agent harness was detected."+ },+ {+ "id": "upkeep",+ "question": "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.",+ "options": [+ {+ "id": "on",+ "label": "Keep free upkeep on (in effect now)"+ },+ {+ "id": "off",+ "label": "Turn free upkeep off",+ "argv": [+ "gbrain",+ "config",+ "set",+ "maintenance.auto",+ "false"+ ]+ }+ ],+ "default": "on",+ "default_reason": "In effect now: the agent's gbrain serve runs the free upkeep tier while idle; nothing needs an answer."}],"contract_version": 1@@ -381,7 +404,7 @@ stdout (`--json`):}```-stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.+stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `writeback` (default `salient`), `harness_wiring` (default `skip`), `upkeep` (default `on`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.### 5. A caller mistake over stdio MCP, recorded: `run` (journey)@@ -1281,8 +1304,10 @@ each with a `fix`.embeddings needs a provider key and costs money (`credentials`, `paid`):ask first, then use the exact command the readiness fix names. It keepspages and facts.-- **Maintenance.** Without a worker, queued jobs wait. `gbrain autopilot- --install` installs a background service (`persistent_install`): ask first.+- **Maintenance.** An open `gbrain serve` runs free upkeep while idle+ (`gbrain maintain --status`). Without a worker, queued jobs wait.+ `gbrain maintain --schedule` and `gbrain autopilot --install` install a+ background service (`persistent_install`): ask first.- **Backup.** Repo backups exclude database-only pages and facts. When the`backup_coverage` notice fires, tell the user what is unprotected.- **Surface.** `--surface verbs` (memory verbs), `starter` or `full` decidesdiff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.mdindex fd0ffc7d77..4280452a6e 100644--- a/skills/maintain/SKILL.md+++ b/skills/maintain/SKILL.md@@ -302,8 +302,11 @@ a colon (`Source: Summary`) is prose, so the row keeps `source: markdown` and thwhole text as its summary.Note: extracted entries improve structured queries (`gbrain timeline`), not vector search.-### Autopilot check-Verify autopilot is running:+### Upkeep and autopilot check+`gbrain maintain --status` shows the last free-upkeep run, which an open+`gbrain serve` does while idle. For a brain no agent opens most days, offer+`gbrain maintain --schedule` (asks consent). On a Postgres brain with a repo,+verify autopilot:```bashgbrain autopilot --status```diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex e39d2a62bf..1569784d97 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -1,5 +1,5 @@{- "RESOLVER.md": "fdb9aeb0b584df8d881c6192f396b6c4e6fa9c57733b726dd6b4b3b8e693908d",+ "RESOLVER.md": "5ac5ffd310c530df995569aebf4325abaca7fd46f86814ead0fc82d02037f4d7","_AGENT_README.md": "d66098abeb735975ffed54cb9c89d51255996500a9554ae1d1e996db4171631f","_brain-filing-rules.json": "4e6ecee2d94867d146583d60bf98dccdd9205bb70793af56fe1397a2b258ae0d","_brain-filing-rules.md": "ff42b331bce542d708f97ff0a73ff0fb5664b46ee9b1862a5478b15dc637487e",@@ -44,7 +44,7 @@"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e","context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",- "conventions/agent-operator-protocol.md": "12c7b876994b96babdffa903326f7e23253d54ad9023248820337f56f8770512",+ "conventions/agent-operator-protocol.md": "dc50fa84aa8ce7b7cd6a72d167eccbad792338d3745d16785bca16487c948f05","conventions/brain-first.md": "f84f03b9619a1c9302a231bd43957c6987d55084f56eee351434b85ec2646a5c","conventions/brain-routing.md": "753703b94fcb10d42cb52fb0c85d7a8c9769df84b0df622dd04ae0d943bb84b1","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",@@ -95,7 +95,7 @@"idea-lineage/SKILL.md": "8cb36179dbf94abc17065613b8e773b1bb2b22670742aa77347b91ac885a05c5","idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41","ingest/SKILL.md": "1acc220ce6e9e65876fa2ccede6ce11f9c75457feb6695ef904955f8debecaae",- "maintain/SKILL.md": "6faf40cb944a0deb7d032e41f44b66f05fe0ebe8178bd84d3cf05e2f766f6127",+ "maintain/SKILL.md": "f2ae80775596f41309efdb90858a471d2229f06ff4a783b87f841cd084588276","manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4","mcp-access/SKILL.md": "1bc16338b89f476aa8c24ffec79c989fa60716793998af264d357f7886d2bc96","measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36",diff --git a/src/cli/main.ts b/src/cli/main.tsindex 63ca7dc5db..d2133d0977 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -2113,6 +2113,8 @@ async function routeEngineFreeSubcommands(command: string, args: string[]): Promconst { tryRunConfigEngineFree } = await import('../commands/config.ts');if (await tryRunConfigEngineFree(args)) return true;}+ // GBRA-438: `maintain --schedule`, `--unschedule` and a scheduled run beside a live serve open no engine (PGLite would wait on its lock).+ if (command === 'maintain' && await (await import('../commands/maintain-schedule.ts')).tryRunMaintainEngineFree(args)) return true;// Engine graduation owns its connections (routing rules: commands/migrate-graduation.ts routesToGraduation).if (command === 'migrate' && await (await import('../commands/migrate-graduation.ts')).tryRunMigrateGraduation(args)) return true;if (command === 'mcp') {diff --git a/src/commands/doctor/checks/unattended-maintenance.ts b/src/commands/doctor/checks/unattended-maintenance.tsindex 814810b330..43710573f5 100644--- a/src/commands/doctor/checks/unattended-maintenance.ts+++ b/src/commands/doctor/checks/unattended-maintenance.ts@@ -7,6 +7,7 @@* that runs free upkeep now.*/import type { Check } from '../../doctor.ts';+import { cliRenderContext, renderAction } from '../../../core/agent-output.ts';import { checkError, infoCheck } from '../check-fix.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { readUpkeepStatus, type UpkeepStatus } from '../../../core/maintenance/status.ts';@@ -19,6 +20,7 @@ function details(s: UpkeepStatus): Record<string, unknown> {pending_purge_count: s.pending_purge_count, paid_phases_opt_in: s.paid_phases_opt_in,embed_spend_today_usd: s.embed_spend_today_usd, embed_daily_cap_usd: s.embed_daily_cap_usd,...(s.failing ? { failing: s.failing } : {}),+ ...(s.alternative_fix ? { alternative_fix: renderAction(s.alternative_fix, cliRenderContext()) } : {}),};}diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 9af44eaa8f..ff204cb067 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -2140,6 +2140,7 @@ export async function extractStaleFromDB(*/timeBudgetMs?: number;/** GBRA-130 A-1 (managed brains): clear held link-extraction failures first. */ retryHeld?: boolean;+ /** GBRA-438: an abort (idle upkeep's budget, or a tool call) stops the sweep between batches, like timeBudgetMs. */ signal?: AbortSignal;},): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; skippedUnknownSource?: number; mentions?: MentionPassResult;linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[] }> {@@ -2166,7 +2167,7 @@ export async function extractStaleFromDB(// (the mention pass runs inside it).if (await managedPersistenceEnabled(engine)) {const { runManagedStaleExtraction, formatManagedStaleExtraction } = await import('../core/persistence/links-maintenance.ts');- const r = await runManagedStaleExtraction(engine, { sourceId: sourceIdFilter, catchUp, timeBudgetMs, counts: !opts.quiet, retryHeld: opts.retryHeld });+ const r = await runManagedStaleExtraction(engine, { sourceId: sourceIdFilter, catchUp, timeBudgetMs, counts: !opts.quiet, retryHeld: opts.retryHeld, signal: opts.signal });if (!jsonMode) log(formatManagedStaleExtraction(r, false, false));else if (!opts.quiet) process.stdout.write(formatManagedStaleExtraction(r, false, true) + '\n');return { linksCreated: r.created, timelineCreated: r.timeline, pagesProcessed: r.pages, staleRemaining: r.remaining + (r.mentions?.remaining ?? 0),@@ -2362,12 +2363,12 @@ export async function extractStaleFromDB(progress.tick(processedRefs.length);afterPageId = rows[rows.length - 1]!.id;- if (Date.now() > linkDeadline) { budgetHit = true; break; }+ if (Date.now() > linkDeadline || opts.signal?.aborted) { budgetHit = true; break; }}progress.finish();if (packUnavailable) throw new Error('Cannot extract links: active schema pack is unavailable.');- const mentions = await runMentionPass(engine, { sourceId: sourceIdFilter, ...(catchUp ? {} : { deadline: startMs + timeBudgetMs }) });+ const mentions = await runMentionPass(engine, { sourceId: sourceIdFilter, ...(catchUp ? {} : { deadline: opts.signal?.aborted ? 0 : startMs + timeBudgetMs }) });const staleRemaining = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs }) + mentions.remaining;const counts = opts.quiet ? null : await staleExtractionCounts(engine, sourceIdFilter);diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.tsindex ac6325a2d5..a84a0ed210 100644--- a/src/commands/init-first-run.ts+++ b/src/commands/init-first-run.ts@@ -9,7 +9,9 @@* `writeback` (recommended `salient`, offered on a personal brain whose* operator has not answered), `harness_wiring` (the A7 readiness fix) and the* optional `skills_scaffold` (recommended skills missing from the detected- * agent workspace; default skip). Human output renders the same bundle+ * agent workspace; default skip), then `upkeep` (GBRA-438: the free upkeep+ * line, a setting in effect whose default `on` needs no answer; it rides a+ * bundle that has another entry and never opens one alone). Human output renders the same bundle* (`[AGENT]` block without a terminal, `Note` lines on one); it replaces* init's separate writeback ask and skills pointer. Extend* `buildInitFirstRunNotices` rather than adding a second notice.@@ -34,6 +36,30 @@ export interface InitFirstRunInputs {skillsScaffold?: { missing: string[]; argv: string[] } | null;/** `gbrain init --surface`: the surface the harness registration pins (default REGISTRATION_SURFACE). */surface?: McpSurface;+ /** GBRA-438: the upkeep line, relayed with the block as a setting in effect; `embedding` says the capped embedding step applies. */+ upkeep?: { embedding: boolean };+}++/** GBRA-438: what runs on its own, stated as a setting in effect (the plan's wording; the keyed form names the one capped paid step). */+export function upkeepLine(embedding: boolean): string {+ return "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. "+ + (embedding+ ? 'Nothing is deleted without you, and the only paid step is embedding new text, capped at $1 a day (maintenance.embed_daily_usd). '+ : 'Nothing is deleted or paid for without you. ')+ + 'Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.';+}++function upkeepDecision(embedding: boolean): Decision {+ return {+ id: 'upkeep',+ question: upkeepLine(embedding),+ options: [+ { id: 'on', label: 'Keep free upkeep on (in effect now)' },+ { id: 'off', label: 'Turn free upkeep off', argv: ['gbrain', 'config', 'set', 'maintenance.auto', 'false'] },+ ],+ default: 'on',+ default_reason: 'In effect now: the agent\'s gbrain serve runs the free upkeep tier while idle; nothing needs an answer.',+ };}function searchModeDecision(applied: { mode: SearchMode; reason: string }): Decision {@@ -103,6 +129,7 @@ export function buildInitFirstRunNotices(inputs: InitFirstRunInputs): Notice[] {}if (inputs.skillsScaffold?.missing.length) decisions.push(skillsScaffoldDecision(inputs.skillsScaffold));if (decisions.length === 0) return [];+ if (inputs.upkeep) decisions.push(upkeepDecision(inputs.upkeep.embedding));const defaults = decisions.map(d => `${d.id}: ${d.default}`).join('; ');return [{code: 'first_run_decisions',@@ -126,18 +153,19 @@ export function setupFirstRunNotices(initNotices: readonly unknown[], harness: sconst decisions = (bundle?.decisions ?? []).filter(d => d.id !== 'harness_wiring');if (decisions.length === 0) return [];const searchMode = decisions.find(d => d.id === 'search_mode');+ const upkeep = decisions.find(d => d.id === 'upkeep');const inEffect = [...(searchMode ? [`search mode ${searchMode.default}`] : []),...(decisions.some(d => d.id === 'writeback') ? ['agents save only what you ask them to remember, until you turn on automatic saving (gbrain recommends salient: durable facts you state, saved with provenance)'] : []),];- if (inEffect.length === 0) return [];+ if (inEffect.length === 0 && !upkeep) return [];return [{code: 'first_run_decisions',kind: 'ask',why: `Setup is complete: the brain is ready and ${harness} is wired, so memory works now. These first-run settings are in effect as listed; none blocks memory or needs a new session to answer. `+ 'Relay them once, in the reply that reports this install, as the current settings and how to change them; do not hold the install open or end it waiting on an answer. '+ 'When the user picks an option, run its command. Automatic saving (`writeback`) is separate from setup\'s capture decision (Stop/SessionEnd hooks); while unanswered it comes back in a later session until the user answers or mutes it.',- user_message: `gbrain is set up and ${harness} is wired, so memory works now. In effect: ${inEffect.join('; ')}.${searchMode ? ` ${costMatrixSentence()}` : ''} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,+ user_message: `gbrain is set up and ${harness} is wired, so memory works now.${inEffect.length ? ` In effect: ${inEffect.join('; ')}.` : ''}${upkeep ? ` ${upkeep.question}` : ''}${searchMode ? ` ${costMatrixSentence()}` : ''} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,decisions,}];}@@ -157,7 +185,10 @@ export function deferredEmbeddingHint(cfg: GBrainConfig): string {export async function firstRunBundle(engine: BrainEngine, searchMode: { mode: SearchMode; reason: string } | undefined, surface?: McpSurface): Promise<Notice[]> {const { writebackAskApplies } = await import('../core/onboard/writeback-nudge.ts');const { initSkillsScaffold } = await import('../core/skillpack/post-install-advisory.ts');- return buildInitFirstRunNotices({ searchMode, config: loadConfig(), writeback: await writebackAskApplies(engine), skillsScaffold: initSkillsScaffold(), surface });+ const { isAvailable } = await import('../core/ai/gateway.ts');+ let embedding = false;+ try { embedding = isAvailable('embedding'); } catch { /* gateway not configured: keyless */ }+ return buildInitFirstRunNotices({ searchMode, config: loadConfig(), writeback: await writebackAskApplies(engine), skillsScaffold: initSkillsScaffold(), surface, upkeep: { embedding } });}/** D2/G5: the bundle rendered into init's --json document (`notices`, empty → omitted). */diff --git a/src/commands/maintain-schedule.ts b/src/commands/maintain-schedule.tsnew file mode 100644index 0000000000..4623cae260--- /dev/null+++ b/src/commands/maintain-schedule.ts@@ -0,0 +1,387 @@+/**+ * `gbrain maintain --schedule [--yes] [--dry-run]` and `--unschedule` (GBRA-438 PR 2, decision E1):+ * the opt-in operating-system schedule for free upkeep, never installed by default. Every+ * 6 hours the job runs `gbrain maintain --unattended --runner schedule` once and exits:+ *+ * - macOS: a launchd user agent (no sudo; runs while the user is logged in);+ * - Linux with a working systemd user manager: a .service plus .timer pair (runs after+ * logout only with lingering, which may need an admin);+ * - other Linux: one user crontab line, tagged with this brain's marker;+ * - a container or cloud sandbox: nothing is installed; the resident `gbrain serve`+ * (stdio or --http) is the runner there;+ * - Windows: nothing is installed; the outcome prints the schtasks line to add by hand.+ *+ * Installing is a persistent_install, so it goes through requireConsent (`--yes`, a TTY+ * prompt or the user's preapproval); a refusal prints the consent payload and writes nothing.+ * A scheduled run exits 0 at once when a live serve owns the brain ("serve owns upkeep"):+ * the PGLite lock holder on a PGLite brain, the warm CLI socket (GBRA-156) on Postgres.+ *+ * Renderers are pure and pinned by test/maintain-schedule-gbra438.test.ts; every exec goes+ * through an injectable CommandRunner and every path through injectable dirs, as in+ * src/core/serve-service.ts, whose wrapper and escaping helpers this reuses.+ */+import { chmodSync, existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { gbrainPath, isThinClient, loadConfig } from '../core/config.ts';+import { resolveAutopilotJob } from '../core/autopilot-paths.ts';+import { detectExecutionEnvironment, type ExecutionEnvironment } from '../core/execution-env.ts';+import { escapeXml, refuseSymlink, resolveServeGbrainCommand, systemdArg, systemdSpecifierEscape } from '../core/serve-service.ts';+import { defaultCommandRunner, type CommandRunner } from '../core/tailscale.ts';+import { isConsentRefusal, printConsentRefusal, requireConsent } from '../core/consent.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { writeCliError } from '../cli/cli-error.ts';+import { opError } from '../core/ops/contract.ts';++export const SCHEDULE_INTERVAL_HOURS = 6;+/** What the job runs: one unattended upkeep run, recorded with runner `schedule`. */+export const SCHEDULED_RUN_ARGS: readonly string[] = ['maintain', '--unattended', '--runner', 'schedule'];++export type ScheduleTarget = 'macos' | 'linux-systemd' | 'linux-cron' | 'container' | 'windows';++export interface ScheduleNames { label: string; unit: string; cronMarker: string }++/** One brain's job names: the default brain keeps the bare names; another GBRAIN_HOME carries its install-id suffix (#5195). */+export function scheduleNames(suffix: string | null): ScheduleNames {+ return {+ label: suffix ? `com.gbrain.maintain.${suffix}` : 'com.gbrain.maintain',+ unit: suffix ? `gbrain-maintain-${suffix}` : 'gbrain-maintain',+ cronMarker: suffix ? `# gbrain-maintain:${suffix}` : '# gbrain-maintain',+ };+}++const sq = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;++export interface ScheduleWrapperParams {+ /** From resolveServeGbrainCommand: `[gbrain]` or `[bun, cli.ts]`. */+ gbrainCommand: string[];+ /** `<gbrain home>/env`, sourced for keys (set -a). */+ gbrainEnvFile: string;+ /** The installer's GBRAIN_HOME, baked when set (supervisors pass no environment). */+ gbrainHome?: string;+ /** Directory of the running bun; '' skips the PATH prefix. */+ runtimeDir?: string;+}++export function renderScheduleWrapper(p: ScheduleWrapperParams): string {+ const [program, ...programArgs] = p.gbrainCommand;+ const tail = [...programArgs.map(sq), ...SCHEDULED_RUN_ARGS].join(' ');+ const runtimeDir = p.runtimeDir ?? '';+ const runtimePrefix = runtimeDir && runtimeDir !== '.' ? `${sq(runtimeDir)}:` : '';+ const homeLine = p.gbrainHome ? `export GBRAIN_HOME=${sq(p.gbrainHome)}\n` : '';+ return `#!/bin/bash+# Auto-generated by \`gbrain maintain --schedule\`: runs free upkeep once and exits.+# Remove with \`gbrain maintain --unschedule\`. Keys come from the gbrain env file only.+[ -f ${sq(p.gbrainEnvFile)} ] && { set -a; source ${sq(p.gbrainEnvFile)} 2>/dev/null; set +a; }+export PATH=${runtimePrefix}"$HOME/.bun/bin:$PATH"+${homeLine}cd "$HOME"+_gbrain=${sq(program!)}+if [ ! -x "$_gbrain" ]; then+ _gbrain=$(type -P gbrain 2>/dev/null)+ if [ -z "$_gbrain" ]; then+ echo "$(date -u +%FT%TZ) [gbrain-maintain] gbrain CLI not found at" ${sq(program!)} "nor on PATH; re-run: gbrain maintain --schedule" >&2+ exit 1+ fi+fi+exec "$_gbrain" ${tail}+`;+}++export function renderScheduleLaunchdPlist(p: { label: string; wrapperPath: string; home: string; logPath: string }): string {+ return `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key><string>${escapeXml(p.label)}</string>+ <key>ProgramArguments</key><array>+ <string>${escapeXml(p.wrapperPath)}</string>+ </array>+ <key>WorkingDirectory</key><string>${escapeXml(p.home)}</string>+ <key>RunAtLoad</key><true/>+ <key>StartInterval</key><integer>${SCHEDULE_INTERVAL_HOURS * 3600}</integer>+ <key>StandardOutPath</key><string>${escapeXml(p.logPath)}</string>+ <key>StandardErrorPath</key><string>${escapeXml(p.logPath)}</string>+</dict>+</plist>+`;+}++export function renderScheduleSystemdService(p: { wrapperPath: string; logPath: string }): string {+ return `[Unit]+Description=GBrain free upkeep (gbrain maintain --unattended --runner schedule)++[Service]+Type=oneshot+ExecStart=${systemdArg(p.wrapperPath)}+StandardOutput=append:${systemdSpecifierEscape(p.logPath)}+StandardError=append:${systemdSpecifierEscape(p.logPath)}+`;+}++export function renderScheduleSystemdTimer(p: { unit: string }): string {+ return `[Unit]+Description=GBrain free upkeep every ${SCHEDULE_INTERVAL_HOURS} hours++[Timer]+OnCalendar=*-*-* 00/${SCHEDULE_INTERVAL_HOURS}:17:00+Persistent=true+RandomizedDelaySec=600+Unit=${p.unit}.service++[Install]+WantedBy=timers.target+`;+}++export function scheduleCronLine(p: { wrapperPath: string; logPath: string; marker: string }): string {+ return `17 */${SCHEDULE_INTERVAL_HOURS} * * * ${sq(p.wrapperPath)} >> ${sq(p.logPath)} 2>&1 ${p.marker}`;+}++/** Windows gets no installer (org rule: minimal Windows support); this is the line the outcome prints. */+export function windowsScheduleCommand(gbrainCommand: string[]): string {+ const run = [...gbrainCommand, ...SCHEDULED_RUN_ARGS].map((a) => (/\s/.test(a) ? `\\"${a}\\"` : a)).join(' ');+ return `schtasks /Create /SC HOURLY /MO ${SCHEDULE_INTERVAL_HOURS} /TN gbrain-maintain /TR "${run}"`;+}++/** Whether a cron line is this brain's schedule line: it ends with exactly this marker. */+export function isScheduleCronLine(line: string, marker: string): boolean {+ return line.trimEnd().endsWith(marker);+}++export interface ScheduleEnv {+ platform: string;+ executionEnv: ExecutionEnvironment;+ /** `<HOME>`: where LaunchAgents and the systemd user dir live. */+ home: string;+ /** The brain's gbrain home (GBRAIN_HOME aware): wrapper, log. */+ dir: string;+ names: ScheduleNames;+ gbrainCommand: string[];+ gbrainHome?: string;+ runtimeDir?: string;+ run: CommandRunner;+ /** `/run/systemd/system` exists (the host booted with systemd); the user manager is probed through `run`. */+ systemdBooted: boolean;+ uid?: number;+ /** Test seam for requireConsent's TTY check. */+ interactive?: boolean;+}++export function defaultScheduleEnv(): ScheduleEnv {+ const runtimeDir = dirname(process.execPath || '');+ return {+ platform: process.platform,+ executionEnv: detectExecutionEnvironment(),+ home: process.env.HOME || '',+ dir: gbrainPath(),+ names: scheduleNames(resolveAutopilotJob({ mint: true }).suffix),+ gbrainCommand: resolveServeGbrainCommand(),+ ...(process.env.GBRAIN_HOME ? { gbrainHome: process.env.GBRAIN_HOME } : {}),+ runtimeDir: runtimeDir === '.' ? '' : runtimeDir,+ run: defaultCommandRunner,+ systemdBooted: existsSync('/run/systemd/system'),+ };+}++export async function detectScheduleTarget(env: ScheduleEnv): Promise<ScheduleTarget> {+ if (env.platform === 'win32') return 'windows';+ if (env.platform === 'darwin') return 'macos';+ if (env.executionEnv !== 'local') return 'container';+ if (!env.systemdBooted) return 'linux-cron';+ const bus = await env.run(['systemctl', '--user', 'is-system-running'], { timeoutMs: 3_000 });+ return bus.status === 0 || /\b(running|degraded)\b/i.test(bus.stdout) ? 'linux-systemd' : 'linux-cron';+}++export interface SchedulePaths { wrapper: string; log: string; plist: string; service: string; timer: string }++export function schedulePaths(env: Pick<ScheduleEnv, 'home' | 'dir' | 'names'>): SchedulePaths {+ const userUnits = join(env.home, '.config', 'systemd', 'user');+ return {+ wrapper: join(env.dir, 'maintain-run.sh'),+ log: join(env.dir, 'maintain.log'),+ plist: join(env.home, 'Library', 'LaunchAgents', `${env.names.label}.plist`),+ service: join(userUnits, `${env.names.unit}.service`),+ timer: join(userUnits, `${env.names.unit}.timer`),+ };+}++/** Every file or table entry an install on `target` writes. */+export function scheduleWrites(target: ScheduleTarget, paths: SchedulePaths): string[] {+ if (target === 'macos') return [paths.wrapper, paths.plist];+ if (target === 'linux-systemd') return [paths.wrapper, paths.service, paths.timer];+ if (target === 'linux-cron') return [paths.wrapper, 'your crontab (one gbrain-maintain line)'];+ return [];+}++function writeFile(path: string, content: string, mode: number, what: string): void {+ refuseSymlink(path, what);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, content, { mode });+ chmodSync(path, mode);+}++const describe = (r: { status: number | null; stdout: string; stderr: string }) => (r.stderr || r.stdout).trim() || `exit ${r.status}`;++async function readCrontab(run: CommandRunner): Promise<string> {+ const r = await run(['crontab', '-l'], { timeoutMs: 15_000 });+ return r.status === 0 ? r.stdout : '';+}++async function writeCrontab(env: ScheduleEnv, lines: string[]): Promise<{ status: number | null; stdout: string; stderr: string }> {+ const tmp = join(env.dir, 'crontab.tmp');+ writeFile(tmp, lines.length ? lines.join('\n') + '\n' : '', 0o600, 'the crontab staging file');+ try { return await env.run(['crontab', tmp], { timeoutMs: 15_000 }); } finally { try { unlinkSync(tmp); } catch { /* best-effort */ } }+}++export interface ScheduleResult { written: string[]; notes: string[]; error?: string }++export async function installSchedule(target: 'macos' | 'linux-systemd' | 'linux-cron', env: ScheduleEnv): Promise<ScheduleResult> {+ const paths = schedulePaths(env);+ const out: ScheduleResult = { written: [], notes: [] };+ writeFile(paths.wrapper, renderScheduleWrapper({ gbrainCommand: env.gbrainCommand, gbrainEnvFile: join(env.dir, 'env'), gbrainHome: env.gbrainHome, runtimeDir: env.runtimeDir }), 0o755, 'the upkeep wrapper');+ out.written.push(paths.wrapper);+ if (target === 'macos') {+ writeFile(paths.plist, renderScheduleLaunchdPlist({ label: env.names.label, wrapperPath: paths.wrapper, home: env.home, logPath: paths.log }), 0o644, 'the launchd plist');+ out.written.push(paths.plist);+ const domain = `gui/${env.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 501)}`;+ await env.run(['launchctl', 'bootout', domain, paths.plist], { timeoutMs: 60_000 });+ const boot = await env.run(['launchctl', 'bootstrap', domain, paths.plist], { timeoutMs: 60_000 });+ if (boot.status !== 0) out.error = `launchctl bootstrap failed: ${describe(boot)}`;+ return out;+ }+ if (target === 'linux-systemd') {+ writeFile(paths.service, renderScheduleSystemdService({ wrapperPath: paths.wrapper, logPath: paths.log }), 0o644, 'the systemd service');+ writeFile(paths.timer, renderScheduleSystemdTimer({ unit: env.names.unit }), 0o644, 'the systemd timer');+ out.written.push(paths.service, paths.timer);+ await env.run(['systemctl', '--user', 'daemon-reload'], { timeoutMs: 15_000 });+ const enable = await env.run(['systemctl', '--user', 'enable', '--now', `${env.names.unit}.timer`], { timeoutMs: 60_000 });+ if (enable.status !== 0) out.error = `systemctl --user enable --now ${env.names.unit}.timer failed: ${describe(enable)}`;+ out.notes.push('The timer runs while your user manager runs; for runs after logout turn on lingering (loginctl enable-linger "$USER", which may need an admin).');+ return out;+ }+ const kept = (await readCrontab(env.run)).split('\n').filter((l) => l.trim() !== '' && !isScheduleCronLine(l, env.names.cronMarker));+ const write = await writeCrontab(env, [...kept, scheduleCronLine({ wrapperPath: paths.wrapper, logPath: paths.log, marker: env.names.cronMarker })]);+ if (write.status !== 0) out.error = `crontab failed: ${describe(write)}`;+ else out.written.push('crontab: one gbrain-maintain line');+ return out;+}++export async function uninstallSchedule(target: ScheduleTarget, env: ScheduleEnv): Promise<ScheduleResult> {+ const paths = schedulePaths(env);+ const out: ScheduleResult = { written: [], notes: [] };+ const remove = (path: string) => { if (existsSync(path)) { unlinkSync(path); out.written.push(path); } };+ if (target === 'macos') {+ const domain = `gui/${env.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 501)}`;+ if (existsSync(paths.plist)) await env.run(['launchctl', 'bootout', domain, paths.plist], { timeoutMs: 60_000 });+ remove(paths.plist);+ } else if (target === 'linux-systemd') {+ if (existsSync(paths.timer)) await env.run(['systemctl', '--user', 'disable', '--now', `${env.names.unit}.timer`], { timeoutMs: 60_000 });+ remove(paths.timer);+ remove(paths.service);+ await env.run(['systemctl', '--user', 'daemon-reload'], { timeoutMs: 15_000 });+ } else if (target === 'linux-cron') {+ const lines = (await readCrontab(env.run)).split('\n').filter((l) => l.trim() !== '');+ const kept = lines.filter((l) => !isScheduleCronLine(l, env.names.cronMarker));+ if (kept.length !== lines.length) {+ const write = await writeCrontab(env, kept);+ if (write.status !== 0) out.error = `crontab failed: ${describe(write)}`;+ else out.written.push('crontab: the gbrain-maintain line');+ }+ }+ remove(paths.wrapper);+ return out;+}++/** "serve owns upkeep": a live serve holds this brain (PGLite lock holder, or the warm CLI socket on Postgres). */+export async function liveServeOwnsBrain(): Promise<boolean> {+ const config = loadConfig();+ if (!config || isThinClient(config)) return false;+ if (config.database_path && !config.database_url) {+ const { probeLivePgliteHolder } = await import('../core/bootstrap/uninstall.ts');+ return !!probeLivePgliteHolder(config.database_path)?.serve;+ }+ const { probeCliSocket } = await import('../core/cli-socket/probe.ts');+ return (await probeCliSocket()).state === 'accepted';+}++function print(json: boolean, doc: Record<string, unknown>, lines: string[]): void {+ if (json) console.log(JSON.stringify(doc, null, 2));+ else for (const line of lines) console.log(line);+}++/** `--schedule` / `--unschedule`. Engine-free: it never opens the brain. */+export async function runMaintainSchedule(args: string[], env: ScheduleEnv = defaultScheduleEnv()): Promise<void> {+ const json = args.includes('--json');+ const target = await detectScheduleTarget(env);+ const paths = schedulePaths(env);+ if (target === 'windows') {+ const line = windowsScheduleCommand(env.gbrainCommand);+ setCliExitVerdict(writeCliError(opError('schedule_unsupported', `gbrain maintain --schedule installs nothing on Windows. To schedule free upkeep by hand, run: ${line}`,+ `Add the scheduled task yourself with: ${line}`, { reason: 'windows', detail: line }), 'maintain', { json }));+ return;+ }+ if (target === 'container') {+ setCliExitVerdict(writeCliError(opError('schedule_unsupported', 'This looks like a container or cloud sandbox, where an operating-system schedule does not survive a redeploy, so nothing was installed.',+ 'Keep gbrain serve running in the container (gbrain serve --http for a hosted brain): it runs free upkeep on its own while idle.', { reason: 'container' }), 'maintain', { json }));+ return;+ }+ if (args.includes('--unschedule')) {+ const result = await uninstallSchedule(target, env);+ if (result.error) setCliExitVerdict(1);+ print(json, { status: result.error ? 'error' : 'removed', target, removed: result.written, ...(result.error ? { error: result.error } : {}) },+ [result.written.length ? `Removed the free upkeep schedule (${target}): ${result.written.join(', ')}.` : 'No free upkeep schedule was installed.', ...(result.error ? [result.error] : [])]);+ return;+ }+ const writes = scheduleWrites(target, paths);+ const what = `every ${SCHEDULE_INTERVAL_HOURS} hours, ${target === 'macos' ? 'a launchd agent' : target === 'linux-systemd' ? 'a systemd user timer' : 'a crontab line'} runs gbrain ${SCHEDULED_RUN_ARGS.join(' ')}`;+ if (args.includes('--dry-run')) {+ print(json, { status: 'dry_run', target, would_write: writes, interval_hours: SCHEDULE_INTERVAL_HOURS },+ [`gbrain maintain --schedule --dry-run: nothing was written. On ${target}, ${what}.`, ' would write:', ...writes.map((w) => ` ${w}`), ' Install: gbrain maintain --schedule --yes (after the user agrees).']);+ return;+ }+ try {+ await requireConsent({+ command: 'maintain',+ effects: ['persistent_install'],+ actor: 'agent',+ what: 'Install an operating-system schedule for free gbrain upkeep',+ why: `On ${target}, ${what}. Writes: ${writes.join(', ')}. A run calls no chat model and never purges a page; it exits at once while a gbrain serve owns the brain or upkeep is not due.`,+ risk: 'A scheduled job keeps running after this session until gbrain maintain --unschedule removes it.',+ user_message: `I'd like to add a small scheduled job that runs gbrain's free upkeep (links, timeline, facts index) every ${SCHEDULE_INTERVAL_HOURS} hours, so your brain stays tidy when no agent session is open. It deletes nothing and calls no chat model; with an embedding key it may embed new text, capped at $1 a day. You can remove it any time with gbrain maintain --unschedule. OK?`,+ argv: ['gbrain', 'maintain', '--schedule', '--yes'],+ preview_argv: ['gbrain', 'maintain', '--schedule', '--dry-run'],+ args,+ }, env.interactive === undefined ? {} : { interactive: env.interactive });+ } catch (error) {+ if (!isConsentRefusal(error)) throw error;+ setCliExitVerdict(printConsentRefusal(error, { json }));+ return;+ }+ const result = await installSchedule(target, env);+ if (result.error) {+ setCliExitVerdict(writeCliError(opError('schedule_install_failed', `The free upkeep schedule was written but the ${target} scheduler refused it: ${result.error}`,+ 'Read the error above, fix the scheduler, then run gbrain maintain --schedule --yes again.', { detail: result.error }), 'maintain', { json }));+ return;+ }+ print(json, { status: 'installed', target, written: result.written, notes: result.notes, interval_hours: SCHEDULE_INTERVAL_HOURS },+ [`Scheduled free upkeep: ${what}.`, ` Wrote: ${result.written.join(', ')}`, ` Log: ${paths.log}`, ...result.notes.map((n) => ` ${n}`),+ ' A run exits at once while a gbrain serve owns the brain or upkeep is not due.', ' Remove: gbrain maintain --unschedule']);+}++/**+ * The engine-free part of `gbrain maintain`, routed before connectEngine: `--schedule` and+ * `--unschedule`, and a scheduled run (`--unattended --runner schedule`) while a live serve+ * owns the brain, which exits 0 without opening it (a PGLite open would wait on the serve's lock).+ */+export async function tryRunMaintainEngineFree(args: string[], deps: { liveServe?: () => Promise<boolean>; env?: ScheduleEnv } = {}): Promise<boolean> {+ if (args.includes('--help') || args.includes('-h')) return false;+ if (args.includes('--schedule') || args.includes('--unschedule')) {+ await runMaintainSchedule(args, deps.env);+ return true;+ }+ const runner = args.indexOf('--runner');+ const scheduled = args.includes('--unattended') && runner >= 0 && args[runner + 1] === 'schedule';+ if (!scheduled || !await (deps.liveServe ?? liveServeOwnsBrain)()) return false;+ const message = 'A gbrain serve owns this brain and runs free upkeep while it is idle (serve owns upkeep), so the scheduled run did nothing.';+ print(args.includes('--json'), { status: 'skipped', exit: 0, code: 'maintenance_owned_by_serve', message }, [message]);+ return true;+}diff --git a/src/commands/maintain.ts b/src/commands/maintain.tsindex 531634a4e2..10e6e76168 100644--- a/src/commands/maintain.ts+++ b/src/commands/maintain.ts@@ -226,6 +226,8 @@ export async function runMaintain(engine: BrainEngine, args: string[]): Promise<gbrain maintain --unattended [--runner <name>] [--json]gbrain maintain --status [--json]gbrain maintain --purge [--yes --expect <hash>] [--json]+ gbrain maintain --schedule [--yes | --dry-run] [--json]+ gbrain maintain --unschedule [--json]Conservative self-healing maintenance.@@ -240,6 +242,11 @@ Modes:--status Show the last upkeep run, the next due time and what waits for you.--purge Preview the page purge (soft-deleted pages past purge.retention_hours);apply it with --yes --expect <hash> from the preview.+ --schedule Opt in to an operating-system schedule (launchd, systemd user timer or+ crontab) that runs --unattended every 6 hours; --yes approves the+ install, --dry-run shows what it writes. A running gbrain serve+ already runs free upkeep while idle, so most installs need none.+ --unschedule Remove that schedule.--json Emit a structured report.Not auto-applied:@@ -326,9 +333,10 @@ async function runUnattendedCli(engine: BrainEngine, opts: MaintainOptions): Proasync function runStatusCli(engine: BrainEngine, opts: MaintainOptions): Promise<void> {const status = await readUpkeepStatus(engine);- const { fix, ...rest } = status;+ const { fix, alternative_fix: alternative, ...rest } = status;if (opts.json) {- console.log(JSON.stringify({ ...rest, ...(fix ? { fix: renderAction(fix, cliRenderContext()) } : {}) }, null, 2));+ console.log(JSON.stringify({ ...rest, ...(fix ? { fix: renderAction(fix, cliRenderContext()) } : {}),+ ...(alternative ? { alternative_fix: renderAction(alternative, cliRenderContext()) } : {}) }, null, 2));return;}console.log(status.message);@@ -336,6 +344,7 @@ async function runStatusCli(engine: BrainEngine, opts: MaintainOptions): Promiseif (status.held.length) console.log(`Held back on this brain (they would call a provider): ${status.held.join(', ')}`);console.log(`Left for you (paid, opt-in; gbrain dream or an autopilot runs them): ${status.paid_phases_opt_in.join(', ')}`);if (fix) console.log(`Fix: ${fix.argv!.join(' ')}: ${fix.why}`);+ if (alternative) console.log(`Or: ${alternative.argv!.join(' ')}: ${alternative.why}`);}/** Hash of exactly what a purge would remove, so --expect binds the apply to the preview the person saw. */diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex af27d02253..a72f521475 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -55,6 +55,7 @@ import { VERSION } from '../version.ts';import { NoticeLedger } from '../core/notice-ledger.ts';import { createReadinessCache, type ReadinessCache } from '../core/readiness.ts';import { withLocalScope } from '../core/engine-scope-store.ts';+import { mcpForegroundMiddleware } from '../core/foreground-activity.ts';export { extractGitHubItemRef, githubKindCoversRepo, selectGitHubItemSources } from './serve-http-webhooks.ts';export { HEALTH_TIMEOUT_MS, probeHealth, probeLiveness, type ProbeHealthResult } from './serve-http-metrics.ts';@@ -772,6 +773,7 @@ export async function buildServeHttpApp(app: express.Express, engine: BrainEngin// below requireAdmin's definition.const metricsCounters = createMetricsCounters();app.use(metricsTrackingMiddleware(metricsCounters));+ app.use('/mcp', mcpForegroundMiddleware);const oauthTokenRateLimit = resolveOAuthTokenRateLimit();const ccRateLimiter = rateLimit({diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 43a7b89a89..c25d973a3b 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -16,7 +16,7 @@ import { startMovementWatch, type MovementWatch } from '../core/persistence/syncimport { startServeHeadWatcher } from '../core/serve-head-watcher.ts';import { isReadOnlyServeArgs, readOnlyServeSkipsResidentDuties } from '../core/direct-pool-profile.ts';import { onForwardProgress } from '../core/forward-progress.ts';-import { foregroundWindow } from '../core/foreground-activity.ts';+import { foregroundWindow, onForegroundRequest } from '../core/foreground-activity.ts';import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';import { withLocalScope } from '../core/engine-scope-store.ts';import {@@ -79,6 +79,35 @@ function idleSweepIntervalMs(): number {return Number.isFinite(n) && n >= 1_000 ? Math.floor(n) : IDLE_SWEEP_INTERVAL_MS;}+/** GBRA-438: idle upkeep, skipped while a delegated sync owns the event loop (the sweep's rule); loaded lazily, off the boot path. */+function defaultIdleUpkeep(log: (line: string) => void): (engine: BrainEngine, signal: AbortSignal) => Promise<unknown> {+ return async (engine, signal) => {+ if ((await loadSyncRunner()).isDelegatedSyncRunning()) return;+ const { runIdleUpkeep } = await import('../core/maintenance/idle.ts');+ await runIdleUpkeep(engine, { runner: 'serve', signal, log });+ };+}++/**+ * GBRA-438: the stdio serve's idle upkeep, one run at a time. abort() (stdin data), a foreground request or stop()+ * (shutdown) aborts the run in flight. run() never throws.+ */+function idleUpkeepSlot(upkeep: (engine: BrainEngine, signal: AbortSignal) => Promise<unknown>): { run(engine: BrainEngine): Promise<void>; abort(): void; stop(): void } {+ let running: AbortController | null = null;+ const abort = (): void => { running?.abort(); };+ const unsubscribe = onForegroundRequest(abort);+ return {+ async run(engine) {+ if (running) return;+ const controller = new AbortController();+ running = controller;+ try { await upkeep(engine, controller.signal); } catch { /* idle upkeep is best-effort; never kill serve */ } finally { running = null; }+ },+ abort,+ stop() { unsubscribe(); abort(); },+ };+}+/** GBRA-156: each idle sweep names its start and its duration on stderr, so slow requests can be lined up with it. */async function loggedIdleSweep(log: (line: string) => void, run: () => Promise<unknown>): Promise<void> {const startedAt = Date.now();@@ -152,6 +181,10 @@ export interface ServeOptions {// sweep core (which opens engine work). Defaults to a lazy-imported// runMaintenanceSweep with a small budget.sweep?: (engine: BrainEngine) => Promise<unknown>;+ // Test seam for idle upkeep (GBRA-438): one run with the abort signal stdin+ // data or a foreground request trips. Defaults to runIdleUpkeep as runner+ // 'serve' (on and due only, small budget, never at boot).+ upkeep?: (engine: BrainEngine, signal: AbortSignal) => Promise<unknown>;// Kill switch seam for the idle sweep. Defaults to// `process.env.GBRAIN_SWEEP !== '0'` when omitted.sweepEnabled?: boolean;@@ -407,6 +440,14 @@ async function serveBrain(// waited for a hand-run sweep and then for retention GC.const { armCorpusDrain } = await import('../core/sweep.ts');const corpusDrain = (opts.armCorpusDrain ?? armCorpusDrain)(engine, { sourceId: process.env.GBRAIN_SOURCE || undefined });+ // GBRA-438: the HTTP serve's idle tick (it had none): free upkeep when due, keyed on /mcp request activity.+ // Same kill switch as the stdio serve's idle tick (GBRAIN_SWEEP=0); HTTP refuses --access read-only, so it is never lean.+ const idleUpkeep = (opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0')) ? (await import('../core/maintenance/idle.ts')).armIdleUpkeep(engine, {+ intervalMs: idleSweepIntervalMs(),+ setInterval: opts.setInterval ?? ((fn, ms) => setInterval(fn, ms)),+ clearInterval: opts.clearInterval ?? ((h) => clearInterval(h as ReturnType<typeof setInterval>)),+ upkeep: opts.upkeep ?? defaultIdleUpkeep(httpLog),+ }) : null;const cliSocket = cliSocketOn ? await (await import('../core/cli-socket/server.ts')).startCliSocket(engine, httpLog) : null;try {@@ -414,6 +455,7 @@ async function serveBrain(} finally {stallWatchdog?.dispose();corpusDrain?.cancel();+ idleUpkeep?.stop();cliSocket?.close();}@@ -669,6 +711,7 @@ function installStdioLifecycle(let shuttingDown = false;let parentWatchdog: unknown = null;let idleSweepTimer: unknown = null;+ const idleUpkeep = idleUpkeepSlot(opts.upkeep ?? defaultIdleUpkeep(deps.log)); // GBRA-438let activateIdleActivityTracking = (): void => {};let factsDrain: { stop(): Promise<void> } | null = null;const beginShutdown = (reason: string): void => {@@ -689,6 +732,7 @@ function installStdioLifecycle(deps.clearInterval(idleSweepTimer);idleSweepTimer = null;}+ idleUpkeep.stop();deps.log(`GBrain MCP server: graceful exit (${reason})`);@@ -914,7 +958,7 @@ function installStdioLifecycle(// unlike the opt-in --stdio-idle-timeout listener below). By the// first tick the transport is long live. No activity signal exists// for this first window yet, so treat it as active and re-arm.- deps.stdin.on('data', () => { stdinSawData = true; });+ deps.stdin.on('data', () => { stdinSawData = true; idleUpkeep.abort(); });dataListenerAttached = true;return;}@@ -926,6 +970,7 @@ function installStdioLifecycle(Promise.resolve().then(() => loggedIdleSweep(deps.log, () => runIdleSweep(engine))).catch(() => { /* idle sweep is best-effort; never kill serve */ })+ .then(() => shuttingDown || stdinSawData || sawForeground() ? undefined : idleUpkeep.run(engine)) // GBRA-438: after the sweep, never beside it.finally(() => { sweepInFlight = false; });}, idleSweepIntervalMs());(idleSweepTimer as { unref?: () => void } | null)?.unref?.();diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7b2c56094a..e8c0618664 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1569,6 +1569,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', id: 'autopilot_refusals_structured_gbra438', text: '`gbrain autopilot --install` refusals (a PGLite brain without --force, no repo path) now go through the agent error contract: codes `autopilot_pglite_daemon` and `autopilot_no_repo`, a why, a fix and `--json` output, instead of a bare line on stderr; PGLite and repo-less users are pointed to `gbrain maintain --status`.' },{ since: 'TBD', id: 'cycle_skip_text_gbra438', text: 'A dream cycle phase skipped for want of a checkout no longer says (postgres/remote engine), which was wrong on PGLite: the summary is now: requires a local brain directory; this brain has no on-disk checkout; pass --dir <path> to run filesystem phases. The reason code `no_brain_dir` is unchanged.' },{ since: 'TBD', id: 'cycle_freshness_keyless_consent_gbra438', text: 'On a brain with no chat or embedding key, the `cycle_freshness` doctor fix (`gbrain dream --source <id>`) now asks no paid consent (`consent: []`, so `next: run`), because no phase it runs can spend.' },+ // GBRA-438 PR 2: serve runs the free upkeep while idle (core/maintenance/idle.ts); since TBD until the merge slot.+ { since: 'TBD', id: 'serve_idle_upkeep_gbra438', text: 'An open `gbrain serve` (stdio or HTTP) now runs the free unattended upkeep (`gbrain maintain --unattended`: link and timeline extraction, stale-page checks, free repair lanes, bookkeeping GC, and on a keyed brain the capped embedding step) while it is idle, at most once every 24 hours per brain, in slices of about 3 seconds that stop when a tool call arrives. It never deletes a page. `maintenance.auto false` or `GBRAIN_SWEEP=0` turns it off; an autopilot brain is left to autopilot. The record it writes is `maintenance.last_run` with runner `serve`.' },+ { since: 'TBD', id: 'serve_http_idle_timer_gbra438', text: 'HTTP `gbrain serve --http` now has an idle timer: it counts an MCP POST as foreground work and runs the idle upkeep only when no request is in flight, aborting the upkeep slice when one arrives. Before, only the stdio server had idle work.' },+ { since: 'TBD', id: 'init_upkeep_line_gbra438', text: 'The first-run settings block printed by `gbrain init` and `gbrain setup <harness>` (and its `--json` decisions) now includes an `upkeep` decision when it shows other settings: upkeep runs while an agent has `gbrain serve` open and idle, on by default, turned off with `gbrain config set maintenance.auto false`. New commands: `gbrain maintain --schedule` (opt-in launchd, systemd or cron job every 6 hours, preview with `--dry-run`, asks consent) and `--unschedule`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex d35240491f..d570e41420 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--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', '--claims', '--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'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--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', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--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', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--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', '--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', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--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'],@@ -78,14 +78,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', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--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', '--yes'],- 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--dir', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--unattended', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--dir', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--unattended', '--uninstall', '--unschedule', '--unsettle', '--untrack', '--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', '--as', '--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', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--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', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--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-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reason', '--reason-scan-limit', '--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', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--unattended', '--uninstall', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--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', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--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-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reason', '--reason-scan-limit', '--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', '--routing', '--row', '--save', '--schedule', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--unattended', '--uninstall', '--unschedule', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--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': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--older-than', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--runner', '--safe', '--scan-secrets', '--scope', '--scopes', '--serves', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--unattended', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'maintain': ['--absolute-git-dir', '--accept-dns', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--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', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--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'],@@ -124,7 +124,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'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', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--limit', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--no-stdio-member', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--serves', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--surface', '--token', '--url', '--workspace', '--yes'],+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--limit', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--no-stdio-member', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--surface', '--token', '--url', '--workspace', '--yes'],'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--skill-loading', '--source', '--text', '--top-k'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex f891b8936b..65bcd018a2 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1473,7 +1473,7 @@ async function runPhaseExtract(includeFrontmatter,sourceIdFilter: sourceId,catchUp: false,- timeBudgetMs: CYCLE_STALE_DRAIN_BUDGET_MS,+ timeBudgetMs: CYCLE_STALE_DRAIN_BUDGET_MS, signal, // GBRA-438: idle upkeep's budget and a tool call stop the drain});staleRemaining = drained.staleRemaining;staleDetails = {@@ -2357,7 +2357,7 @@ async function runCycleUnscoped(details: { reason: 'no_database' },});} else if (brainDir === null) {- const { result, duration_ms } = await timePhase(async () => (await import('./cycle/connector-extract.ts')).runPhaseExtractDatabaseOnly(engine, { dryRun, sourceId: cycleSourceId, timeBudgetMs: CYCLE_STALE_DRAIN_BUDGET_MS }), 'extract');+ const { result, duration_ms } = await timePhase(async () => (await import('./cycle/connector-extract.ts')).runPhaseExtractDatabaseOnly(engine, { dryRun, sourceId: cycleSourceId, timeBudgetMs: CYCLE_STALE_DRAIN_BUDGET_MS, signal: cycleSignal }), 'extract');phaseResults.push({ ...result, duration_ms });} else {// No sync (or a failed one) and no source window (#8573): syncPagesAffecteddiff --git a/src/core/cycle/connector-extract.ts b/src/core/cycle/connector-extract.tsindex d57f385bd8..1bd11e04b1 100644--- a/src/core/cycle/connector-extract.ts+++ b/src/core/cycle/connector-extract.ts@@ -43,7 +43,7 @@ export function staleDrainFailures(drained: { linkFailed?: number; linkFailures?export async function runPhaseExtractDatabaseOnly(engine: BrainEngine,- opts: { dryRun: boolean; sourceId?: string; timeBudgetMs: number },+ opts: { dryRun: boolean; sourceId?: string; timeBudgetMs: number; signal?: AbortSignal },): Promise<PhaseResult> {if (opts.dryRun) {return {@@ -61,6 +61,7 @@ export async function runPhaseExtractDatabaseOnly(sourceIdFilter: opts.sourceId,catchUp: false,timeBudgetMs: opts.timeBudgetMs,+ signal: opts.signal,});const failures = staleDrainFailures(drained);return {diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 06ecb38153..ce463e7a3b 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -800,6 +800,9 @@ async function pendingLegacyRows(engine: BrainEngine, sourceId: string): Promisereturn new Map(legacy.map(row => [row.entity_slug, parseInt(row.n ?? '0', 10)]));}+/** Pages between macrotask yields in the reconcile walk (about 10 ms of work on PGLite). */+const FACTS_WALK_YIELD_EVERY = 50;+/*** Run the extract_facts phase against the current brain state. Returns* an ExtractFactsResult envelope; status mapping (ok / warn / fail)@@ -1121,6 +1124,9 @@ export async function runExtractFacts(};for (const slug of slugs) {+ // GBRA-438: PGLite resolves queries on a microtask chain, so a macrotask yield every FACTS_WALK_YIELD_EVERY pages lets a+ // timer, a budget or a request (stdin) trip the abort mid-walk instead of after it.+ if (result.pagesScanned > 0 && result.pagesScanned % FACTS_WALK_YIELD_EVERY === 0) await new Promise(r => setTimeout(r, 0));// #1972: bail at the top of the per-page loop on abort. Each page is an// independent delete-then-insert commit, so breaking leaves a consistent// partial state; the receipt/rollup below still runs with partial counts.diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 859359f84d..113a6a2b80 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -70,6 +70,9 @@ export const CODES = {cycle_already_running: { class: 'retryable', summary: 'Another maintenance cycle holds the brain cycle lock, so this run skipped instead of waiting.', why: 'Cycles serialize on the gbrain-cycle lease; the holder releases it when it finishes (or its TTL lapses after a crash).', suggestion: 'Wait for the other cycle; unattended upkeep retries on its next turn (gbrain maintain --status shows the last skip).' },engine_degraded: { class: 'unavailable', summary: 'The brain database was unreachable (the engine is in degraded mode), so background work such as unattended upkeep skipped this run.', why: 'A degraded engine answers from its last state and reconnects on its own; writing maintenance results then would be lost or refused.', suggestion: 'Run gbrain doctor --json and report the connection problem it names.' },maintenance_disabled: { class: 'caller', exit: 0, summary: 'Free unattended upkeep is off on this brain (maintenance.auto is false), so nothing ran.', why: 'The person turned upkeep off; doctor reads it as off, not stale.', suggestion: 'Turn it back on with gbrain config set maintenance.auto true.' },+ maintenance_owned_by_serve: { class: 'caller', exit: 0, summary: 'A live gbrain serve owns this brain and runs free upkeep while idle, so the scheduled upkeep run did nothing (serve owns upkeep).', why: 'One runner at a time: the serve holds the brain (the PGLite lock, or the warm CLI socket on Postgres) and runs the same free upkeep on its idle tick.', suggestion: 'Nothing to do; gbrain maintain --status shows the last run and its runner.' },+ schedule_unsupported: { class: 'caller', reasons: ['windows', 'container'], summary: 'gbrain maintain --schedule installed nothing: on Windows and in containers it has no installer.', why: 'Windows gets the schtasks line to add by hand (minimal Windows support). In a container an operating-system schedule does not survive a redeploy, so the resident gbrain serve is the upkeep runner there.', suggestion: 'On Windows, add the printed schtasks line yourself. In a container, keep gbrain serve running; it runs free upkeep while idle.' },+ schedule_install_failed: { class: 'host_only', retryable: false, actor: 'user', summary: 'gbrain maintain --schedule wrote its files, but the operating-system scheduler (launchctl, systemctl --user or crontab) refused the job.', why: 'The scheduler belongs to the host: a missing user session bus, a locked crontab or a launchd error stops the job from loading.', suggestion: 'Read the scheduler error in the message, fix it on the host, then run gbrain maintain --schedule --yes again (gbrain maintain --unschedule removes the files).' },maintenance_owned_by_autopilot: { class: 'caller', exit: 0, summary: 'An autopilot keeps this brain maintained (its brain-wide pass stamped autopilot.last_global_at within 48 hours), so free upkeep did nothing.', why: 'One owner per brain: the autopilot already runs the free phases and more, on any host sharing the database.', suggestion: 'Nothing to do; gbrain autopilot --status shows the daemon.' },on_behalf_of_invalid_audience: { class: 'caller', summary: "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', suggestion: 'Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.' },on_behalf_of_unknown_member: { class: 'caller', summary: "A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read.", why: 'An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads.', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member', suggestion: 'Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest.' },@@ -1070,4 +1073,5 @@ export const NOTICE_CODES = {engine_degraded: { kind: 'degraded', summary: 'Unattended upkeep skipped this run because the brain database was unreachable (degraded engine).' },maintenance_disabled: { kind: 'info', summary: 'Unattended upkeep is off on this brain (maintenance.auto is false).' },maintenance_owned_by_autopilot: { kind: 'info', summary: 'An autopilot keeps this brain maintained, so free upkeep did nothing.' },+ maintenance_owned_by_serve: { kind: 'info', summary: 'A live gbrain serve owns this brain and runs free upkeep while idle, so the scheduled upkeep run did nothing.' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/foreground-activity.ts b/src/core/foreground-activity.tsindex d8ae637e17..5c414af901 100644--- a/src/core/foreground-activity.ts+++ b/src/core/foreground-activity.ts@@ -1,15 +1,24 @@/**- * GBRA-156: foreground requests a serve answers outside its MCP stdin (the warm CLI socket). The serve's idle- * maintenance sweep treats a window with one as active, as it treats stdin data, so a sweep never starts while warm- * CLI searches are flowing and competing with them for the event loop and the pool.+ * GBRA-156: foreground requests a serve answers outside its MCP stdin (the warm CLI socket, and the HTTP serve's /mcp+ * requests). The serve's idle maintenance sweep and idle upkeep treat a window with one as active, as they treat stdin+ * data, so neither starts while requests are flowing and competing with them for the event loop and the pool; a request+ * that starts during idle upkeep aborts it (GBRA-438).*/let inFlight = 0;let lastAt = 0;+const startListeners = new Set<() => void>();++/** Calls `listener` when a foreground request starts (idle upkeep aborts on it); returns the unsubscribe. */+export function onForegroundRequest(listener: () => void): () => void {+ startListeners.add(listener);+ return () => { startListeners.delete(listener); };+}/** Marks one foreground request started; the returned function marks it finished (idempotent). */export function beginForegroundRequest(now: () => number = Date.now): () => void {inFlight++;lastAt = now();+ for (const listener of startListeners) listener();let done = false;return () => {if (done) return;@@ -33,4 +42,18 @@ export function foregroundWindow(now: () => number = Date.now): () => boolean {export function _resetForegroundActivityForTests(): void {inFlight = 0;lastAt = 0;+ startListeners.clear();+}++/**+ * GBRA-438: the HTTP serve's /mcp middleware. A POST is foreground activity, so idle upkeep waits for a quiet window+ * and a request aborts a run in flight; GET /mcp (a long-lived event stream) does not count.+ */+export function mcpForegroundMiddleware(req: { method: string }, res: { once(event: 'finish' | 'close', fn: () => void): unknown }, next: () => void): void {+ if (req.method === 'POST') {+ const done = beginForegroundRequest();+ res.once('finish', done);+ res.once('close', done);+ }+ next();}diff --git a/src/core/maintenance/idle.ts b/src/core/maintenance/idle.tsnew file mode 100644index 0000000000..0b579a1b7f--- /dev/null+++ b/src/core/maintenance/idle.ts@@ -0,0 +1,88 @@+/**+ * Idle upkeep (GBRA-438 PR 2): the resident runner. A `gbrain serve` runs+ * free upkeep while its agent is quiet, a few seconds at a time, so a keyless+ * repo-less brain is maintained without any installed service.+ *+ * The stdio serve calls `runIdleUpkeep` from its existing idle tick, after+ * the maintenance sweep and never beside it. The HTTP serve has no stdin, so+ * `armIdleUpkeep` gives it the same tick keyed on request activity (the+ * foreground-activity window its /mcp requests mark). Both skip the first+ * tick (never at boot), run only when upkeep is on and due, pass a small+ * budget, and abort the run when a request arrives.+ */+import type { BrainEngine } from '../engine.ts';+import { foregroundWindow, onForegroundRequest } from '../foreground-activity.ts';+import { readUpkeepRecord, runUnattendedMaintenance, upkeepDue, upkeepEnabled, type UpkeepOpts, type UpkeepOutcome } from './run.ts';++/** Wall-clock budget of one idle run; an unfinished round resumes on the next quiet tick. */+export const IDLE_UPKEEP_BUDGET_MS = 3_000;++export interface IdleUpkeepOpts {+ runner: string;+ signal: AbortSignal;+ budgetMs?: number;+ log?: (line: string) => void;+ /** Test seams, passed to the runner. */+ now?: () => Date;+ providers?: UpkeepOpts['providers'];+ cycle?: UpkeepOpts['cycle'];+}++/** One idle run: nothing (null) when upkeep is off or not due, else the runner's outcome. Never throws. */+export async function runIdleUpkeep(engine: BrainEngine, opts: IdleUpkeepOpts): Promise<UpkeepOutcome | null> {+ try {+ if (opts.signal.aborted || !await upkeepEnabled(engine)) return null;+ if (!upkeepDue(await readUpkeepRecord(engine), (opts.now ?? (() => new Date()))())) return null;+ } catch {+ return null;+ }+ const startedAt = Date.now();+ opts.log?.(`[gbrain serve] idle upkeep: started`);+ const outcome = await runUnattendedMaintenance(engine, {+ runner: opts.runner, budgetMs: opts.budgetMs ?? IDLE_UPKEEP_BUDGET_MS, signal: opts.signal,+ ...(opts.now ? { now: opts.now } : {}), ...(opts.providers ? { providers: opts.providers } : {}), ...(opts.cycle ? { cycle: opts.cycle } : {}),+ });+ opts.log?.(`[gbrain serve] idle upkeep: finished in ${Date.now() - startedAt} ms (${outcome.status}${outcome.code ? ` ${outcome.code}` : ''})`);+ return outcome;+}++export interface IdleUpkeepTimerDeps {+ intervalMs: number;+ setInterval: (fn: () => void, ms: number) => unknown;+ clearInterval: (handle: unknown) => void;+ /** One run with the abort signal a request trips; defaults to `runIdleUpkeep` as runner `serve`. */+ upkeep?: (engine: BrainEngine, signal: AbortSignal) => Promise<unknown>;+ log?: (line: string) => void;+}++/**+ * The HTTP serve's idle tick: each interval with no foreground request since+ * the previous one runs one upkeep run (never two at once); the first tick+ * only opens the window. A request that starts mid-run aborts it.+ */+export function armIdleUpkeep(engine: BrainEngine, deps: IdleUpkeepTimerDeps): { stop(): void } {+ const upkeep = deps.upkeep ?? ((e: BrainEngine, signal: AbortSignal) => runIdleUpkeep(e, { runner: 'serve', signal, log: deps.log }));+ const sawForeground = foregroundWindow();+ let opened = false;+ let running: AbortController | null = null;+ const unsubscribe = onForegroundRequest(() => running?.abort());+ const handle = deps.setInterval(() => {+ const active = sawForeground();+ if (!opened) { opened = true; return; }+ if (active || running) return;+ const controller = new AbortController();+ running = controller;+ Promise.resolve()+ .then(() => upkeep(engine, controller.signal))+ .catch(() => { /* best-effort; never kill serve */ })+ .finally(() => { if (running === controller) running = null; });+ }, deps.intervalMs);+ (handle as { unref?: () => void } | null)?.unref?.();+ return {+ stop() {+ deps.clearInterval(handle);+ unsubscribe();+ running?.abort();+ },+ };+}diff --git a/src/core/maintenance/run.ts b/src/core/maintenance/run.tsindex 24018975ae..50fe3d1b8e 100644--- a/src/core/maintenance/run.ts+++ b/src/core/maintenance/run.ts@@ -175,6 +175,11 @@ export async function readUpkeepRecord(engine: BrainEngine): Promise<UpkeepRecor}}+/** Whether a run would do work now: no record yet, a round left unfinished, or past next_due_at. */+export function upkeepDue(record: UpkeepRecord | null, now: Date): boolean {+ return !record || !!record.cursor || !(Date.parse(record.next_due_at) > now.getTime());+}+export async function upkeepEnabled(engine: BrainEngine): Promise<boolean> {const raw = (await engine.getConfig(MAINTENANCE_AUTO_KEY).catch(() => null))?.trim().toLowerCase();return !(raw === 'false' || raw === '0' || raw === 'off' || raw === 'no');@@ -323,6 +328,20 @@ async function runEmbedStep(engine: BrainEngine, now: Date, signal: AbortSignalreturn { step: { name: 'embed', scope: 'global', status, ...(code ? { code } : {}), ...(reason ? { reason } : {}) }, embed: embed(total) };}+/**+ * PGLite only: a top-level CHECKPOINT once a round finishes, outside every+ * transaction, so the WAL the round wrote is folded into the data files+ * while the brain is quiet instead of at the next open.+ */+async function checkpointStep(engine: BrainEngine): Promise<UpkeepStep> {+ try {+ await engine.executeRaw('CHECKPOINT');+ return { name: 'checkpoint', scope: 'global', status: 'ok' };+ } catch (error) {+ return { name: 'checkpoint', scope: 'global', status: 'fail', code: (error as { code?: string } | null)?.code ?? 'checkpoint_failed' };+ }+}+/*** One unattended upkeep run. Never throws: a run that cannot start returns a* skip with its code and fix, a failed step is recorded with its own code and@@ -337,8 +356,8 @@ export async function runUnattendedMaintenance(engine: BrainEngine, opts: Upkeepif (prior && refused.code) await engine.setConfig(MAINTENANCE_LAST_RUN_KEY, JSON.stringify({ ...prior, last_skip: { at: now.toISOString(), code: refused.code } }));return refused;}- if (prior && !prior.cursor && Date.parse(prior.next_due_at) > now.getTime()) {- return { status: 'not_due', exit: 0, message: `Upkeep already ran at ${prior.at}; next due at ${prior.next_due_at}.`, record: prior };+ if (!upkeepDue(prior, now)) {+ return { status: 'not_due', exit: 0, message: `Upkeep already ran at ${prior!.at}; next due at ${prior!.next_due_at}.`, record: prior! };}const plan = unattendedPlan(opts.providers ?? await readSafePhaseProviders(engine));const sources = (await engine.listAllSources()).sort((a, b) => a.id.localeCompare(b.id));@@ -396,6 +415,7 @@ export async function runUnattendedMaintenance(engine: BrainEngine, opts: Upkeepsteps.push(result.step);embed = result.embed;}+ if (finished && engine.kind === 'pglite' && !opts.signal?.aborted) steps.push(await checkpointStep(engine));const failed = steps.filter((step) => step.status === 'fail');const nextFailures: UpkeepFailure[] = failures.filter((f) => !steps.some((s) => s.name === f.step && s.scope === f.scope && s.status !== 'fail' && s.reason !== 'backed_off'));diff --git a/src/core/maintenance/status.ts b/src/core/maintenance/status.tsindex e79682065e..271311de93 100644--- a/src/core/maintenance/status.ts+++ b/src/core/maintenance/status.ts@@ -30,6 +30,8 @@ export interface UpkeepStatus {embed_spend_today_usd: number | null;embed_daily_cap_usd: number | null;fix?: Action;+ /** The second option beside `fix` when upkeep is overdue: the opt-in operating-system schedule. */+ alternative_fix?: Action;}function ago(ms: number): string {@@ -65,6 +67,19 @@ export function upkeepFix(paid: boolean): Action {};}+/** Overdue means no serve ran upkeep: name both ways back. */+const SCHEDULE_NOTE = ' It runs while an agent\'s gbrain serve is open and idle; run it now with gbrain maintain --unattended, or add the opt-in schedule with gbrain maintain --schedule.';++/** The second option: install the opt-in schedule, a persistent_install the user approves. */+export function scheduleFix(): Action {+ return {+ argv: ['gbrain', 'maintain', '--schedule'], consent: ['persistent_install'], actor: 'agent', requires_exclusive: false,+ preview_argv: ['gbrain', 'maintain', '--schedule', '--dry-run'],+ why: 'Installs an operating-system schedule (launchd, systemd user timer or crontab) that runs free upkeep every 6 hours when no gbrain serve is running; gbrain maintain --unschedule removes it.',+ verify: { argv: ['gbrain', 'doctor', '--only', 'unattended_maintenance', '--json'] },+ };+}+export async function readUpkeepStatus(engine: BrainEngine, nowMs: number = Date.now()): Promise<UpkeepStatus> {const now = new Date(nowMs);const [record, enabled, owner, pending, cap, spent] = await Promise.all([@@ -94,11 +109,11 @@ export async function readUpkeepStatus(engine: BrainEngine, nowMs: number = Dateif (age === null || age < UPKEEP_OVERDUE_MS) {return { ...base, state: 'never', message: `Free upkeep has not run on this brain yet; gbrain maintain --unattended runs it (no model calls, no page purge).${purgeNote}` };}- return { ...base, fix, state: 'overdue', message: `No free upkeep run is recorded on this brain, which is ${ago(age)} old.${purgeNote}` };+ return { ...base, fix, alternative_fix: scheduleFix(), state: 'overdue', message: `No free upkeep run is recorded on this brain, which is ${ago(age)} old.${SCHEDULE_NOTE}${purgeNote}` };}const age = nowMs - Date.parse(record.at);if (age > UPKEEP_OVERDUE_MS) {- return { ...base, fix, state: 'overdue', message: `Free upkeep last ran ${ago(age)} ago (${record.runner}), past its 48h window.${purgeNote}${spendNote}` };+ return { ...base, fix, alternative_fix: scheduleFix(), state: 'overdue', message: `Free upkeep last ran ${ago(age)} ago (${record.runner}), past its 48h window.${SCHEDULE_NOTE}${purgeNote}${spendNote}` };}const ran = record.steps.filter((s) => s.status === 'ok' || s.status === 'warn').length;const due = Date.parse(record.next_due_at) - nowMs;diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.tsindex bcf180b569..d5214beb07 100644--- a/src/core/persistence/links-maintenance.ts+++ b/src/core/persistence/links-maintenance.ts@@ -36,11 +36,11 @@ export const LINK_FAILURE_REPORT_LIMIT = 50;* `STALE_TIME_BUDGET_MS` budget and the next resumes, `catchUp` runs until nothing is stale (#6803 D2).*/export async function runManagedStaleExtraction(engine: BrainEngine,- opts: { sourceId?: string; dryRun?: boolean; catchUp?: boolean; timeBudgetMs?: number; counts?: boolean; retryHeld?: boolean }): Promise<ManagedLinkExtraction> {+ opts: { sourceId?: string; dryRun?: boolean; catchUp?: boolean; timeBudgetMs?: number; counts?: boolean; retryHeld?: boolean; signal?: AbortSignal }): Promise<ManagedLinkExtraction> {const counts = async () => opts.counts === false ? {} : { counts: await staleExtractionCounts(engine, opts.sourceId) };if (!opts.dryRun) {if (opts.retryHeld) await clearLinkExtractionHolds(engine, opts.sourceId);- const result = await extractManagedStaleLinks(engine, { sourceId: opts.sourceId, ...(opts.catchUp ? {} : { timeBudgetMs: opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS }) });+ const result = await extractManagedStaleLinks(engine, { sourceId: opts.sourceId, signal: opts.signal, ...(opts.catchUp ? {} : { timeBudgetMs: opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS }) });return { ...result, ...await counts() };}const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: await effectiveLinkExtractorWatermark(engine), held: 'exclude' });diff --git a/src/core/serve-service.ts b/src/core/serve-service.tsindex 9fd3058242..1e77fdb986 100644--- a/src/core/serve-service.ts+++ b/src/core/serve-service.ts@@ -225,7 +225,7 @@ exec "$_gbrain"${programTail ? ` ${programTail}` : ''} ${serveArgs}`;}-function escapeXml(s: string): string {+export function escapeXml(s: string): string {return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');}@@ -254,7 +254,7 @@ export function renderServeLaunchdPlist(p: LaunchdParams): string {export interface SystemdParams { wrapperPath: string; logPath: string; errPath: string }/** systemd specifier escaping (`%h` etc. expand in every path-like setting): `%` → `%%`. */-function systemdSpecifierEscape(s: string): string {+export function systemdSpecifierEscape(s: string): string {return s.replace(/%/g, '%%');}@@ -262,7 +262,7 @@ function systemdSpecifierEscape(s: string): string {* ExecStart quoting: `%` → `%%` (specifiers), `$` → `$$` (environment* expansion), then double-quote when the path carries whitespace or quotes.*/-function systemdArg(s: string): string {+export function systemdArg(s: string): string {const escaped = systemdSpecifierEscape(s).replace(/\$/g, '$$$$');return /[\s"'\\]/.test(escaped) ? `"${escaped.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"` : escaped;}diff --git a/test/e2e/serve-idle-upkeep-keyless-pglite.test.ts b/test/e2e/serve-idle-upkeep-keyless-pglite.test.tsnew file mode 100644index 0000000000..64da426c49--- /dev/null+++ b/test/e2e/serve-idle-upkeep-keyless-pglite.test.ts@@ -0,0 +1,71 @@+/**+ * GBRA-438 PR 2, done item 2: free upkeep runs inside the agent's own+ * \`gbrain serve\` on a fresh keyless, repo-less PGLite brain, black-box+ * through the real CLI. init, import and remember; start a stdio serve with a+ * one-second GBRAIN_SWEEP_IDLE_INTERVAL_MS and leave it idle past due. While it+ * runs, a scheduled run exits 0 because the serve owns upkeep (the real+ * live-serve probe). After it stops: links are extracted, maintenance.last_run+ * names runner serve, and doctor's unattended_maintenance is ok.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from '../helpers/cli-spawn.ts';++const KEYLESS = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined, GEMINI_API_KEY: undefined, JEV_TYPESAFE_API_KEY: undefined };+const TIMEOUT_MS = 180_000;+const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');++describe('stdio serve runs free upkeep while idle (keyless, repo-less PGLite)', () => {+ let home: string;+ const gbrain = (args: string[]) => runCli(args, { home, env: KEYLESS, timeoutMs: TIMEOUT_MS });++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-serve-upkeep-e2e-'));+ expect((await gbrain(['init', '--pglite', '--no-embedding', '--non-interactive'])).exitCode).toBe(0);+ const notes = join(home, 'notes');+ mkdirSync(notes);+ writeFileSync(join(notes, 'alpha.md'), '---\ntitle: Alpha\ntype: concept\n---\n# Alpha\n\nAlpha relies on [[beta]].\n');+ writeFileSync(join(notes, 'beta.md'), '---\ntitle: Beta\ntype: concept\n---\n# Beta\n\nBeta.\n');+ expect((await gbrain(['import', notes, '--no-embed'])).exitCode).toBe(0);+ const remember = await gbrain(['remember', 'Alpha ships on Fridays.', '--entity', 'alpha', '--content-origin', 'user_said', '--provenance', 'e2e test']);+ expect(remember.exitCode).toBe(0);+ }, TIMEOUT_MS);++ afterAll(() => rmSync(home, { recursive: true, force: true }));++ test('an idle serve runs upkeep as runner serve; the scheduled run defers to it; doctor is ok', async () => {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', ...Object.keys(KEYLESS)]) delete env[k];+ Object.assign(env, { HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP_IDLE_INTERVAL_MS: '1000' });+ const serve = Bun.spawn({ cmd: [process.execPath, '--no-env-file', CLI, 'serve'], env, cwd: home, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });+ let log = '';+ const reader = (async () => { for await (const chunk of serve.stderr) log += new TextDecoder().decode(chunk); })();+ try {+ const deadline = Date.now() + 120_000;+ while (!/idle upkeep: finished/.test(log) && Date.now() < deadline && serve.exitCode === null) await Bun.sleep(250);+ expect(log).toMatch(/idle upkeep: started/);+ expect(log).toMatch(/idle upkeep: finished in \d+ ms \(ran\)/);+ expect(log.indexOf('idle sweep: finished')).toBeLessThan(log.indexOf('idle upkeep: started'));+ const scheduled = await gbrain(['maintain', '--unattended', '--runner', 'schedule', '--json']);+ expect(scheduled.exitCode).toBe(0);+ expect(JSON.parse(scheduled.stdout)).toMatchObject({ status: 'skipped', exit: 0, code: 'maintenance_owned_by_serve' });+ } finally {+ serve.stdin.end();+ const killer = setTimeout(() => serve.kill(9), 15_000);+ await serve.exited;+ clearTimeout(killer);+ await reader.catch(() => {});+ }+ const status = JSON.parse((await gbrain(['maintain', '--status', '--json'])).stdout);+ expect(status).toMatchObject({ state: 'ok', runner: 'serve' });+ const links = JSON.parse((await gbrain(['backlinks', 'beta', '--json'])).stdout);+ expect(links.map((l: { from_slug: string }) => l.from_slug)).toEqual(['alpha']);+ const doctor = JSON.parse((await gbrain(['doctor', '--only', 'unattended_maintenance', '--json'])).stdout);+ const check = doctor.checks.find((c: { name: string }) => c.name === 'unattended_maintenance');+ expect(check).toMatchObject({ status: 'ok', details: { state: 'ok', runner: 'serve' } });+ expect(check.message).toMatch(/^Free upkeep ran \d+m ago \(serve, \d+ steps ok\)\./);+ }, TIMEOUT_MS);+});diff --git a/test/fixtures/agent-contract/v1/journey/init-first-run.json b/test/fixtures/agent-contract/v1/journey/init-first-run.jsonindex a19974f47c..bf4260d88a 100644--- a/test/fixtures/agent-contract/v1/journey/init-first-run.json+++ b/test/fixtures/agent-contract/v1/journey/init-first-run.json@@ -29,7 +29,7 @@"code": "first_run_decisions","kind": "ask","why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",- "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip), or tell me what to change.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; writeback: salient; harness_wiring: skip; upkeep: on), or tell me what to change.","decisions": [{"id": "search_mode",@@ -128,6 +128,29 @@],"default": "skip","default_reason": "No agent harness was detected."+ },+ {+ "id": "upkeep",+ "question": "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.",+ "options": [+ {+ "id": "on",+ "label": "Keep free upkeep on (in effect now)"+ },+ {+ "id": "off",+ "label": "Turn free upkeep off",+ "argv": [+ "gbrain",+ "config",+ "set",+ "maintenance.auto",+ "false"+ ]+ }+ ],+ "default": "on",+ "default_reason": "In effect now: the agent's gbrain serve runs the free upkeep tier while idle; nothing needs an answer."}],"contract_version": 1diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex c440fb02b0..0415c167b5 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -1175,7 +1175,17 @@"maintain": {"hasSwitchCase": true,"phase": "post-connect",- "preConnectRules": [],+ "preConnectRules": [+ {+ "condition": "command === 'maintain' && await (await import('../commands/maintain-schedule.ts')).tryRunMaintainEngineFree(args)",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": false,+ "unconditionalFor": []+ }+ ],"thinClient": "none","thinClientRoutedSubcommands": []},diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex cdb2e99b4c..57ff575722 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4845,7 +4845,7 @@"kind": "function","name": "extractStaleFromDB","signature": [- "(engine: BrainEngine, opts: { dryRun: boolean; jsonMode: boolean; quiet?: boolean; includeFrontmatter?: boolean; sourceIdFilter?: string; catchUp: boolean; timeBudgetMs?: number; retryHeld?: boolean; }) => Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; skippedUnknownSource?: number; mentions?: MentionPassResult; linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[]; }>"+ "(engine: BrainEngine, opts: { dryRun: boolean; jsonMode: boolean; quiet?: boolean; includeFrontmatter?: boolean; sourceIdFilter?: string; catchUp: boolean; timeBudgetMs?: number; retryHeld?: boolean; signal?: AbortSignal; }) => Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; skippedConcurrentWrite?: number; skippedUnknownSource?: number; mentions?: MentionPassResult; linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[]; }>"]},{@@ -6857,7 +6857,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",diff --git a/test/fixtures/goldens/serve-http/routes-runtime.json b/test/fixtures/goldens/serve-http/routes-runtime.jsonindex 4289d6e949..d579b10503 100644--- a/test/fixtures/goldens/serve-http/routes-runtime.json+++ b/test/fixtures/goldens/serve-http/routes-runtime.json@@ -25,6 +25,13 @@"method": "use","path": null},+ {+ "handlers": [+ "mcpForegroundMiddleware"+ ],+ "method": "use",+ "path": "/mcp"+ },{"handlers": ["corsMiddleware"@@ -775,6 +782,13 @@"method": "use","path": null},+ {+ "handlers": [+ "mcpForegroundMiddleware"+ ],+ "method": "use",+ "path": "/mcp"+ },{"handlers": ["corsMiddleware"diff --git a/test/fixtures/goldens/serve-http/routes.json b/test/fixtures/goldens/serve-http/routes.jsonindex d17547ee83..125019c20b 100644--- a/test/fixtures/goldens/serve-http/routes.json+++ b/test/fixtures/goldens/serve-http/routes.json@@ -32,6 +32,14 @@"path": null,"when": []},+ {+ "handlers": [+ "mcpForegroundMiddleware"+ ],+ "method": "use",+ "path": "/mcp",+ "when": []+ },{"handlers": ["cors(corsOAuthOptions)"diff --git a/test/init-first-run.test.ts b/test/init-first-run.test.tsindex afc5d2b078..4a2aacf0a8 100644--- a/test/init-first-run.test.ts+++ b/test/init-first-run.test.ts@@ -5,7 +5,7 @@* offering 'defaults'. Pure: no engine, no filesystem.*/import { describe, expect, test } from 'bun:test';-import { buildInitFirstRunNotices, setupFirstRunNotices } from '../src/commands/init-first-run.ts';+import { buildInitFirstRunNotices, setupFirstRunNotices, upkeepLine } from '../src/commands/init-first-run.ts';import { costMatrixSentence } from '../src/core/search/mode-advice.ts';const searchMode = { mode: 'balanced' as const, reason: 'Balanced default for a new brain.' };@@ -51,6 +51,41 @@ describe('buildInitFirstRunNotices', () => {});});+describe('the upkeep line (GBRA-438)', () => {+ test('rides the bundle last as a setting in effect: the plan\'s wording, default on, off through config set', () => {+ const [bundle] = buildInitFirstRunNotices({ searchMode, upkeep: { embedding: false } });+ expect(bundle.decisions!.map(d => d.id)).toEqual(['search_mode', 'upkeep']);+ const upkeep = bundle.decisions!.find(d => d.id === 'upkeep')!;+ expect(upkeep.question).toBe(+ "Upkeep: free upkeep runs on its own while your agent's gbrain session is open. Nothing is deleted or paid for without you. "+ + 'Turn off: gbrain config set maintenance.auto false. Optional schedule: gbrain maintain --schedule.',+ );+ expect(upkeep.question).not.toContain('?');+ expect(upkeep.default).toBe('on');+ expect(upkeep.options.find(o => o.id === 'on')!.argv).toBeUndefined();+ expect(upkeep.options.find(o => o.id === 'off')!.argv).toEqual(['gbrain', 'config', 'set', 'maintenance.auto', 'false']);+ expect(bundle.user_message).toContain('upkeep: on');+ });++ test('a keyed brain\'s line names the one capped paid step', () => {+ expect(upkeepLine(true)).toContain('the only paid step is embedding new text, capped at $1 a day (maintenance.embed_daily_usd)');+ expect(upkeepLine(true)).not.toContain('paid for without you');+ });++ test('upkeep alone never opens a bundle', () => {+ expect(buildInitFirstRunNotices({ writeback: false, skillsScaffold: null, upkeep: { embedding: false } })).toEqual([]);+ });++ test('setup states it once in the settings it relays, never as a question', () => {+ const [bundle] = buildInitFirstRunNotices({ searchMode, upkeep: { embedding: false } });+ const [n] = setupFirstRunNotices([{ ...bundle, contract_version: 1 }], 'Claude Code');+ expect(n.user_message!.split(upkeepLine(false)).length).toBe(2);+ expect(n.user_message).toContain("Nothing needs an answer now");+ const [alone] = setupFirstRunNotices([{ ...bundle, decisions: bundle.decisions!.filter(d => d.id === 'upkeep'), contract_version: 1 }], 'Claude Code');+ expect(alone.user_message).toBe(`gbrain is set up and Claude Code is wired, so memory works now. ${upkeepLine(false)} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`);+ });+});+describe('setupFirstRunNotices (gbrain setup <harness>)', () => {const wiring = { id: 'harness_wiring', question: 'Which agent app should get gbrain memory?', options: [{ id: 'wire', label: 'wire' }, { id: 'skip', label: 'skip' }], default: 'wire', default_reason: 'detected' };const fromInit = (inputs: Parameters<typeof buildInitFirstRunNotices>[0]) => {diff --git a/test/maintain-schedule-gbra438.test.ts b/test/maintain-schedule-gbra438.test.tsnew file mode 100644index 0000000000..b72f7fe5ff--- /dev/null+++ b/test/maintain-schedule-gbra438.test.ts@@ -0,0 +1,221 @@+/**+ * GBRA-438 PR 2, done item 4: gbrain maintain --schedule / --unschedule, the+ * opt-in operating-system schedule for free upkeep (decision E1).+ *+ * 1. Protects: the generated wrapper, launchd plist, systemd service and timer+ * and cron line (pinned, pure); a refusal without --yes writes nothing and+ * exits through the consent contract; --dry-run writes nothing; the cron+ * install keeps one line per brain and --unschedule removes it; Windows and+ * containers install nothing and print their outcome; a scheduled run+ * exits 0 while a live serve owns the brain.+ * 2. Fails when: a generated file drifts, an install happens without consent,+ * a second install duplicates the cron line, or a scheduled run opens a+ * brain a serve owns.+ * 3. Seams: ScheduleEnv (platform, execution environment, dirs, a fake+ * CommandRunner, interactive=false) and tryRunMaintainEngineFree's liveServe.+ */+import { afterAll, afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ isScheduleCronLine, renderScheduleLaunchdPlist, renderScheduleSystemdService, renderScheduleSystemdTimer, renderScheduleWrapper,+ runMaintainSchedule, scheduleCronLine, scheduleNames, tryRunMaintainEngineFree, windowsScheduleCommand, type ScheduleEnv,+} from '../src/commands/maintain-schedule.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { exitCodeForCode } from '../src/core/error-catalogue.ts';+import type { CommandRunner } from '../src/core/tailscale.ts';++describe('generated files (pure)', () => {+ test('job names: bare for the default brain, suffixed for another GBRAIN_HOME', () => {+ expect(scheduleNames(null)).toEqual({ label: 'com.gbrain.maintain', unit: 'gbrain-maintain', cronMarker: '# gbrain-maintain' });+ expect(scheduleNames('abcd1234')).toEqual({ label: 'com.gbrain.maintain.abcd1234', unit: 'gbrain-maintain-abcd1234', cronMarker: '# gbrain-maintain:abcd1234' });+ });++ test('wrapper: env file, PATH, baked GBRAIN_HOME, PATH fallback, one unattended run as runner schedule', () => {+ expect(renderScheduleWrapper({ gbrainCommand: ['/opt/bun/bin/bun', '/opt/gbrain/src/cli.ts'], gbrainEnvFile: '/home/u/.gbrain/env', gbrainHome: '/home/u/alt', runtimeDir: '/opt/bun/bin' })).toBe(+ "#!/bin/bash\n"+ + "# Auto-generated by `gbrain maintain --schedule`: runs free upkeep once and exits.\n"+ + "# Remove with `gbrain maintain --unschedule`. Keys come from the gbrain env file only.\n"+ + "[ -f '/home/u/.gbrain/env' ] && { set -a; source '/home/u/.gbrain/env' 2>/dev/null; set +a; }\n"+ + "export PATH='/opt/bun/bin':\"$HOME/.bun/bin:$PATH\"\n"+ + "export GBRAIN_HOME='/home/u/alt'\n"+ + "cd \"$HOME\"\n"+ + "_gbrain='/opt/bun/bin/bun'\n"+ + "if [ ! -x \"$_gbrain\" ]; then\n"+ + " _gbrain=$(type -P gbrain 2>/dev/null)\n"+ + " if [ -z \"$_gbrain\" ]; then\n"+ + " echo \"$(date -u +%FT%TZ) [gbrain-maintain] gbrain CLI not found at\" '/opt/bun/bin/bun' \"nor on PATH; re-run: gbrain maintain --schedule\" >&2\n"+ + " exit 1\n"+ + " fi\n"+ + "fi\n"+ + "exec \"$_gbrain\" '/opt/gbrain/src/cli.ts' maintain --unattended --runner schedule\n",+ );+ expect(renderScheduleWrapper({ gbrainCommand: ['/usr/local/bin/gbrain'], gbrainEnvFile: '/h/.gbrain/env' })).toContain("export PATH=\"$HOME/.bun/bin:$PATH\"\ncd \"$HOME\"\n");+ });++ test('launchd: a user agent every 6 hours, at load, no KeepAlive', () => {+ expect(renderScheduleLaunchdPlist({ label: 'com.gbrain.maintain', wrapperPath: '/Users/u/.gbrain/maintain-run.sh', home: '/Users/u', logPath: '/Users/u/.gbrain/maintain.log' })).toBe(+ '<?xml version="1.0" encoding="UTF-8"?>\n'+ + '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'+ + '<plist version="1.0">\n'+ + '<dict>\n'+ + ' <key>Label</key><string>com.gbrain.maintain</string>\n'+ + ' <key>ProgramArguments</key><array>\n'+ + ' <string>/Users/u/.gbrain/maintain-run.sh</string>\n'+ + ' </array>\n'+ + ' <key>WorkingDirectory</key><string>/Users/u</string>\n'+ + ' <key>RunAtLoad</key><true/>\n'+ + ' <key>StartInterval</key><integer>21600</integer>\n'+ + ' <key>StandardOutPath</key><string>/Users/u/.gbrain/maintain.log</string>\n'+ + ' <key>StandardErrorPath</key><string>/Users/u/.gbrain/maintain.log</string>\n'+ + '</dict>\n'+ + '</plist>\n',+ );+ });++ test('systemd: a oneshot service and a persistent 6-hour timer', () => {+ expect(renderScheduleSystemdService({ wrapperPath: '/home/u/.gbrain/maintain-run.sh', logPath: '/home/u/.gbrain/maintain.log' })).toBe(+ '[Unit]\nDescription=GBrain free upkeep (gbrain maintain --unattended --runner schedule)\n\n'+ + '[Service]\nType=oneshot\nExecStart=/home/u/.gbrain/maintain-run.sh\n'+ + 'StandardOutput=append:/home/u/.gbrain/maintain.log\nStandardError=append:/home/u/.gbrain/maintain.log\n',+ );+ expect(renderScheduleSystemdTimer({ unit: 'gbrain-maintain' })).toBe(+ '[Unit]\nDescription=GBrain free upkeep every 6 hours\n\n'+ + '[Timer]\nOnCalendar=*-*-* 00/6:17:00\nPersistent=true\nRandomizedDelaySec=600\nUnit=gbrain-maintain.service\n\n'+ + '[Install]\nWantedBy=timers.target\n',+ );+ expect(renderScheduleSystemdService({ wrapperPath: '/home/u 1/%x.sh', logPath: '/l/%h.log' })).toContain('ExecStart="/home/u 1/%%x.sh"\nStandardOutput=append:/l/%%h.log');+ });++ test('cron: one tagged line every 6 hours; the marker matches only its own brain', () => {+ const line = scheduleCronLine({ wrapperPath: '/home/u/.gbrain/maintain-run.sh', logPath: '/home/u/.gbrain/maintain.log', marker: '# gbrain-maintain' });+ expect(line).toBe("17 */6 * * * '/home/u/.gbrain/maintain-run.sh' >> '/home/u/.gbrain/maintain.log' 2>&1 # gbrain-maintain");+ expect(isScheduleCronLine(line, '# gbrain-maintain')).toBe(true);+ expect(isScheduleCronLine(line.replace('# gbrain-maintain', '# gbrain-maintain:abcd1234'), '# gbrain-maintain')).toBe(false);+ expect(isScheduleCronLine('*/5 * * * * /x/autopilot-run.sh # gbrain-autopilot:abcd1234', '# gbrain-maintain')).toBe(false);+ });++ test('Windows: the schtasks line to add by hand', () => {+ expect(windowsScheduleCommand(['C:\\gbrain\\gbrain.exe'])).toBe('schtasks /Create /SC HOURLY /MO 6 /TN gbrain-maintain /TR "C:\\gbrain\\gbrain.exe maintain --unattended --runner schedule"');+ });+});++describe('gbrain maintain --schedule', () => {+ let root: string;+ let out: string[];+ let crontab: string;+ let calls: string[][];+ let logSpy: ReturnType<typeof spyOn>;+ let errSpy: ReturnType<typeof spyOn>;+ let stderrSpy: ReturnType<typeof spyOn>;+ let errOut: string[] = [];++ const run: CommandRunner = async (argv) => {+ calls.push(argv);+ if (argv[0] === 'crontab' && argv[1] === '-l') return { status: 0, stdout: crontab, stderr: '' };+ if (argv[0] === 'crontab') { crontab = readFileSync(argv[1]!, 'utf8'); return { status: 0, stdout: '', stderr: '' }; }+ return { status: 0, stdout: '', stderr: '' };+ };+ const env = (platform: string, executionEnv: ScheduleEnv['executionEnv'] = 'local'): ScheduleEnv => ({+ platform, executionEnv, home: join(root, 'home'), dir: join(root, 'home', '.gbrain'), names: scheduleNames(null),+ gbrainCommand: ['/usr/local/bin/gbrain'], runtimeDir: '', run, systemdBooted: false, interactive: false,+ });+ const json = () => JSON.parse(out.join('\n'));++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'gbrain-schedule-'));+ out = []; calls = []; crontab = 'MAILTO=""\n0 1 * * * /usr/bin/true\n';+ _resetCliExitVerdictForTests();+ logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });+ errSpy = spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => { out.push(String(chunk)); return true; }) as never);+ stderrSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { errOut.push(String(chunk)); return true; }) as never);+ errOut = [];+ });+ afterEach(() => {+ logSpy.mockRestore();+ errSpy.mockRestore();+ stderrSpy.mockRestore();+ rmSync(root, { recursive: true, force: true });+ });+ afterAll(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });++ test('without --yes it refuses through the consent contract and writes nothing', async () => {+ await runMaintainSchedule(['--schedule', '--json'], env('linux'));+ expect(currentExitCode()).toBe(exitCodeForCode('confirmation_required'));+ const doc = json();+ expect(JSON.stringify(doc)).toContain('persistent_install');+ expect(JSON.stringify(doc)).toContain('gbrain maintain --schedule --yes');+ expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);+ expect(calls.filter((c) => c[0] === 'crontab' && c[1] !== '-l')).toEqual([]);+ });++ test('--dry-run lists what it would write and writes nothing', async () => {+ await runMaintainSchedule(['--schedule', '--dry-run', '--json'], env('linux'));+ expect(currentExitCode()).toBe(0);+ expect(json()).toMatchObject({ status: 'dry_run', target: 'linux-cron', interval_hours: 6 });+ expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);+ });++ test('--yes on cron installs the wrapper and one line; a reinstall keeps one; --unschedule removes it and keeps the rest', async () => {+ await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux'));+ expect(currentExitCode()).toBe(0);+ expect(json()).toMatchObject({ status: 'installed', target: 'linux-cron' });+ const wrapper = join(root, 'home', '.gbrain', 'maintain-run.sh');+ expect(readFileSync(wrapper, 'utf8')).toContain('maintain --unattended --runner schedule');+ expect(crontab.split('\n').filter((l) => l.endsWith('# gbrain-maintain'))).toHaveLength(1);+ out.length = 0;+ await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux'));+ expect(crontab.split('\n').filter((l) => l.endsWith('# gbrain-maintain'))).toHaveLength(1);+ expect(crontab).toContain('0 1 * * * /usr/bin/true');+ out.length = 0;+ await runMaintainSchedule(['--unschedule', '--json'], env('linux'));+ expect(json()).toMatchObject({ status: 'removed' });+ expect(crontab).not.toContain('gbrain-maintain');+ expect(crontab).toContain('0 1 * * * /usr/bin/true');+ expect(existsSync(wrapper)).toBe(false);+ });++ test('--yes on a systemd host writes the service and timer and enables the timer', async () => {+ await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), systemdBooted: true });+ expect(json()).toMatchObject({ status: 'installed', target: 'linux-systemd' });+ const units = join(root, 'home', '.config', 'systemd', 'user');+ expect(readFileSync(join(units, 'gbrain-maintain.timer'), 'utf8')).toContain('OnCalendar=*-*-* 00/6:17:00');+ expect(readFileSync(join(units, 'gbrain-maintain.service'), 'utf8')).toContain('Type=oneshot');+ expect(calls).toContainEqual(['systemctl', '--user', 'enable', '--now', 'gbrain-maintain.timer']);+ expect(json().notes.join(' ')).toContain('loginctl enable-linger');+ });++ test('--yes on macOS writes the plist and bootstraps it in the user domain', async () => {+ await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('darwin'), uid: 501 });+ const plist = join(root, 'home', 'Library', 'LaunchAgents', 'com.gbrain.maintain.plist');+ expect(readFileSync(plist, 'utf8')).toContain('<key>StartInterval</key><integer>21600</integer>');+ expect(calls).toContainEqual(['launchctl', 'bootstrap', 'gui/501', plist]);+ });++ test('Windows installs nothing and prints the schtasks line', async () => {+ await runMaintainSchedule(['--schedule', '--yes', '--json'], env('win32'));+ expect(currentExitCode()).toBe(exitCodeForCode('schedule_unsupported'));+ const text = [...out, ...errOut].join('\n');+ expect(text).toContain('schedule_unsupported');+ expect(text).toContain('schtasks /Create /SC HOURLY /MO 6 /TN gbrain-maintain');+ expect(calls).toEqual([]);+ });++ test('a container installs nothing and names the resident serve as its runner', async () => {+ await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux', 'ephemeral-container' as ScheduleEnv['executionEnv']));+ const text = [...out, ...errOut].join('\n');+ expect(text).toContain('schedule_unsupported');+ expect(text).toContain('gbrain serve');+ expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);+ });++ test('a scheduled run exits 0 "serve owns upkeep" while a live serve owns the brain, without opening it', async () => {+ expect(await tryRunMaintainEngineFree(['--unattended', '--runner', 'schedule', '--json'], { liveServe: async () => true })).toBe(true);+ expect(currentExitCode()).toBe(0);+ expect(json()).toMatchObject({ status: 'skipped', exit: 0, code: 'maintenance_owned_by_serve' });+ expect(json().message).toContain('serve owns upkeep');+ expect(await tryRunMaintainEngineFree(['--unattended', '--runner', 'schedule'], { liveServe: async () => false })).toBe(false);+ expect(await tryRunMaintainEngineFree(['--unattended'], { liveServe: async () => true })).toBe(false);+ });+});diff --git a/test/maintenance-idle-gbra438.test.ts b/test/maintenance-idle-gbra438.test.tsnew file mode 100644index 0000000000..7f56190a2c--- /dev/null+++ b/test/maintenance-idle-gbra438.test.ts@@ -0,0 +1,168 @@+/**+ * GBRA-438 PR 2: the idle runner a serve calls (src/core/maintenance/idle.ts)+ * and the PGLite CHECKPOINT step, on a repo-less brain; the Postgres arm also+ * runs two serves against one brain.+ *+ * 1. Protects: an idle run does nothing when maintenance.auto is false or+ * upkeep is not due, records runner serve when it runs, hands its abort+ * signal into the work item, ends a finished PGLite round with a+ * CHECKPOINT step, and two serves sharing a brain run each global step+ * once while the other reports cycle_already_running.+ * 2. Fails when: an idle run ignores maintenance.auto, reruns a round that is+ * not due, drops the signal, skips the checkpoint on PGLite (or runs one on+ * Postgres), or both serves run the global steps.+ * 3. Real seams: runCycle and the gbrain-cycle lease on PGLite and Postgres;+ * the cycle seam only gates the first phase.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { runCycle, type CycleOpts } from '../src/core/cycle.ts';+import { readUpkeepRecord, unattendedPlan, type SafePhaseProviders } from '../src/core/maintenance/run.ts';+import { runIdleUpkeep } from '../src/core/maintenance/idle.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { checkUnattendedMaintenance } from '../src/commands/doctor/checks/unattended-maintenance.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const KEYLESS: SafePhaseProviders = { embedding: false, decideConflict: false, fenceRepairModel: false, contentRepairModel: false };+const quiet = () => new AbortController().signal;++for (const kind of testBackends()) {+ describe(`idle upkeep (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let databaseUrl = '';++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close, databaseUrl } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ });+ afterAll(async () => { await close(); });+ beforeEach(async () => {+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'maintenance.%' OR key = 'autopilot.last_global_at'");+ await engine.executeRaw('DELETE FROM pages');+ });++ test('maintenance.auto=false: nothing runs and nothing is recorded', async () => {+ await engine.setConfig('maintenance.auto', 'false');+ let cycles = 0;+ const outcome = await runIdleUpkeep(engine, { runner: 'serve', signal: quiet(), providers: KEYLESS, cycle: async (e, o) => { cycles++; return runCycle(e, o); } });+ expect(outcome).toBeNull();+ expect(cycles).toBe(0);+ expect(await readUpkeepRecord(engine)).toBeNull();+ });++ test('due: runs as runner serve; a second idle run is not due and does nothing', async () => {+ await engine.putPage('notes/alpha', { type: 'concept', title: 'Alpha', compiled_truth: 'Alpha relies on [[notes/beta]].' });+ const outcome = await runIdleUpkeep(engine, { runner: 'serve', signal: quiet(), providers: KEYLESS, budgetMs: 60_000 });+ expect(outcome).toMatchObject({ status: 'ran', record: { runner: 'serve', cursor: null } });+ expect((await readUpkeepRecord(engine))!.runner).toBe('serve');+ let cycles = 0;+ expect(await runIdleUpkeep(engine, { runner: 'serve', signal: quiet(), providers: KEYLESS, cycle: async (e, o) => { cycles++; return runCycle(e, o); } })).toBeNull();+ expect(cycles).toBe(0);+ });++ test(kind === 'pglite' ? 'a finished PGLite round ends with a CHECKPOINT step' : 'Postgres runs no CHECKPOINT step', async () => {+ const outcome = await runIdleUpkeep(engine, { runner: 'serve', signal: quiet(), providers: KEYLESS, budgetMs: 60_000 });+ const steps = outcome!.record!.steps;+ if (kind === 'pglite') expect(steps.at(-1)).toEqual({ name: 'checkpoint', scope: 'global', status: 'ok' });+ else expect(steps.map((s) => s.name)).not.toContain('checkpoint');+ });++ test('the abort signal reaches the work item: a request mid-item stops it and the round resumes later', async () => {+ const controller = new AbortController();+ let seen: AbortSignal | undefined;+ const outcome = await runIdleUpkeep(engine, {+ runner: 'serve', signal: controller.signal, providers: KEYLESS, budgetMs: 60_000,+ cycle: async (e, o: CycleOpts) => {+ seen = o.signal;+ setTimeout(() => controller.abort(), 10);+ await new Promise<void>((r) => o.signal!.addEventListener('abort', () => r()));+ return runCycle(e, o);+ },+ });+ expect(seen?.aborted).toBe(true);+ expect(outcome!.record!.cursor).not.toBeNull();+ expect(outcome!.record!.steps.map((s) => s.name)).not.toContain('checkpoint');+ });++ test('inside the extract phase: an abort mid-drain stops the repo-less stale link drain after one batch', async () => {+ for (let i = 0; i < 60; i++) await engine.putPage(`notes/p${i}`, { type: 'concept', title: `P${i}`, compiled_truth: `P${i} relies on [[notes/p${(i + 1) % 60}]].` });+ const controller = new AbortController();+ const list = engine.listStalePagesForExtraction.bind(engine);+ engine.listStalePagesForExtraction = (async (o: Parameters<typeof list>[0]) => { const rows = await list(o); controller.abort(); return rows; }) as typeof list;+ try {+ await runCycle(engine, { brainDir: null, pull: false, phases: ['extract'], stamp: 'none', sourceId: 'default', signal: controller.signal });+ } finally {+ engine.listStalePagesForExtraction = list;+ }+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM links');+ expect(controller.signal.aborted).toBe(true);+ expect(n).toBeGreaterThan(0);+ expect(n).toBeLessThanOrEqual(25);+ });++ test('inside extract_facts: the full page walk yields to timers, so an abort a timer trips stops it mid-walk', async () => {+ for (let i = 0; i < 120; i++) await engine.putPage(`walk/w${i}`, { type: 'concept', title: `W${i}`, compiled_truth: `W${i} is a plain page.` });+ const total = (await engine.getAllSlugs({ sourceId: 'default' })).size;+ const controller = new AbortController();+ const slugs = engine.getAllSlugs.bind(engine);+ engine.getAllSlugs = (async (o: Parameters<typeof slugs>[0]) => { const rows = await slugs(o); setTimeout(() => controller.abort(), 0); return rows; }) as typeof slugs;+ let scanned: number;+ try {+ scanned = (await runExtractFacts(engine, { sourceId: 'default', signal: controller.signal })).pagesScanned;+ } finally {+ engine.getAllSlugs = slugs;+ }+ expect(total).toBeGreaterThanOrEqual(120);+ expect(scanned).toBeLessThan(total);+ expect(scanned).toBeGreaterThan(0);+ expect(controller.signal.aborted).toBe(true);+ });++ test('an overdue doctor warn offers the opt-in schedule as the second option, consent persistent_install', async () => {+ const at = Date.now() - 72 * 60 * 60 * 1000;+ await engine.setConfig('maintenance.last_run', JSON.stringify({ at: new Date(at).toISOString(), runner: 'serve', status: 'ok', steps: [], held: [], cursor: null,+ next_due_at: new Date(at + 24 * 60 * 60 * 1000).toISOString(), consecutive_failures: [] }));+ const check = await checkUnattendedMaintenance(engine);+ expect(check).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'maintain', '--unattended'], consent: [] },+ details: { alternative_fix: { argv: ['gbrain', 'maintain', '--schedule'], consent: ['persistent_install'], preview_argv: ['gbrain', 'maintain', '--schedule', '--dry-run'] } } });+ expect(check.message).toContain('add the opt-in schedule with gbrain maintain --schedule');+ await engine.setConfig('maintenance.last_run', JSON.stringify({ at: new Date().toISOString(), runner: 'serve', status: 'ok', steps: [], held: [], cursor: null,+ next_due_at: new Date(Date.now() + 1000).toISOString(), consecutive_failures: [] }));+ expect((await checkUnattendedMaintenance(engine)).details).not.toHaveProperty('alternative_fix');+ });++ if (kind === 'postgres') {+ test('two serves on one repo-less brain: one runs each global step, the other reports cycle_already_running', async () => {+ const second = new PostgresEngine();+ await second.connect({ database_url: databaseUrl, poolSize: 2 } as never);+ try {+ let reached!: () => void;+ const inside = new Promise<void>((r) => { reached = r; });+ let release!: () => void;+ const held = new Promise<void>((r) => { release = r; });+ let gated = false;+ const first = runIdleUpkeep(engine, {+ runner: 'serve', signal: quiet(), providers: KEYLESS, budgetMs: 60_000,+ cycle: (e, o) => runCycle(e, { ...o, onPhaseStart: async () => { if (!gated) { gated = true; reached(); await held; } } }),+ });+ await inside;+ const other = await runIdleUpkeep(second, { runner: 'serve', signal: quiet(), providers: KEYLESS, budgetMs: 60_000 });+ expect(other).toMatchObject({ status: 'skipped', exit: 0, code: 'cycle_already_running' });+ release();+ const ran = await first;+ expect(ran).toMatchObject({ status: 'ran', record: { runner: 'serve', cursor: null } });+ for (const phase of unattendedPlan(KEYLESS).global) {+ expect(ran!.record!.steps.filter((s) => s.name === phase).map((s) => s.scope)).toEqual(['global']);+ }+ expect(await runIdleUpkeep(second, { runner: 'serve', signal: quiet(), providers: KEYLESS })).toBeNull();+ } finally {+ await second.disconnect();+ }+ }, 120_000);+ }+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 1cf5276a1c..db27bc8014 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -292,6 +292,7 @@ test/links-extraction-yield.test.tstest/list-jobs-row-bound.test.tstest/list-pages-empty-type-notice-gbra449.test.tstest/lower-tier-label-hold.test.ts+test/maintenance-idle-gbra438.test.tstest/maintenance-lowering-7917-7918.test.tstest/maintenance-trust-marker-7905.test.tstest/maintenance-unattended.test.tsdiff --git a/test/serve-http-route-runtime-golden.test.ts b/test/serve-http-route-runtime-golden.test.tsindex 93cd1461bd..51e60f8851 100644--- a/test/serve-http-route-runtime-golden.test.ts+++ b/test/serve-http-route-runtime-golden.test.ts@@ -163,6 +163,7 @@ const AST_TO_RUNTIME: Array<[RegExp, string]> = [[/^requireAdmin$/, 'requireAdmin'],[/^(ccRateLimiter|adminLimits\.(total|failures|consent)|ingestRateLimiter|githubWebhookLimiter)$/, 'rateLimit'],[/^authRouter$/, 'router'],+ [/^mcpForegroundMiddleware$/, 'mcpForegroundMiddleware'],[/^(<inline>|ipLimit|tokenLimit|mountOAuthCorsGate\(.*|metricsTrackingMiddleware\(.*|withBearerScopeHint\(.*|requireBearerAuth\(.*)$/, '<anonymous>'],];diff --git a/test/serve-idle-upkeep-gbra438.test.ts b/test/serve-idle-upkeep-gbra438.test.tsnew file mode 100644index 0000000000..ad9b6fa61c--- /dev/null+++ b/test/serve-idle-upkeep-gbra438.test.ts@@ -0,0 +1,235 @@+/**+ * GBRA-438 PR 2, done item 1: the resident serve runs free upkeep on its idle+ * tick, through the injected timer seam.+ *+ * 1. Protects: upkeep never runs at boot (the first tick only opens the+ * window), runs after the idle sweep and never beside it, never runs twice+ * at once, is aborted by stdin data, a warm CLI request or shutdown, is+ * skipped when a request arrived during the sweep, and is never armed on a+ * read-only (lean) Postgres serve. The HTTP serve gets the same tick, keyed+ * on POST /mcp activity, stopped when the server ends.+ * 2. Fails when: upkeep starts on the first tick, overlaps the sweep, keeps+ * running after a request, or a lean serve or an HTTP serve's GET stream+ * counts wrong.+ * 3. Seams: ServeOptions.setInterval / sweep / upkeep / runServeHttp, a stub+ * engine, and the real foreground-activity window.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { EventEmitter } from 'node:events';+import { runServe, type ServeOptions } from '../src/commands/serve.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { _resetStdoutRedirectForTests } from '../src/core/console-prefix.ts';+import { _resetForegroundActivityForTests, beginForegroundRequest, foregroundWindow, mcpForegroundMiddleware } from '../src/core/foreground-activity.ts';++/* eslint-disable no-console */+const realLog = console.log, realInfo = console.info, realDebug = console.debug;+afterEach(() => {+ console.log = realLog; console.info = realInfo; console.debug = realDebug;+ _resetStdoutRedirectForTests();+});+/* eslint-enable no-console */+beforeEach(() => { _resetForegroundActivityForTests(); });++function gate() {+ let open!: () => void;+ const promise = new Promise<void>((resolve) => { open = resolve; });+ return { promise, open };+}++async function until(pred: () => boolean, ms = 5_000): Promise<void> {+ const deadline = Date.now() + ms;+ while (!pred()) {+ if (Date.now() > deadline) throw new Error('condition not met');+ await new Promise((r) => setTimeout(r, 5));+ }+}++const engineOf = (kind: 'pglite' | 'postgres') =>+ ({ kind, disconnect: async () => {}, getConfig: async () => null, executeRaw: async () => [] }) as unknown as BrainEngine;++function harness() {+ const stdin = new EventEmitter();+ const signals = new EventEmitter();+ const timers: Array<() => void> = [];+ const cleared: unknown[] = [];+ const events: string[] = [];+ const runs: AbortSignal[] = [];+ let sweepGate = gate();+ let upkeepGate = gate();+ const opts: ServeOptions = {+ stdin: stdin as never, signals: signals as never, exit: () => {}, log: () => {}, startMcpServer: async () => {},+ getParentPid: () => 1, probeWatchdog: () => true,+ setInterval: (fn) => { timers.push(fn); return timers.length; }, clearInterval: (h) => { cleared.push(h); },+ mcpStdio: false, bootTimeoutMs: 0, sweepEnabled: true, factsDrain: false,+ sweep: async () => { events.push('sweep:start'); await sweepGate.promise; events.push('sweep:end'); },+ upkeep: async (_engine, signal) => {+ events.push('upkeep:start');+ runs.push(signal);+ await Promise.race([upkeepGate.promise, new Promise<void>((r) => signal.addEventListener('abort', () => r()))]);+ events.push(signal.aborted ? 'upkeep:aborted' : 'upkeep:end');+ },+ };+ return {+ stdin, signals, timers, cleared, events, runs, opts,+ tick: () => timers[0]!(),+ openSweep: () => { sweepGate.open(); sweepGate = gate(); },+ openUpkeep: () => { upkeepGate.open(); upkeepGate = gate(); },+ };+}++describe('stdio serve: idle upkeep on the idle tick', () => {+ test('never at boot: the first tick only opens the window; the second runs the sweep, then upkeep', async () => {+ const h = harness();+ await runServe(engineOf('pglite'), [], h.opts);+ expect(h.timers).toHaveLength(1);+ expect(h.events).toEqual([]);+ h.tick();+ await new Promise((r) => setTimeout(r, 20));+ expect(h.events).toEqual([]);+ h.tick();+ await until(() => h.events.includes('sweep:start'));+ expect(h.events).toEqual(['sweep:start']);+ h.openSweep();+ await until(() => h.events.includes('upkeep:start'));+ expect(h.events).toEqual(['sweep:start', 'sweep:end', 'upkeep:start']);+ h.openUpkeep();+ await until(() => h.events.includes('upkeep:end'));+ });++ test('never overlaps the sweep or itself: ticks while either runs start nothing', async () => {+ const h = harness();+ await runServe(engineOf('pglite'), [], h.opts);+ h.tick(); h.tick();+ await until(() => h.events.includes('sweep:start'));+ h.tick();+ await new Promise((r) => setTimeout(r, 20));+ expect(h.events).toEqual(['sweep:start']);+ h.openSweep();+ await until(() => h.events.includes('upkeep:start'));+ h.tick();+ await new Promise((r) => setTimeout(r, 20));+ expect(h.events).toEqual(['sweep:start', 'sweep:end', 'upkeep:start']);+ h.openUpkeep();+ await until(() => h.events.includes('upkeep:end'));+ expect(h.events.filter((e) => e === 'sweep:start')).toHaveLength(1);+ expect(h.events.filter((e) => e === 'upkeep:start')).toHaveLength(1);+ });++ test('stdin data aborts the run in flight', async () => {+ const h = harness();+ await runServe(engineOf('pglite'), [], h.opts);+ h.tick(); h.tick();+ await until(() => h.events.includes('sweep:start'));+ h.openSweep();+ await until(() => h.runs.length === 1);+ expect(h.runs[0]!.aborted).toBe(false);+ h.stdin.emit('data', Buffer.from('{}'));+ expect(h.runs[0]!.aborted).toBe(true);+ await until(() => h.events.includes('upkeep:aborted'));+ });++ test('a warm CLI socket request aborts the run in flight', async () => {+ const h = harness();+ await runServe(engineOf('pglite'), [], h.opts);+ h.tick(); h.tick();+ await until(() => h.events.includes('sweep:start'));+ h.openSweep();+ await until(() => h.runs.length === 1);+ beginForegroundRequest()();+ expect(h.runs[0]!.aborted).toBe(true);+ });++ test('shutdown aborts the run in flight', async () => {+ const h = harness();+ await runServe(engineOf('pglite'), [], h.opts);+ h.tick(); h.tick();+ await until(() => h.events.includes('sweep:start'));+ h.openSweep();+ await until(() => h.runs.length === 1);+ h.signals.emit('SIGTERM');+ expect(h.runs[0]!.aborted).toBe(true);+ });++ test('stdin data during the sweep skips upkeep for that tick', async () => {+ const h = harness();+ await runServe(engineOf('pglite'), [], h.opts);+ h.tick(); h.tick();+ await until(() => h.events.includes('sweep:start'));+ h.stdin.emit('data', Buffer.from('{}'));+ h.openSweep();+ await until(() => h.events.includes('sweep:end'));+ await new Promise((r) => setTimeout(r, 20));+ expect(h.events).toEqual(['sweep:start', 'sweep:end']);+ });++ test('a read-only (lean) Postgres serve arms no idle tick, so upkeep never runs', async () => {+ const h = harness();+ await runServe(engineOf('postgres'), ['--access', 'read-only'], h.opts);+ expect(h.timers).toHaveLength(0);+ expect(h.events).toEqual([]);+ });+});++describe('HTTP serve: the same idle tick, keyed on request activity', () => {+ function httpHarness() {+ const h = harness();+ const server = gate();+ const opts: ServeOptions = {+ ...h.opts, stallWatchdogMs: 0,+ runServeHttp: () => server.promise,+ armCorpusDrain: () => ({ tick: async () => {}, cancel: () => {} }),+ };+ return { ...h, opts, stopServer: server.open };+ }++ test('never at boot; a quiet window runs upkeep; a request aborts it; the tick stops with the server', async () => {+ const h = httpHarness();+ const served = runServe(engineOf('pglite'), ['--http'], h.opts);+ await until(() => h.timers.length === 1);+ h.tick();+ await new Promise((r) => setTimeout(r, 20));+ expect(h.events).toEqual([]);+ h.tick();+ await until(() => h.runs.length === 1);+ expect(h.events).toEqual(['upkeep:start']);+ h.tick();+ await new Promise((r) => setTimeout(r, 20));+ expect(h.runs).toHaveLength(1);+ beginForegroundRequest()();+ expect(h.runs[0]!.aborted).toBe(true);+ await until(() => h.events.includes('upkeep:aborted'));+ h.tick();+ await new Promise((r) => setTimeout(r, 20));+ expect(h.runs).toHaveLength(1);+ h.tick();+ await until(() => h.runs.length === 2);+ h.openUpkeep();+ h.stopServer();+ await served;+ expect(h.cleared).toContain(1);+ });++ test('GBRAIN_SWEEP=0 (the idle tick switch) arms no HTTP idle tick', async () => {+ const h = httpHarness();+ h.stopServer();+ await runServe(engineOf('pglite'), ['--http'], { ...h.opts, sweepEnabled: false });+ expect(h.timers).toHaveLength(0);+ });++ test('POST /mcp is foreground activity; GET /mcp (the event stream) is not', async () => {+ const window = foregroundWindow();+ window();+ const finish: Array<() => void> = [];+ let nexts = 0;+ mcpForegroundMiddleware({ method: 'GET' }, { once: (_e, fn) => finish.push(fn) }, () => { nexts++; });+ expect(window()).toBe(false);+ mcpForegroundMiddleware({ method: 'POST' }, { once: (_e, fn) => finish.push(fn) }, () => { nexts++; });+ expect(nexts).toBe(2);+ expect(window()).toBe(true);+ for (const fn of finish) fn();+ await new Promise((r) => setTimeout(r, 5));+ window();+ await new Promise((r) => setTimeout(r, 5));+ expect(window()).toBe(false);+ });+});diff --git a/test/sweep.test.ts b/test/sweep.test.tsindex fab7c3a661..416c95a667 100644--- a/test/sweep.test.ts+++ b/test/sweep.test.ts@@ -799,6 +799,7 @@ function makeServeHarness(opts: { sweepEnabled?: boolean; sweep?: (e: BrainEnginclearInterval: timers.clearInterval,mcpStdio: false,bootTimeoutMs: 0,+ upkeep: async () => {},...(opts.sweep ? { sweep: opts.sweep } : {}),...(opts.sweepEnabled !== undefined ? { sweepEnabled: opts.sweepEnabled } : {}),};